commit fa432bebdad4d49c5a89aa4e9fbc81fa1ea83b53 Author: Mateusz Gruszczyński Date: Sun Nov 22 14:21:54 2026 +0100 v0.1.0 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ae89693 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +target +.dev +dist +.git +fuzz/target +**/*.secret diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..946d8cc --- /dev/null +++ b/.gitignore @@ -0,0 +1,92 @@ +# --------------------------------------------------------------------------- +# EasyDNS .gitignore +# --------------------------------------------------------------------------- + +# --- Rust build output ----------------------------------------------------- +/target/ +**/target/ +**/*.rs.bk +*.pdb +# Cargo.lock IS committed: this workspace ships binaries (reproducible builds). + +# --- Packages and release artefacts (scripts/build-deb.sh, release.sh) ------ +/dist/ +*.deb +*.rpm +*.apk +*.tar.gz +*.tar.zst +*.zip +*.sha256 +# ...but not the Dockerfile that builds the .deb +!deploy/docker/Dockerfile.deb + +# --- Fuzzing (cargo-fuzz) --------------------------------------------------- +/fuzz/target/ +/fuzz/corpus/ +/fuzz/artifacts/ +/fuzz/coverage/ + +# --- Runtime state (never commit) ------------------------------------------- +# data_dir: secondary snapshots, IXFR journals, signed zones, API overlay, audit log +/data/ +data/ +*.jnl +*.journal +*.meta.json +api-overlay.yaml +audit.log +*.log +*.pid + +# --- Local development (dev.sh) --------------------------------------------- +/.dev/ +/tmp/ +.env +.env.* +!.env.example + +# --- Secrets: TSIG keys, API tokens, DNSSEC private keys, TLS keys ---------- +# Configs reference secrets as "file:..." or "env:..." – the files stay local. +*.secret +*.token +*.key +*.private +*.pem +*.p12 +*.pfx +K*.+*+*.private +dnssec-keys/ +!deploy/**/*.key.example +!deploy/**/*.secret.example + +# --- Profiling and benchmarks ----------------------------------------------- +perf.data +perf.data.old +flamegraph.svg +*.profraw +*.profdata +/benches/results/ +criterion/ + +# --- Editors and IDEs ------------------------------------------------------- +.idea/ +*.iml +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json.example +*.swp +*.swo +*~ +\#*\# +.#* +*.sublime-project +*.sublime-workspace +.fleet/ +.zed/ + +# --- OS files --------------------------------------------------------------- +.DS_Store +._* +Thumbs.db +desktop.ini diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..be36bd9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,94 @@ +# Changelog + +All notable changes follow [Keep a Changelog](https://keepachangelog.com/) and SemVer. + +## [Unreleased] + +### Changed + +- **Defaults**: hybrid mode listening on `0.0.0.0:53` and `[::1]:53`; recursion allowed for `192.168.0.0/16`, `10.0.0.0/8`, `127.0.0.1/32`, `::1/128`; the installed `/etc/easydns/config.yaml` is a ready hybrid node (previous example moved to `config/hybrid.yaml`). +- **Data directory** of packages, systemd unit and container: `/etc/easydns/data` (was `/var/lib/easydns`). Purging the package no longer deletes it. +- **Zone `file:` paths are relative to `data_dir`** (`file: zones/example.com.zone` → `/etc/easydns/data/zones/example.com.zone`); old configs with paths relative to the config directory still load. Secondary copies default to `/zones/secondary/`. +- **TSIG keys are optional everywhere**: examples, docs and `zone create` use IP ACLs; `check-config` no longer warns about secondaries without TSIG or update keys without an ACL. +- **API** default listener `127.0.0.1:9953` (was 8080). The server creates a local admin token (`/control.token`, 0640) that the CLI reads automatically – no key to generate or pass locally (`api.local_token`). +- DoH server rewritten on hyper: **HTTP/2** and HTTP/1.1 (ALPN), h2c behind a proxy, 100 streams per connection, body size/time limits. +- `[::]` listeners are IPv6-only (as in BIND), so `0.0.0.0:53` and `[::]:53` can be configured together; TCP listeners use SO_REUSEADDR. +- The server CLI is now `easydns` (short alias `edns`) instead of `mydns`. +- UDP: N sockets per listen address with SO_REUSEPORT (`server.udp_sockets`, default one per CPU, max 16), each with its own receive loop; `server.max_inflight` is now one server-wide limit. Socket buffers of 1 MiB are requested. +- Cache split into 16 independently locked shards; records are copied outside the lock. +- Rate limiter: client buckets in 16 shards, lock-free global limit (GCRA). +- **Default `rate_limit.global_qps` is now 0 (no server-wide cap)**; it was 100 000, which limited every server to 100 k QPS. Set it explicitly to keep a cap. +- Reload reports `server.udp_sockets`/`max_inflight` changes as requiring a restart. + +### Added + +- **Encoded-answer cache** (`cache.answer_entries`, default 20 000; `cache.answer_max_age`): repeated queries are answered by copying stored response bytes (ID, question case and TTLs patched); UDP hits are served inline in the receive loop. Key includes the client profile (view, recursion ACL, block-list exemption, client-specific forward rules, transport); TSIG queries are never cached; zone changes, expiry, reloads and cache flushes invalidate it immediately. Measured: 2.2× less server CPU per query for repeated names and for cached forwarder answers, 1.65× for a realistic authoritative mix. Metrics `dns_answer_cache_*`. +- Batched UDP receive/send on Linux (`recvmmsg`/`sendmmsg`, 32 packets per call) through `nix`'s safe wrappers; other systems keep one call per packet. +- Resolver **prefetch** (`cache.prefetch`, default on): popular entries are refreshed in the background shortly before expiry (recursion and forwarding); metric `dns_cache_prefetches_total`. +- `scripts/bench-vs-bind.sh`: EasyDNS vs BIND on the same machine and cores with dnsperf (zone, query mix and report generated). +- `easydns zone create` (alias of `zones create`): minimal valid zone (SOA, NS, glue, apex addresses) in `/zones/` plus its `zones.d/` definition; `--allow-transfer`, `--notify`, `--allow-update`, `--dry-run`, `--reload`. +- RFC 2136 without keys: `update_acl` (alias `allow_update`) alone authorises updates by source address (BIND `allow-update { IPs; }`). +- `update_policy`: BIND `update-policy` rules (`grant|deny name|subdomain|wildcard|zonesub|self|selfsub [name] [types]`), as strings or mappings; first match decides. +- BIND key files (`key "…" { algorithm …; secret "…"; };`) can be included unchanged; default config includes `keys.d/*.conf`. +- Persistent encrypted upstreams: DoT connection pool and multiplexed HTTP/2 DoH client (HTTP/1.1 fallback); `upstreams.tls_ca_file` for private CAs. +- TLS certificates (DoT/DoH) are re-read within 60 s after the files change; a broken pair is rejected and the old one kept. +- `edoh --http2`. +- Docs: step-by-step DNSSEC guide (key, signing, checks, DS/DNSKEY for the registrar, verification, rollover, safe disabling) in `docs/dnssec.md`; DNSSEC keys kept under `/etc/easydns/data/keys/`. +- Docs: `docs/secure-dns.md` (DoT/DoH server and secure forwarder), RFC 2136 section with a BIND translation in `docs/primary.md`, default installation layout. +- Tests: update policy + BIND key file + IP-only updates, BIND key parser, update rule parser, zone create, DoH HTTP/2 with 50 concurrent queries, DoT pool reuse, secure forwarder over DoT and DoH, certificate reload. +- Coalescing of identical in-flight resolutions (forwarder and recursion): concurrent cache misses for the same question share one upstream query. +- Tests: socket group, coalescing (burst of 40 → 1 upstream query, cancelled leader), cache sharding and concurrency, rate limiter bounds. +- `.gitignore` covering build output, packages, runtime state, secrets, editors and OS files. +- `include:` in the configuration: zone definitions, keys, ACLs and forward zones in separate files (`zones.d/*.yaml`). +- Docs: zone transfer variants (with/without TSIG), operations guide (master, name resolution), performance estimates vs BIND. +- `scripts/build-deb.sh` + `deploy/docker/Dockerfile.deb`: .deb packages built in Docker into `dist/`. +- `dev.sh`: developer runner (dev node, secondary, DNSSEC variant, queries, API, checks, e2e). +- `docs/migration-from-bind.md`, `docs/spec-gaps.md`. + +### Fixed + +- Upgrades: secondary zone copies kept by older versions in `/secondary/` are moved to `/zones/secondary/` on start, so `file: null` secondaries keep serving from their local copy instead of transferring again. +- Package upgrade restarts a running server only after the new version accepted the configuration (checked as the `easydns` user); previously the old binary kept running until a manual restart. +- Zone `file:` paths with `..` relative to `data_dir` failed while the data directory did not exist yet; paths are now normalised lexically. +- `easydns dnssec keygen`: key directory created 0700 and key file created 0600 from the start (it was briefly readable before `chmod`); when run as root both are owned by the data directory's owner (`easydns`), so the service can read the key. +- One-shot commands and tools no longer panic when their output pipe is closed early (`easydns … | head`); they exit with status 141 like classic Unix tools. +- DoT listener: TCP_NODELAY was not set, so every new DoT connection waited ~40 ms on delayed ACKs during the TLS handshake (measured 44 ms → 0.5 ms). +- DoH: a request announcing an oversized body could keep the connection waiting; it is now rejected at once (413) and the connection closed. +- `0.0.0.0:53` together with `[::]:53` failed with "address in use" on Linux. + +## [0.1.0] – 2026-11-21 + +First functionally complete release of all mandatory roles. + +### Added + +- Workspace with crates `dns-core`, `dns-config`, `dns-authoritative`, `dns-recursive`, + `dns-forwarder`, `dns-cache`, `dns-policy`, `dns-server`, `dns-api`, `dns-metrics`, + `dns-cli` (`easydns`) and `dns-tools`. +- Primary: BIND zone files, wildcard (RFC 4592), delegations and glue, empty non-terminals, + CNAME chains, AXFR, IXFR with persistent journal and AXFR-style fallback, NOTIFY with + retries, TSIG (RFC 8945, multi-message), transfer ACLs, RFC 2136 dynamic updates with + TSIG + ACL and audit log, atomic zone publication, serial strategies (increment/unixtime/date). +- Secondary: initial AXFR, IXFR with AXFR fallback, NOTIFY handling with ACL/TSIG, SOA + REFRESH/RETRY/EXPIRE timers, RFC 1982 serial arithmetic, persistent snapshot with atomic + replace, restart recovery, SERVFAIL after EXPIRE, transfer history. +- Recursive resolver: iterative resolution from root hints, bailiwick filtering, glueless + delegations, QNAME minimisation with fallback, budgets (queries, depth, CNAME chain, + deadline), server RTT tracking/back-off, RFC 2308 negative caching, serve-stale (opt-in). +- DNSSEC: online signing of primary zones (NSEC chain, Ed25519/ECDSA P-256/P-384, KSK/ZSK/CSK, + automatic re-signing, persisted signed zone), validating resolver (chain of trust from the + IANA root KSKs or configured anchors, NSEC and NSEC3 denial proofs, CD bit, AD bit). +- Forwarder: pools with round-robin/fastest/failover/random/priority, circuit breaker, + health checks, UDP/TCP/DoT/DoH upstreams, conditional forwarding per domain/client. +- Hybrid routing with per-route cache namespaces, split-horizon views, local-only names + (RFC 6761/6303), block/allow lists (exact, suffix, wildcard, bounded regex, hosts format). +- DoT and DoH (GET/POST) listeners; per-client and global rate limiting with RRL-style slip. +- REST API `/api/v1` with bearer tokens (admin/read-only), ETag/If-Match, pagination, + audit trail, OpenAPI document; `/metrics` in Prometheus format; hot reload with rollback + (SIGHUP or API); configuration precedence CLI > ENV > file > defaults. +- Tools: ed/easydig, eh/easyhost, ens/easynslookup, etrace, ednssec, eptr, ezone, econf, + ebench, ewhois, edoh, edot, ediff; shell completions and man page for `easydns`. +- Zone file pre-processor for DNSKEY/RRSIG/NSEC/NSEC3/NSEC3PARAM and RFC 3597 generic types. +- Deployment: Dockerfile, compose, hardened systemd unit, nfpm (.deb/.rpm) packaging, + install script with name-collision checks, CI workflow (fmt, clippy, tests, ARM64, musl, + macOS/Windows tools, cargo-deny), fuzz targets and a stable robustness test. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..5cbc769 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2279 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "clap_mangen" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3b6a8907b1723f211693e27b9af5899b86a9512ef5b08bd4a15b6bceb30da6d" +dependencies = [ + "clap", + "roff", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dns-api" +version = "0.1.0" +dependencies = [ + "axum", + "data-encoding", + "dns-authoritative", + "dns-cache", + "dns-config", + "dns-core", + "dns-metrics", + "dns-policy", + "dns-server", + "ring", + "serde", + "serde_json", + "serde_norway", + "tokio", + "tracing", +] + +[[package]] +name = "dns-authoritative" +version = "0.1.0" +dependencies = [ + "data-encoding", + "dns-config", + "dns-core", + "ipnet", + "rand 0.9.5", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "dns-cache" +version = "0.1.0" +dependencies = [ + "dns-config", + "dns-core", + "lru", + "serde", +] + +[[package]] +name = "dns-cli" +version = "0.1.0" +dependencies = [ + "clap", + "clap_complete", + "clap_mangen", + "dns-api", + "dns-authoritative", + "dns-config", + "dns-core", + "dns-metrics", + "dns-recursive", + "dns-server", + "serde_json", + "tokio", + "tracing", +] + +[[package]] +name = "dns-config" +version = "0.1.0" +dependencies = [ + "dns-core", + "ipnet", + "serde", + "serde_json", + "serde_norway", + "thiserror", +] + +[[package]] +name = "dns-core" +version = "0.1.0" +dependencies = [ + "bytes", + "data-encoding", + "hickory-proto", + "http-body-util", + "hyper", + "hyper-util", + "rand 0.9.5", + "rcgen", + "rustls", + "serde", + "serde_json", + "thiserror", + "tokio", + "tokio-rustls", + "tracing", + "webpki-roots", +] + +[[package]] +name = "dns-forwarder" +version = "0.1.0" +dependencies = [ + "dns-config", + "dns-core", + "rand 0.9.5", + "rustls", + "serde", + "tokio", + "tracing", +] + +[[package]] +name = "dns-metrics" +version = "0.1.0" +dependencies = [ + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "dns-policy" +version = "0.1.0" +dependencies = [ + "dns-config", + "dns-core", + "ipnet", + "regex", + "tracing", +] + +[[package]] +name = "dns-recursive" +version = "0.1.0" +dependencies = [ + "dns-authoritative", + "dns-cache", + "dns-config", + "dns-core", + "rand 0.9.5", + "serde", + "tokio", + "tracing", +] + +[[package]] +name = "dns-server" +version = "0.1.0" +dependencies = [ + "bytes", + "data-encoding", + "dns-authoritative", + "dns-cache", + "dns-config", + "dns-core", + "dns-forwarder", + "dns-metrics", + "dns-policy", + "dns-recursive", + "http-body-util", + "hyper", + "hyper-util", + "lru", + "nix", + "rcgen", + "rustls", + "serde", + "serde_json", + "socket2", + "tokio", + "tokio-rustls", + "tracing", +] + +[[package]] +name = "dns-tools" +version = "0.1.0" +dependencies = [ + "clap", + "data-encoding", + "dns-cache", + "dns-config", + "dns-core", + "dns-recursive", + "dns-server", + "rand 0.9.5", + "serde", + "serde_json", + "serde_norway", + "tokio", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hickory-proto" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +dependencies = [ + "bitflags", + "data-encoding", + "idna", + "ipnet", + "jni", + "once_cell", + "rand 0.10.4", + "ring", + "rustls-pki-types", + "thiserror", + "time", + "tinyvec", + "tracing", + "url", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +dependencies = [ + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roff" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_norway" +version = "0.9.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml-norway", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unsafe-libyaml-norway" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c5b0a1e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,63 @@ +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +license = "MIT" +repository = "https://example.invalid/easydns" +authors = ["EasyDNS contributors"] + +[workspace.dependencies] +hickory-proto = { version = "0.26.3", default-features = false, features = ["std", "dnssec-ring"] } +tokio = { version = "1.47", features = ["full"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_norway = "0.9" +thiserror = "2" +anyhow = "1" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } +ipnet = { version = "2", features = ["serde"] } +rand = "0.9" +lru = "0.16" +socket2 = { version = "0.6", features = ["all"] } +data-encoding = "2" +clap = { version = "4.5", features = ["derive", "env"] } +clap_complete = "4.5" +clap_mangen = "0.3" +axum = "0.8" +hyper = { version = "1", features = ["client", "server", "http1", "http2"] } +hyper-util = { version = "0.1", features = ["tokio", "server-auto", "http1", "http2"] } +http-body-util = "0.1" +bytes = "1" +idna = "1" +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"] } +webpki-roots = "1" +rcgen = "0.14" +dns-core = { path = "crates/dns-core" } +dns-config = { path = "crates/dns-config" } +dns-authoritative = { path = "crates/dns-authoritative" } +dns-cache = { path = "crates/dns-cache" } +dns-recursive = { path = "crates/dns-recursive" } +dns-forwarder = { path = "crates/dns-forwarder" } +dns-policy = { path = "crates/dns-policy" } +dns-server = { path = "crates/dns-server" } +dns-api = { path = "crates/dns-api" } +dns-metrics = { path = "crates/dns-metrics" } + +[workspace.lints.rust] +unsafe_code = "forbid" + +[workspace.lints.clippy] +unwrap_used = "warn" +expect_used = "warn" +# Style: nested `if let` blocks are kept for readability instead of let-chains. +collapsible_if = "allow" + +[profile.release] +lto = "thin" +codegen-units = 4 diff --git a/KNOWN_ISSUES.md b/KNOWN_ISSUES.md new file mode 100644 index 0000000..483cdf0 --- /dev/null +++ b/KNOWN_ISSUES.md @@ -0,0 +1,48 @@ +# Known issues and limitations (0.1.0) + +Items that are **not** implemented are listed explicitly; none of them is faked by a stub. + +## Not implemented +- **Web panel** – out of scope for the first versions (spec §15); the REST API covers all operations. +- **DNS-over-QUIC / DNS-over-HTTP/3** – the listener architecture (one task per transport + feeding `handler::handle`) is ready, the transports are not implemented. +- **NSEC3 signing** – the signer produces an NSEC chain. NSEC3 *validation* is implemented. +- **DNAME** – not supported by the zone parser or the resolver's chain following. +- **RFC 5011 automated trust-anchor rollover** – anchors are built in (IANA KSK-2017 and + KSK-2024) or loaded from `recursion.trust_anchors`; updating is manual. +- **Ed448** DNSSEC algorithm – zones signed only with Ed448 validate as *insecure*. +- **Persistent cache across restarts** (optional in the spec) – not implemented. +- **`$GENERATE`** in zone files, **RPZ** – see docs/migration-from-bind.md. +- `update_policy` rule types for Kerberos/GSS identities (`krb5-*`, `ms-*`), `tcp-self`, + `6to4-self`, `external` – reported as configuration errors. +- BIND `zone { … }` statements cannot be included directly (BIND **key** files can); + zone definitions are translated to YAML (docs/primary.md has a worked example). +- Upstream certificate pinning (SPKI hashes) for DoT/DoH – only CA-based verification. +- **Internationalised messages** – messages and documentation are English only; there is no translation catalogue. + +## Limitations +- Zone files changed through the API/DDNS are rewritten in canonical form; comments and + `$INCLUDE` structure of the original file are not preserved (a backup is advisable). +- `$INCLUDE`d files are parsed by the base parser only: DNSKEY/RRSIG/NSEC*/RFC 3597 records + must be in the main zone file. +- Views select which zones a client sees; recursion/forwarding policy is global (plus + per-forward-rule client ACLs), not per view. +- Changes of listen addresses, TLS settings, API/metrics listen and cache size need a + restart; a reload reports them in `restart_required` instead of silently ignoring them. +- Remote block lists are downloaded by `easydns blocklists update` (schedule it with the + provided systemd timer); the server never fetches URLs itself. +- IP-only dynamic updates (`update_acl` without keys) trust the UDP source address, which + can be spoofed on networks without ingress filtering – keep such lists to single hosts. +- DoH behind a TLS-terminating proxy sees the proxy's address (no `X-Forwarded-For`/PROXY + protocol support), so ACLs and rate limits apply to the proxy. +- Rate limiting is per client prefix (IPv4 /32, IPv6 /56) and optionally global; response-based RRL + (per qname/response) is not implemented. +- Query coalescing covers whole client questions; the resolver's internal lookups (NS addresses, DNSKEY/DS) are not de-duplicated. +- Multi-core throughput gains of SO_REUSEPORT, the sharded caches and the encoded-answer cache are estimated, not measured (only a 2-vCPU container was available); `scripts/bench-vs-bind.sh` was not run (no dnsperf/BIND in the development environment). +- Batched `recvmmsg`/`sendmmsg` showed no measurable gain at the low batch sizes the test generator produces; its benefit under real heavy load is expected, not measured. +- With `logging.query_log: true` the encoded-answer cache is bypassed (every query is logged), so query logging costs the full per-query path. +- Load figures in docs/testing.md come from a 2-vCPU container and are indicative only. +- .deb packages are built with `scripts/build-deb.sh` (Docker); this script, the Docker image, + the CI workflow and ARM64/macOS/Windows builds were not executed in the development + environment of this release. `scripts/e2e.sh` (comparison with BIND tools) was not run either. +- Full list with references to the specification: docs/spec-gaps.md. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..29665a3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 EasyDNS Mateusz Grusczyński [www.linuxiarz.pl] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 120000 index 0000000..7a694c9 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1 @@ +LICENSE \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f8d8154 --- /dev/null +++ b/README.md @@ -0,0 +1,271 @@ +# EasyDNS + +**EasyDNS** is a self-hosted DNS server for Linux written in Rust. One binary covers every +DNS role – authoritative **Primary** and **Secondary**, an iterative validating **Recursive +resolver**, a **Forwarder** and any **Hybrid** combination of them – and comes with the +**EasyDNS Tools**, practical replacements for `dig`, `host`, `nslookup`, `delv`, +`named-checkzone`, `named-checkconf` and `dnsperf`. + +> Migration from BIND: [docs/migration-from-bind.md](docs/migration-from-bind.md) · Specification gaps: [docs/spec-gaps.md](docs/spec-gaps.md) + +## Project status: 0.1.0 – beta, not yet production-certified + +All mandatory roles from the specification are implemented and covered by automated +tests (unit, integration with real servers on loopback, DNSSEC chains, DoT/DoH, API, CLI, +robustness – 97 test cases, `cargo clippy -D warnings` clean). **It has not yet been +verified in production conditions.** Before it can be called production-ready, the items +in [Production readiness](#production-readiness) must be completed. Until then use it: + +* in labs, staging and internal networks; +* in production **next to** an existing DNS server (extra secondary, a resolver for part of + the clients) with a rollback path; +* not as the only authoritative server of an important zone, and not as the only resolver + of a network. + +## Features + +### Authoritative – Primary (master) +* BIND-format zone files (`$ORIGIN`, `$TTL`, `$INCLUDE`, parentheses, all common types, + DNSKEY/RRSIG/NSEC/NSEC3 and RFC 3597 `\#` generic records) +* validation on load: SOA/NS at apex, CNAME conflicts, out-of-zone data, duplicates; lint + warnings (missing glue, MX/NS → CNAME, SOA timers) +* wildcards (RFC 4592), empty non-terminals, delegations with glue, DS at the cut, + additional-section processing, negative answers with SOA (RFC 2308) +* **atomic publication** – a query never sees a half-applied change +* AXFR, **IXFR** from a persistent journal with AXFR-style fallback, **NOTIFY** with retries +* transfers authorised by **IP ACL** (default, no key needed) with optional **TSIG** + (HMAC-SHA256/384/512, multi-message verification) – any combination +* **Dynamic DNS** (RFC 2136): by source IP without keys (BIND `allow-update`), by key, or + per-record **`update_policy`** rules in BIND syntax (`grant key zonesub TXT`, `name`, + `subdomain`, `wildcard`, `self`, `selfsub`); prerequisites, audit log +* **BIND key files** (`key "…" { algorithm …; secret "…"; };`) included unchanged +* `easydns zone create` – a valid minimal zone (SOA, NS, glue) and its definition in one command +* serial strategies: increment, unixtime, date (RFC 1982 arithmetic everywhere) +* **online DNSSEC signing**: Ed25519 / ECDSA P-256/P-384, KSK/ZSK/CSK, NSEC chain, + automatic re-signing, stable signatures across restarts, `easydns dnssec keygen|ds` + +### Authoritative – Secondary (slave) +* any number of zones, several primaries per zone with failover +* initial AXFR, IXFR with AXFR fallback, NOTIFY (ACL and/or TSIG) +* SOA REFRESH / RETRY / EXPIRE; after EXPIRE the zone answers SERVFAIL, never stale data +* complete validation of every transfer before an atomic swap; persistent snapshot, + restart without the primary; chaining (secondary of a secondary) +* status per zone (serial, source, last/next refresh, expiry, last error) in CLI, API, metrics + +### Recursive resolver +* real iteration from the root hints – no upstream resolver needed +* bailiwick checks, random IDs and source ports, glueless delegations, CNAME chains +* QNAME minimisation (RFC 9156), EDNS(0), UDP→TCP fallback, budgets and timeouts +* positive and negative cache (RFC 2308) with LRU bound, TTL clamping, optional serve-stale +* **DNSSEC validation**: chain of trust from the IANA root KSKs (or own anchors), + NSEC and NSEC3 proofs, secure / insecure / bogus / indeterminate, AD and CD bits +* recursion only for allowed clients (default: `192.168.0.0/16`, `10.0.0.0/8`, loopback) – no open resolver + +### Forwarder and hybrid routing +* upstreams over UDP, TCP, **DoT** (pooled persistent connections) and **DoH** (persistent, + multiplexed **HTTP/2**); private CAs; strategies round-robin, fastest, failover, random, + priority; health checks and circuit breaker; identical concurrent queries coalesced +* conditional forwarding per domain (and per client network), fallback to recursion +* hybrid: local zones → policy → forward zones → recursion/forwarding, with separate cache + namespaces; private names never leak to the Internet (RFC 6761/6303 local-only names) +* split-horizon **views**, block/allow lists (exact, suffix, wildcard, regex, hosts files) + +### Transport and security +* UDP/TCP (SO_REUSEPORT socket group per core), **DNS-over-TLS** and **DNS-over-HTTPS** + (GET/POST, **HTTP/2** and HTTP/1.1, h2c behind a proxy) listeners on rustls; + certificates reloaded automatically after renewal – guide: [docs/secure-dns.md](docs/secure-dns.md) +* per-client and optional global rate limiting with RRL-style slip, connection and in-flight limits +* secure defaults: no open recursion, transfers denied by default, API/metrics on loopback, + secrets only as `env:`/`file:` references, no `unsafe`, robustness test with 30 000 + malformed packets, hardened systemd unit and non-root container + +### Operations +* `config.yaml` (YAML/JSON) with **`include:`** for zone files (`zones.d/*.yaml`), + offline validation with file/line errors, precedence CLI > ENV > file +* **hot reload** (SIGHUP / CLI / API) with automatic rollback on errors +* **REST API** `/api/v1`: zones, records (ETag/If-Match), NOTIFY/sync, transfers, cache, + upstreams, policies, block lists, reload, audit, OpenAPI; admin and read-only tokens +* **Prometheus** metrics (low cardinality), JSON logs, optional privacy-friendly query log, + audit log, Grafana dashboard +* `easydns` / `edns` CLI: run, check-config, status, zone create, zones, cache, upstreams, + block lists, root hints, DNSSEC keys, completions, man page – works locally **without + generating or passing an API key** (local control token, API on `127.0.0.1:9953`) +* one directory for everything: `/etc/easydns` (config, `zones.d/`, `keys.d/`, `data/zones/`) +* packaging: `.deb` built in Docker (`scripts/build-deb.sh`), Dockerfile + compose, + systemd units, install script, developer runner `dev.sh` + +### EasyDNS Tools +| Short | Long | Replaces | +|---|---|---| +| `ed` | `easydig` | dig (+short, +trace, +dnssec, +tcp, -x, -y TSIG, AXFR, --json/--yaml, --watch, --compare, --benchmark) | +| `eh` | `easyhost` | host | +| `ens` | `easynslookup` | nslookup (incl. interactive mode) | +| `etrace` | `easytrace` | dig +trace | +| `ednssec` | `easydnssec` | delv | +| `eptr` | `easyptr` | dig -x (+ forward-confirmed check) | +| `ezone` | `easyzone` | named-checkzone | +| `econf` | `easyconf` | named-checkconf | +| `ebench` | `easybench` | dnsperf | +| `ewhois` | `easywhois` | whois (RDAP first) | +| `edoh` / `edot` | `easydoh` / `easydot` | DoH / DoT diagnostics | +| `ediff` | `easydiff` | compare resolvers (order-insensitive) | + +Short names are installed only when they do not collide with existing commands. + +## Quick start + +```bash +# development (from source, debug build, throw-away state in .dev/) +./dev.sh run # DNS 127.0.0.1:5353, API :9953, metrics :9090 +./dev.sh q www.example.com # query it with easydig +./dev.sh api /status + +# package +scripts/build-deb.sh --test # .deb built in Docker → dist/ +sudo apt install ./dist/easydns_0.1.0-1_amd64.deb +sudo easydns zone create example.com --ns ns1.example.com=192.0.2.10 --ip 192.0.2.80 +sudo systemctl enable --now easydns # hybrid: your zones + recursion for the LAN +sudo easydns status # no API key needed +``` + +The installed default ([config/config.yaml](config/config.yaml)): hybrid mode, +`0.0.0.0:53` + `[::1]:53`, recursion for `acl:lan`, zones in `/etc/easydns/data/zones/`, +definitions in `/etc/easydns/zones.d/`, BIND key files in `/etc/easydns/keys.d/`. + +Example configurations: [primary](config/primary.yaml), [secondary](config/secondary.yaml), +[resolver](config/resolver.yaml), [forwarder](config/forwarder.yaml), +[hybrid example](config/hybrid.yaml) with [zones.d](config/zones.d/). None of them needs a +TSIG key; keys are optional extras. + +## Production readiness + +EasyDNS will be declared production-ready (1.0) when all of the following are done and +documented in [docs/testing.md](docs/testing.md): + +- [ ] `scripts/e2e.sh` passes against real BIND tools (`dig`, `host`, `nslookup`) +- [ ] interoperability: BIND/Knot/PowerDNS primary → EasyDNS secondary and + EasyDNS primary → BIND secondary (AXFR, IXFR, NOTIFY, TSIG, signed zones) +- [ ] validating resolver tested on the real Internet (DNSSEC test domains, broken chains) +- [ ] 72-hour soak test at sustained load: no growth of memory, tasks or file descriptors +- [ ] `cargo fuzz` campaign (≥ 24 h per target) without findings +- [ ] `.deb` built and installed on Debian 12 / Ubuntu 22.04 & 24.04, amd64 and arm64; + systemd hardening verified; upgrade and rollback tested +- [ ] CI running (fmt, clippy, tests, cargo-deny, ARM64, musl) +- [ ] external security review of the parser, TSIG and the API +- [ ] at least one month as an additional secondary / partial resolver in a real network + +## Roadmap + +**0.2 – verification and hardening** (the list above), plus fixes found on the way. + +**0.3 – performance** ([estimates vs BIND](docs/performance.md)) +* ✅ done (Unreleased): SO_REUSEPORT socket group per core, sharded cache and rate limiter, query coalescing +* ✅ done (Unreleased): encoded-answer cache with inline UDP fast path (2.2× / 1.65× less CPU per query), + batched `recvmmsg`/`sendmmsg` on Linux, resolver prefetch +* multi-core benchmark against BIND: `scripts/bench-vs-bind.sh` (to be run on 8+ cores) +* cache-miss path: allocation-free parsing, pre-encoded RRsets +* compact zone storage for large zones (faster loading, less memory) +* resolver: aggressive NSEC/NSEC3 (RFC 8198) + +**0.4 – DNS features** +* NSEC3 signing, automated key rollover (ZSK/KSK), CDS/CDNSKEY, RFC 5011 trust anchors +* DNAME, `$GENERATE`, Ed448 +* RPZ (response policy zones), per-subnet and per-record-type policies, response RRL +* ✅ done (Unreleased): `update-policy`-style DDNS rules, IP-only updates, BIND key files +* UPDATE forwarding from secondaries; reading BIND `zone { … }` statements directly +* per-view recursion/forwarding policy, catalog zones (RFC 9432) for provisioning secondaries + +**0.5 – transports and operations** +* ✅ done (Unreleased): DoH over HTTP/2 (server and client), persistent DoT/DoH upstream + connections, automatic certificate reload +* DNS-over-QUIC (RFC 9250), DoH3, upstream certificate pinning +* API: token management endpoints, JWT/mTLS, users; UNIX socket for the CLI +* persistent cache, built-in block list scheduler, backup/restore commands +* message translations (i18n), man pages for every tool, `.rpm` packages + +**Later** +* web panel (separate project, on top of the REST API) +* database backends (PostgreSQL/SQLite) for very large or multi-tenant deployments +* clustering helpers (multi-primary with catalog zones), anycast health integration + +## Query flow + +```mermaid +flowchart TD + Q[query UDP/TCP/DoT/DoH] --> P{parse ok?} + P -- no --> FE[FORMERR] + P -- yes --> RL{rate limit} + RL -- exceeded --> D[drop / TC=1 slip] + RL -- ok --> TS{TSIG valid?} + TS -- invalid --> NA[NOTAUTH] + TS --> OP{opcode} + OP -- NOTIFY --> N[secondary refresh] + OP -- UPDATE --> U[RFC 2136 on primary] + OP -- QUERY --> X{AXFR/IXFR?} + X -- yes --> XA[ACL + TSIG → transfer] + X -- no --> Z{local zone in client view?} + Z -- yes --> AA[authoritative answer AA=1] + Z -- no --> R{client allowed to recurse?} + R -- no --> REF[REFUSED] + R -- yes --> L{local-only / blocked?} + L -- yes --> NX[NXDOMAIN / policy answer] + L -- no --> F{forward zone match?} + F -- yes --> FW[forwarder pool + cache ns] + F -- no --> DEF[default: recursive / forward / refuse] + DEF --> V[DNSSEC validation → AD / SERVFAIL] +``` + +## NOTIFY → IXFR/AXFR + +```mermaid +sequenceDiagram + participant A as Admin (API/DDNS/file) + participant P as Primary + participant S as Secondary + A->>P: change zone + P->>P: bump serial, validate, write file, journal diff, atomic swap + P->>S: NOTIFY (IP ACL, optional TSIG) + S->>P: SOA? + P-->>S: SOA serial N+1 + S->>P: IXFR from N (TCP) + P-->>S: diff N→N+1 (or AXFR-style if journal too short) + alt IXFR fails + S->>P: AXFR + end + S->>S: validate, atomic swap, persist snapshot +``` + +## Security defaults + +No open resolver (recursion only for private LAN ranges and loopback unless configured), +zone transfers and dynamic updates denied unless allowed by IP ACL and/or key, API on +loopback with mandatory tokens (the local one is created with mode 0640 for the CLI), +metrics on loopback, secrets as `env:`/`file:` references or BIND key files with +restricted permissions, runs unprivileged with `CAP_NET_BIND_SERVICE`. Details: [docs/security.md](docs/security.md). + +## Documentation + +[architecture](docs/architecture.md) · [configuration](docs/configuration.md) · +[primary](docs/primary.md) · [secondary](docs/secondary.md) · [recursive](docs/recursive.md) · +[forwarder](docs/forwarder.md) · [hybrid](docs/hybrid.md) · [dnssec](docs/dnssec.md) · +[security](docs/security.md) · [api](docs/api.md) · [cli-tools](docs/cli-tools.md) · +[monitoring](docs/monitoring.md) · [deployment](docs/deployment.md) · +[troubleshooting](docs/troubleshooting.md) · [testing](docs/testing.md) · +[**migration from BIND**](docs/migration-from-bind.md) · [spec gaps](docs/spec-gaps.md) · +[**operations: master & resolution**](docs/operations.md) · [**zone transfer variants**](docs/zone-transfer-variants.md) · +[**performance vs BIND (estimates)**](docs/performance.md) · +[**encrypted DNS: DoT/DoH**](docs/secure-dns.md) + +## Tests + +```bash +cargo fmt --all -- --check +cargo clippy --workspace --all-targets --all-features -- -D warnings +cargo test --workspace --all-features +cargo build --workspace --release +./dev.sh e2e # release build + scripts/e2e.sh (needs dig/host/nslookup) +``` + +## License + +MIT – see [LICENSE](LICENSE). diff --git a/benches/README.md b/benches/README.md new file mode 100644 index 0000000..ce7160b --- /dev/null +++ b/benches/README.md @@ -0,0 +1,13 @@ +# Benchmarks + +Load tests use `easybench` against a running server you own: + +```bash +cargo build --release +target/release/easydns run -c config/config.yaml & +target/release/easybench 127.0.0.1:5353 -n www.example.com --qps 0 --duration 30s -c 50 --i-own-this-server +target/release/easybench 127.0.0.1:5353 -d queries.txt --qps 10000 --duration 60s -c 100 --i-own-this-server --json +``` + +Report hardware, CPU, RSS (`curl -s localhost:9090/metrics | grep process_resident`), +p50/p95/p99, loss and cache hit ratio. Results so far: docs/testing.md. diff --git a/ci/github-actions-ci.yml b/ci/github-actions-ci.yml new file mode 100644 index 0000000..b9defab --- /dev/null +++ b/ci/github-actions-ci.yml @@ -0,0 +1,54 @@ +name: CI +on: + push: + pull_request: +env: + CARGO_TERM_COLOR: always +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: { components: "rustfmt, clippy" } + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --all -- --check + - run: cargo clippy --workspace --all-targets --all-features -- -D warnings + - run: cargo test --workspace --all-features + - run: cargo build --workspace --release + - name: e2e with BIND tools + run: | + sudo apt-get update && sudo apt-get install -y dnsutils + ./scripts/e2e.sh + - name: secret scan (no keys committed) + run: "! grep -rEn --include='*.yaml' --include='*.yml' 'secret: \"base64:' config/ deploy/" + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - run: cargo install cargo-deny --locked + - run: cargo deny check + arm64: + runs-on: ubuntu-24.04-arm + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - run: cargo build --workspace --release + - run: cargo test --workspace + musl: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: { targets: x86_64-unknown-linux-musl } + - run: sudo apt-get update && sudo apt-get install -y musl-tools + - run: cargo build --release --target x86_64-unknown-linux-musl -p dns-cli -p dns-tools + tools-cross-platform: + strategy: + matrix: { os: [macos-latest, windows-latest] } + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - run: cargo build --release -p dns-tools diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..a63662a --- /dev/null +++ b/compose.yaml @@ -0,0 +1,33 @@ +# docker compose up -d (config in ./config, state in a named volume) +services: + easydns: + build: + context: . + dockerfile: deploy/docker/Dockerfile + image: easydns:latest + restart: unless-stopped + ports: + - "53:53/udp" + - "53:53/tcp" + # - "853:853/tcp" # DoT + - "127.0.0.1:9953:9953" # REST API – loopback only + - "127.0.0.1:9090:9090" # metrics – loopback only + environment: + EASYDNS_LISTEN: "0.0.0.0:53" + EASYDNS_API_LISTEN: "0.0.0.0:9953" + EASYDNS_DATA_DIR: /etc/easydns/data + # secrets via env files, never in the image: + # DNS_TSIG_XFR: ... + env_file: + - path: ./deploy/docker/easydns.env + required: false + volumes: + - ./config:/etc/easydns:ro + - ./zones:/etc/easydns/data/zones + - easydns-data:/etc/easydns/data + read_only: true + cap_drop: [ALL] + cap_add: [NET_BIND_SERVICE] + security_opt: ["no-new-privileges:true"] +volumes: + easydns-data: {} diff --git a/config/config.yaml b/config/config.yaml new file mode 100644 index 0000000..5288fe6 --- /dev/null +++ b/config/config.yaml @@ -0,0 +1,70 @@ +# EasyDNS – default configuration, installed as /etc/easydns/config.yaml. +# +# Hybrid node: authoritative for your own zones + recursive resolver for the LAN. +# check: easydns check-config +# new zone: easydns zone create example.com --ns ns1.example.com --ip 192.0.2.1 +# reload: easydns reload (or: systemctl reload easydns) +# status: easydns status (no API key needed – see api.local_token) + +# Zone definitions (one file per zone) and TSIG keys (BIND `key "..." { ... };` files can +# be copied here unchanged). +include: ["zones.d/*.yaml", "keys.d/*.conf"] + +server: + mode: hybrid + listen: ["0.0.0.0:53", "[::1]:53"] + udp: true + tcp: true + data_dir: /etc/easydns/data # zone files in data/zones/, secondary copies, journals + max_udp_payload: 1232 + +logging: + level: info # error | warn | info | debug | trace + format: text # text | json + query_log: false # per-query logs are off by default (privacy) + anonymize_clients: true + +acls: + lan: ["192.168.0.0/16", "10.0.0.0/8", "127.0.0.1/32"] # add 172.16.0.0/12 if you use it + +recursion: + enabled: true + allowed_clients: ["acl:lan", "::1/128"] # never make this "any" (open resolver) + qname_minimization: true + dnssec_validation: true + +resolution: + default: recursive # recursive | forward | forwardthenrecursive | refuse +# Encrypted forwarding instead of recursion (DNS-over-TLS to public resolvers): +# resolution: { default: forward } +# upstreams: +# strategy: fastest +# servers: ["tls://1.1.1.1:853#cloudflare-dns.com", "tls://9.9.9.9:853#dns.quad9.net"] + +# DNS-over-TLS (853) and DNS-over-HTTPS (443, HTTP/2 and HTTP/1.1) for your clients: +# tls: +# cert_file: /etc/letsencrypt/live/dns.example.com/fullchain.pem +# key_file: /etc/letsencrypt/live/dns.example.com/privkey.pem +# dot_listen: ["0.0.0.0:853"] +# doh_listen: ["0.0.0.0:443"] + +cache: + enabled: true + max_entries: 100000 + +rate_limit: + enabled: true + per_client_qps: 200 + burst: 400 + exempt_clients: ["acl:lan"] + +api: + enabled: true + listen: "127.0.0.1:9953" # loopback only, non-standard port + local_token: true # CLI works out of the box (token in data_dir, mode 0640) + # tokens: # extra tokens for remote tools / automation + # - { name: admin, role: admin, token: "file:/etc/easydns/api.token" } + +metrics: + enabled: true + listen: "127.0.0.1:9090" diff --git a/config/forwarder.yaml b/config/forwarder.yaml new file mode 100644 index 0000000..e3fc539 --- /dev/null +++ b/config/forwarder.yaml @@ -0,0 +1,9 @@ +# Forwarder with DoT upstreams and conditional forwarding +server: { mode: forwarder, listen: ["127.0.0.1:53"], data_dir: /etc/easydns/data } +recursion: { allowed_clients: ["127.0.0.0/8", "::1/128", "192.168.0.0/16"] } +upstreams: + strategy: fastest + servers: ["tls://1.1.1.1#cloudflare-dns.com", "tls://9.9.9.9#dns.quad9.net", "1.0.0.1:53"] +forward_zones: + - { domain: corp.internal, upstreams: ["192.168.1.1:53"] } +resolution: { default: forward } diff --git a/config/hybrid.yaml b/config/hybrid.yaml new file mode 100644 index 0000000..fef984e --- /dev/null +++ b/config/hybrid.yaml @@ -0,0 +1,78 @@ +# EasyDNS example configuration (hybrid node). All addresses are documentation/test ranges. +# Validate with: easydns check-config -c config/hybrid.yaml (or: econf check config/hybrid.yaml) +# Zone definitions can live in separate files (like BIND `include`): +include: ["zones.d/*.yaml"] + +server: + mode: hybrid + listen: ["127.0.0.1:5353", "[::1]:5353"] + udp: true + tcp: true + data_dir: ../data # secondary snapshots, IXFR journals, audit log + max_udp_payload: 1232 + +logging: + level: info # error | warn | info | debug | trace + format: text # text | json + query_log: false # per-query logs are off by default (privacy) + anonymize_clients: true + +# TSIG keys are optional. Zone transfers below are authorised by IP address only. +# To also require a key, uncomment and add `transfer_tsig_key: xfr-key` to the zone: +# keys: +# - name: xfr-key +# algorithm: hmac-sha256 +# secret: "env:DNS_TSIG_XFR" # generate: head -c 32 /dev/urandom | base64 + +acls: + lan: ["192.168.0.0/16", "10.0.0.0/8"] + +recursion: + enabled: true + root_hints: root.hints + allowed_clients: ["127.0.0.0/8", "::1/128", "acl:lan"] + qname_minimization: true + dnssec_validation: false + +zones: + - name: example.com + type: primary + file: ../zones/example.com.zone # relative to data_dir + transfer_acl: ["127.0.0.1/32"] # secondaries allowed to AXFR/IXFR (IP only) + # transfer_tsig_key: xfr-key # optional: also require a TSIG key + notify: [] # e.g. ["192.168.1.20:53"] + - name: 2.0.192.in-addr.arpa + type: primary + file: ../zones/2.0.192.in-addr.arpa.zone # relative to data_dir + +forward_zones: + - domain: corp.internal + upstreams: ["192.168.1.1:53", "192.168.1.2:53"] + strategy: failover + +upstreams: + strategy: fastest + servers: ["1.1.1.1:53", "9.9.9.9:53"] + +resolution: + default: recursive # recursive | forward | forwardthenrecursive | refuse + +cache: + enabled: true + max_entries: 100000 + +rate_limit: + enabled: true + per_client_qps: 200 + burst: 400 + +api: + enabled: true + listen: "127.0.0.1:9953" + auth_required: true + tokens: + - { name: admin, role: admin, token: "env:EASYDNS_ADMIN_TOKEN" } + +metrics: + enabled: true + listen: "127.0.0.1:9090" diff --git a/config/primary.yaml b/config/primary.yaml new file mode 100644 index 0000000..28465a5 --- /dev/null +++ b/config/primary.yaml @@ -0,0 +1,17 @@ +# Minimal authoritative primary (master). +# Transfers are authorised by secondary IP addresses; a TSIG key is optional (see below). +server: { mode: primary, listen: ["0.0.0.0:53", "[::]:53"], data_dir: /etc/easydns/data } +zones: + - name: example.com + type: primary + file: zones/example.com.zone # = /etc/easydns/data/zones/example.com.zone + transfer_acl: ["192.168.1.20/32"] # secondaries allowed to AXFR/IXFR + notify: ["192.168.1.20:53"] # send NOTIFY after every change +resolution: { default: refuse } + +# Optional – also require a TSIG key for transfers: +# keys: +# - { name: xfr-key, algorithm: hmac-sha256, secret: "file:/etc/easydns/keys/xfr-key.secret" } +# and in the zone: +# transfer_tsig_key: xfr-key +# notify_tsig_key: xfr-key diff --git a/config/resolver.yaml b/config/resolver.yaml new file mode 100644 index 0000000..a3f4d34 --- /dev/null +++ b/config/resolver.yaml @@ -0,0 +1,8 @@ +# Validating recursive resolver for a LAN (no upstream resolver required) +server: { mode: recursive, listen: ["0.0.0.0:53", "[::]:53"], data_dir: /etc/easydns/data } +recursion: + enabled: true + allowed_clients: ["127.0.0.0/8", "::1/128", "192.168.0.0/16"] + qname_minimization: true +resolution: { default: recursive } +cache: { max_entries: 200000 } diff --git a/config/root.hints b/config/root.hints new file mode 100644 index 0000000..b9f7eb6 --- /dev/null +++ b/config/root.hints @@ -0,0 +1,41 @@ +; Root name server hints (IANA named.root). Update with: easydns root-hints update +; or download https://www.internic.net/domain/named.root and verify its signature. +. 3600000 NS A.ROOT-SERVERS.NET. +A.ROOT-SERVERS.NET. 3600000 A 198.41.0.4 +A.ROOT-SERVERS.NET. 3600000 AAAA 2001:503:ba3e::2:30 +. 3600000 NS B.ROOT-SERVERS.NET. +B.ROOT-SERVERS.NET. 3600000 A 170.247.170.2 +B.ROOT-SERVERS.NET. 3600000 AAAA 2801:1b8:10::b +. 3600000 NS C.ROOT-SERVERS.NET. +C.ROOT-SERVERS.NET. 3600000 A 192.33.4.12 +C.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:2::c +. 3600000 NS D.ROOT-SERVERS.NET. +D.ROOT-SERVERS.NET. 3600000 A 199.7.91.13 +D.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:2d::d +. 3600000 NS E.ROOT-SERVERS.NET. +E.ROOT-SERVERS.NET. 3600000 A 192.203.230.10 +E.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:a8::e +. 3600000 NS F.ROOT-SERVERS.NET. +F.ROOT-SERVERS.NET. 3600000 A 192.5.5.241 +F.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:2f::f +. 3600000 NS G.ROOT-SERVERS.NET. +G.ROOT-SERVERS.NET. 3600000 A 192.112.36.4 +G.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:12::d0d +. 3600000 NS H.ROOT-SERVERS.NET. +H.ROOT-SERVERS.NET. 3600000 A 198.97.190.53 +H.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:1::53 +. 3600000 NS I.ROOT-SERVERS.NET. +I.ROOT-SERVERS.NET. 3600000 A 192.36.148.17 +I.ROOT-SERVERS.NET. 3600000 AAAA 2001:7fe::53 +. 3600000 NS J.ROOT-SERVERS.NET. +J.ROOT-SERVERS.NET. 3600000 A 192.58.128.30 +J.ROOT-SERVERS.NET. 3600000 AAAA 2001:503:c27::2:30 +. 3600000 NS K.ROOT-SERVERS.NET. +K.ROOT-SERVERS.NET. 3600000 A 193.0.14.129 +K.ROOT-SERVERS.NET. 3600000 AAAA 2001:7fd::1 +. 3600000 NS L.ROOT-SERVERS.NET. +L.ROOT-SERVERS.NET. 3600000 A 199.7.83.42 +L.ROOT-SERVERS.NET. 3600000 AAAA 2001:500:9f::42 +. 3600000 NS M.ROOT-SERVERS.NET. +M.ROOT-SERVERS.NET. 3600000 A 202.12.27.33 +M.ROOT-SERVERS.NET. 3600000 AAAA 2001:dc3::35 diff --git a/config/secondary.yaml b/config/secondary.yaml new file mode 100644 index 0000000..dfb52ae --- /dev/null +++ b/config/secondary.yaml @@ -0,0 +1,17 @@ +# Minimal authoritative secondary (slave). +# The primary authorises this server by its IP address; a TSIG key is optional (see below). +server: { mode: secondary, listen: ["0.0.0.0:53", "[::]:53"], data_dir: /etc/easydns/data } +zones: + - name: example.com + type: secondary + primaries: ["192.168.1.10:53"] + allow_notify: ["192.168.1.10/32"] # default: the primaries' addresses + transfer: { prefer: ixfr, fallback_axfr: true } + # copy kept in /etc/easydns/data/zones/secondary/example.com.zone +resolution: { default: refuse } + +# Optional – sign transfer requests with a TSIG key (the primary must require the same key): +# keys: +# - { name: xfr-key, algorithm: hmac-sha256, secret: "file:/etc/easydns/keys/xfr-key.secret" } +# and in the zone: +# transfer: { prefer: ixfr, fallback_axfr: true, tsig_key: xfr-key } diff --git a/config/zones.d/10-example.org.yaml b/config/zones.d/10-example.org.yaml new file mode 100644 index 0000000..79030d0 --- /dev/null +++ b/config/zones.d/10-example.org.yaml @@ -0,0 +1,6 @@ +# Plain list form: one or more zone definitions. +- name: example.org + type: secondary + primaries: ["192.0.2.53:53"] + allow_notify: ["192.0.2.53/32"] + transfer: { prefer: ixfr, fallback_axfr: true } # IP-only variant (no TSIG) diff --git a/config/zones.d/20-example.net.yaml b/config/zones.d/20-example.net.yaml new file mode 100644 index 0000000..6e0b703 --- /dev/null +++ b/config/zones.d/20-example.net.yaml @@ -0,0 +1,11 @@ +# Mapping form: may also define keys, ACLs, forward zones and nested includes. +acls: + example-net-primaries: ["198.51.100.10/32", "2001:db8:100::10/128"] +zones: + - name: example.net + type: secondary + primaries: ["198.51.100.10:53", "[2001:db8:100::10]:53"] + allow_notify: ["acl:example-net-primaries"] + transfer: { prefer: ixfr, fallback_axfr: true } + # optional TSIG: define `keys: [ { name: example-net-xfr, secret: "env:..." } ]` + # above and add `tsig_key: example-net-xfr` to `transfer:` diff --git a/config/zones.d/README.md b/config/zones.d/README.md new file mode 100644 index 0000000..b41cd3b --- /dev/null +++ b/config/zones.d/README.md @@ -0,0 +1,4 @@ +Zone definitions included by `config/config.yaml` (`include: ["zones.d/*.yaml"]`). +One file per zone or per customer; files are read in alphabetical order, hidden files +and `*~` backups are ignored. Relative `file:` paths are resolved against the directory +of the main configuration file. diff --git a/crates/dns-api/Cargo.toml b/crates/dns-api/Cargo.toml new file mode 100644 index 0000000..43330ad --- /dev/null +++ b/crates/dns-api/Cargo.toml @@ -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 diff --git a/crates/dns-api/src/auth.rs b/crates/dns-api/src/auth.rs new file mode 100644 index 0000000..8dbc1aa --- /dev/null +++ b/crates/dns-api/src/auth.rs @@ -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, + acl: Acl, + rpm: u32, + buckets: Mutex>, +} + +/// 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 { + 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 { + 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>, ConnectInfo(peer): ConnectInfo, 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 +} diff --git a/crates/dns-api/src/handlers.rs b/crates/dns-api/src/handlers.rs new file mode 100644 index 0000000..c99c01f --- /dev/null +++ b/crates/dns-api/src/handlers.rs @@ -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>; + +fn ok(v: Value) -> Response { + Json(v).into_response() +} + +fn zone_entry(st: &ApiState, zone: &str) -> Result, 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 = 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::>(), + "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::>(), + "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, + per_page: Option, + name: Option, + #[serde(rename = "type")] + rtype: Option, + kind: Option, +} + +fn paginate(items: &[T], p: &Page) -> (Vec, 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) -> Response { + let rt = st.server.shared.rt(); + let all: Vec = 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) -> 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, + #[serde(default)] + ns: Vec, + hostmaster: Option, + #[serde(default)] + transfer_acl: Vec, + #[serde(default)] + notify: Vec, +} + +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 { + 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, Json(b): Json) -> 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, + Path(zone): Path, + h: HeaderMap, + Json(b): Json, +) -> 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, Path(zone): Path) -> 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, Query(p): Query) -> 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 = 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 { + 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 { + 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, + h: &HeaderMap, + removed: Vec, + added: Vec, + 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::>() }); + 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, + Path(zone): Path, + h: HeaderMap, + Json(b): Json, +) -> 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, + Path((zone, id)): Path<(String, String)>, + h: HeaderMap, + Json(b): Json, +) -> 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, + 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, Path(zone): Path) -> 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, Path(zone): Path) -> 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) -> 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, +} + +pub async fn cache_clear(State(st): St, Extension(c): Extension, Query(q): Query) -> 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::>() })); + } + 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::>() })); + } + ok(json!({ "items": groups })) +} + +#[derive(Deserialize)] +pub struct NewUpstream { + address: String, +} + +pub async fn upstreams_add(State(st): St, Extension(c): Extension, Json(b): Json) -> 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>, + block_action: Option, +} + +pub async fn policies_put(State(st): St, Extension(c): Extension, Json(b): Json) -> 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, Json(b): Json) -> 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) -> 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, +} + +pub async fn audit_tail(State(st): St, Query(q): Query) -> 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, +} + +/// Run a query through this server (convenience for `easydns query`). +pub async fn api_query(State(st): St, Query(q): Query) -> 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::>(), + "authority": ex.message.authorities.iter().map(record_json).collect::>(), + "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 +} diff --git a/crates/dns-api/src/lib.rs b/crates/dns-api/src/lib.rs new file mode 100644 index 0000000..e2bf0d9 --- /dev/null +++ b/crates/dns-api/src/lib.rs @@ -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:` 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, + pub auth: auth::Auth, +} + +/// Build the API router. +pub fn router(state: Arc) -> 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, addr: SocketAddr, mut shutdown: watch::Receiver) -> Result { + 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::(); + 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, addr: SocketAddr, mut shutdown: watch::Receiver) -> Result { + 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) +} diff --git a/crates/dns-api/tests/api.rs b/crates/dns-api/tests/api.rs new file mode 100644 index 0000000..0f52000 --- /dev/null +++ b/crates/dns-api/tests/api.rs @@ -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, 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, 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; +} diff --git a/crates/dns-authoritative/Cargo.toml b/crates/dns-authoritative/Cargo.toml new file mode 100644 index 0000000..eef9e0d --- /dev/null +++ b/crates/dns-authoritative/Cargo.toml @@ -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 diff --git a/crates/dns-authoritative/src/journal.rs b/crates/dns-authoritative/src/journal.rs new file mode 100644 index 0000000..1c00721 --- /dev/null +++ b/crates/dns-authoritative/src/journal.rs @@ -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, + pub added: Vec, +} + +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, + add: Vec, +} + +fn enc(r: &Record) -> Option { + r.to_bytes().ok().map(|b| BASE64.encode(&b)) +} + +fn dec(s: &str) -> Option { + 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, + max: usize, + path: Option, +} + +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 { + 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::>()?, + added: l.add.iter().map(|s| dec(s)).collect::>()?, + }) + } + + fn line(d: &Diff) -> Option { + let l = Line { + from: enc(&d.from_soa)?, + to: enc(&d.to_soa)?, + del: d.removed.iter().map(enc).collect::>()?, + add: d.added.iter().map(enc).collect::>()?, + }; + 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> { + let start = self.entries.iter().position(|d| d.from_serial() == serial)?; + let chain: Vec = 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::())); + 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); + } +} diff --git a/crates/dns-authoritative/src/lib.rs b/crates/dns-authoritative/src/lib.rs new file mode 100644 index 0000000..2731242 --- /dev/null +++ b/crates/dns-authoritative/src/lib.rs @@ -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}; diff --git a/crates/dns-authoritative/src/secondary.rs b/crates/dns-authoritative/src/secondary.rs new file mode 100644 index 0000000..248cfca --- /dev/null +++ b/crates/dns-authoritative/src/secondary.rs @@ -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 = 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 { + 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 { + 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 { + 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, on_update: impl Fn(&Arc) + 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() +} diff --git a/crates/dns-authoritative/src/signing.rs b/crates/dns-authoritative/src/signing.rs new file mode 100644 index 0000000..f5adddf --- /dev/null +++ b/crates/dns-authoritative/src/signing.rs @@ -0,0 +1,237 @@ +//! Online DNSSEC signing of primary zones (NSEC, RFC 4033–4035). +//! +//! Keys live in `keys_dir` as `...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, + 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 { + let prefix = zone_prefix(zone); + let mut keys = Vec::new(); + if let Ok(rd) = std::fs::read_dir(keys_dir) { + let mut files: Vec = 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 { + 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 { + 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 = 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> = 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 = 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> = BTreeMap::new(); + for (n, t) in sets.keys() { + if below_cut(n) { + continue; + } + names.entry(n.clone()).or_default().insert(*t); + } + let ordered: Vec = names.keys().cloned().collect(); + let mut out: Vec = records.clone(); + for (i, n) in ordered.iter().enumerate() { + let next = &ordered[(i + 1) % ordered.len()]; + let mut types: Vec = 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 { + 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 = self.keys.iter().map(|k| k.tag).collect(); + let used: BTreeSet = 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 { + 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::())); + 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 = all.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect(); + let mut sets: BTreeMap<(Name, RecordType), Vec> = 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); + } +} diff --git a/crates/dns-authoritative/src/store.rs b/crates/dns-authoritative/src/store.rs new file mode 100644 index 0000000..148aed2 --- /dev/null +++ b/crates/dns-authoritative/src/store.rs @@ -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, + pub loaded: bool, + pub expired: bool, + pub records: usize, + pub source: Option, + pub last_refresh_unix: Option, + pub last_success_unix: Option, + pub next_refresh_unix: Option, + pub expires_at_unix: Option, + pub last_error: Option, + 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, + pub records: usize, + pub ok: bool, + pub error: Option, + pub duration_ms: u64, +} + +fn lock(m: &Mutex) -> 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, + data: RwLock>, + expired: AtomicBool, + pub journal: Mutex, + status: Mutex, + history: Mutex>, + /// Wakes the secondary refresh task (NOTIFY / manual sync). + pub refresh_trigger: tokio::sync::Notify, + pub shutdown: AtomicBool, + write_lock: Mutex<()>, + pub transfer_acl: Vec, + pub notify_acl: Vec, + pub update_acl: Vec, + pub transfer_key: Option, + pub notify_key: Option, + pub client_key: Option, + pub update_keys: Vec, + pub update_policy: Vec, + /// 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>, + /// Unsigned source of a signed zone. + source: Mutex>, + signed_file: PathBuf, + keys_dir: Option, +} + +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: `/zones/secondary/.zone`. +/// +/// Versions before 0.1.x-unreleased kept it in `/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 { + let name = dns_core::names::parse_name(&zc.name).map_err(|e| e.to_string())?; + let key = |k: &Option| -> Result, 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 { + 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 { + 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) { + 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 { + 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 { + lock(&self.signer).as_ref().map(|s| s.ds_records(&self.name)).unwrap_or_default() + } + + fn with_serial(zone: &Zone, serial: u32) -> Result { + 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 { + 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 = + 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 { + // 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 { + 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 { + 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) { + 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>, +} + +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>), 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> { + 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> { + let l = LowerName::new(name); + self.zones.iter().find(|z| z.lname == l).cloned() + } + + pub fn all(&self) -> &[Arc] { + &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); + } +} diff --git a/crates/dns-authoritative/src/update.rs b/crates/dns-authoritative/src/update.rs new file mode 100644 index 0000000..13ca9e9 --- /dev/null +++ b/crates/dns-authoritative/src/update.rs @@ -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, + pub added: usize, + pub removed: usize, + pub reason: String, +} + +fn fail(rcode: ResponseCode, reason: impl Into) -> 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)> = 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 = 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, Vec), UpdateOutcome> { + let apex = zone.origin_lower().clone(); + let mut removed: Vec = Vec::new(); + let mut added: Vec = Vec::new(); + let mut removed_keys: HashSet<(LowerName, RecordType, String)> = HashSet::new(); + let mut remove = |r: &Record, removed: &mut Vec| { + 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), +} + +/// A compiled `update_policy` rule. +#[derive(Debug, Clone)] +pub struct PolicyRule { + grant: bool, + /// None = any valid key (`*`). + identity: Option, + matches: UpdateMatch, + /// For `wildcard`: the base name below the `*` label. + name: Option, + types: Types, +} + +fn abs_name(s: &str) -> Result { + 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, 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::().map_err(|e| format!("{t}: {e}"))).collect::>()?) + }; + 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, updates: Vec) -> Message { + use dns_core::proto::op::{MessageType, OpCode, Query}; + let mut m = Message::new(rand::random::(), 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 +} diff --git a/crates/dns-authoritative/src/xfr.rs b/crates/dns-authoritative/src/xfr.rs new file mode 100644 index 0000000..b1106aa --- /dev/null +++ b/crates/dns-authoritative/src/xfr.rs @@ -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) -> Vec { + 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 { + 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, 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), +} + +/// Build a zone from an AXFR (or AXFR-style IXFR) record stream. +pub fn zone_from_axfr(origin: &Name, records: &[Record], limit: usize) -> Result { + 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 { + 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 = 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()); + } +} diff --git a/crates/dns-authoritative/src/zone.rs b/crates/dns-authoritative/src/zone.rs new file mode 100644 index 0000000..b17ed1d --- /dev/null +++ b/crates/dns-authoritative/src/zone.rs @@ -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, + pub rrsigs: Vec, +} + +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, +} + +/// 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, + /// All existing names including empty non-terminals. + names: HashSet, + soa: Record, + count: usize, + /// Owners of NSEC records (canonical order) – non-empty for signed zones. + nsec_names: BTreeSet, +} + +/// 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, additional: Vec, wildcard: bool, authority: Vec }, + /// CNAME whose target is outside this zone; caller may continue resolution. + CnameOut { answers: Vec, target: Name }, + /// Name exists, type does not. + NoData { soa: Record, proof: Vec }, + /// Name does not exist (possibly after following a CNAME: `answers` holds the chain). + NxDomain { soa: Record, answers: Vec, proof: Vec }, + /// Delegation to a child zone (not authoritative). + Referral { ns: Vec, glue: Vec, ds: Vec }, +} + +/// 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) -> Result { + Self::from_records_limited(origin, records, usize::MAX) + } + + pub fn from_records_limited(origin: &Name, records: Vec, limit: usize) -> Result { + 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 = HashMap::new(); + let mut soa: Option = 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 { + 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 { + 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 { + self.with_sigs(&LowerName::new(name), RecordType::NSEC) + } + + /// NSEC (+RRSIG) whose span covers `name` (canonical predecessor, wrapping). + fn nsec_covering(&self, name: &Name) -> Vec { + 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) { + 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) -> Vec { + 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) -> Vec { + 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 { + 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 = Vec::new(); + let mut authority: Vec = Vec::new(); + let mut current = qname.clone(); + let mut wildcard_used = false; + let negative = |answers: Vec, mut proof: Vec, 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| { + 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, Vec) { + 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 { + 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 = + 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; + +/// Non-fatal zone quality findings (named-checkzone style). +pub fn lint(zone: &Zone) -> Vec { + 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"))); + } +} diff --git a/crates/dns-cache/Cargo.toml b/crates/dns-cache/Cargo.toml new file mode 100644 index 0000000..cb8b303 --- /dev/null +++ b/crates/dns-cache/Cargo.toml @@ -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 diff --git a/crates/dns-cache/src/lib.rs b/crates/dns-cache/src/lib.rs new file mode 100644 index 0000000..23e547c --- /dev/null +++ b/crates/dns-cache/src/lib.rs @@ -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>>; + +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>> { + // 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>> { + 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 { + 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 { + 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> { + 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 = 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); + } +} diff --git a/crates/dns-cli/Cargo.toml b/crates/dns-cli/Cargo.toml new file mode 100644 index 0000000..c401e53 --- /dev/null +++ b/crates/dns-cli/Cargo.toml @@ -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 diff --git a/crates/dns-cli/build.rs b/crates/dns-cli/build.rs new file mode 100644 index 0000000..f5a5597 --- /dev/null +++ b/crates/dns-cli/build.rs @@ -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"); +} diff --git a/crates/dns-cli/src/bin/easydns.rs b/crates/dns-cli/src/bin/easydns.rs new file mode 100644 index 0000000..18efc38 --- /dev/null +++ b/crates/dns-cli/src/bin/easydns.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_cli::main() +} diff --git a/crates/dns-cli/src/bin/edns.rs b/crates/dns-cli/src/bin/edns.rs new file mode 100644 index 0000000..18efc38 --- /dev/null +++ b/crates/dns-cli/src/bin/edns.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_cli::main() +} diff --git a/crates/dns-cli/src/http.rs b/crates/dns-cli/src/http.rs new file mode 100644 index 0000000..5b2a26a --- /dev/null +++ b/crates/dns-cli/src/http.rs @@ -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)) +} diff --git a/crates/dns-cli/src/lib.rs b/crates/dns-cli/src/lib.rs new file mode 100644 index 0000000..55734db --- /dev/null +++ b/crates/dns-cli/src/lib.rs @@ -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, + /// API bearer token + #[arg(long, global = true, env = "EASYDNS_API_TOKEN", hide_env_values = true)] + token: Option, + /// 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, + #[arg(long)] + log_level: Option, + #[arg(long)] + data_dir: Option, + }, + /// 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:`) + 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 /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, + }, + Stats, +} + +#[derive(Subcommand)] +enum UpstreamsCmd { + List, +} + +#[derive(Subcommand)] +enum BlocklistCmd { + /// Download remote (https) lists into /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::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, log_level: Option, data_dir: Option) -> 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::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 (`/control.token`, readable by root and the `easydns` group). +fn api_token(cli: &Cli) -> Result, 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 { + 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"), +]; diff --git a/crates/dns-cli/src/zonecreate.rs b/crates/dns-cli/src/zonecreate.rs new file mode 100644 index 0000000..83faf31 --- /dev/null +++ b/crates/dns-cli/src/zonecreate.rs @@ -0,0 +1,291 @@ +//! `easydns zone create`: write a minimal, valid primary zone and its definition. +//! +//! Creates `/zones/.zone` (SOA, NS, glue for in-zone name servers and +//! optional apex addresses) and `/zones.d/.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. + #[arg(long = "ns", value_name = "NAME[=IP]")] + pub ns: Vec, + /// 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, + /// Responsible mailbox (`hostmaster@example.com`). Default: hostmaster@ + #[arg(long)] + pub email: Option, + /// 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, + /// Secondary to NOTIFY after changes (IP or IP:port, repeatable) + #[arg(long = "notify", value_name = "IP[:PORT]")] + pub notify: Vec, + /// Allow RFC 2136 updates from these addresses without a key (repeatable) + #[arg(long = "allow-update", value_name = "IP")] + pub allow_update: Vec, + /// 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, + pub definition: String, +} + +fn fqdn(s: &str) -> Result { + 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 { + s.parse::() + .or_else(|_| s.parse::().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)> = 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::().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 = 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 {}=", + 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::>().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 = a.notify.iter().map(|s| notify_addr(s).map(|x| x.to_string())).collect::>()?; + 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 { + 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); + } +} diff --git a/crates/dns-config/Cargo.toml b/crates/dns-config/Cargo.toml new file mode 100644 index 0000000..9239df5 --- /dev/null +++ b/crates/dns-config/Cargo.toml @@ -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 diff --git a/crates/dns-config/src/bindconf.rs b/crates/dns-config/src/bindconf.rs new file mode 100644 index 0000000..f1cc73c --- /dev/null +++ b/crates/dns-config/src/bindconf.rs @@ -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, (usize, String)> { + let b: Vec = 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, (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::()), + 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()); + } +} diff --git a/crates/dns-config/src/duration.rs b/crates/dns-config/src/duration.rs new file mode 100644 index 0000000..5306bfd --- /dev/null +++ b/crates/dns-config/src/duration.rs @@ -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 { + 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(d: &Duration, s: S) -> Result { + s.serialize_str(&format(d)) +} + +pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result { + 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(d: &Option, s: S) -> Result { + match d { + Some(d) => s.serialize_str(&super::format(d)), + None => s.serialize_none(), + } + } + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, 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()); + } +} diff --git a/crates/dns-config/src/include.rs b/crates/dns-config/src/include.rs new file mode 100644 index 0000000..ae77563 --- /dev/null +++ b/crates/dns-config/src/include.rs @@ -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, + pub keys: Vec, + pub acls: BTreeMap>, + pub forward_zones: Vec, + pub include: Vec, +} + +fn perr(file: &str, line: Option, message: String) -> ConfigError { + ConfigError::Parse { file: file.into(), line, message } +} + +pub(crate) fn parse(text: &str, file: &str) -> Result { + 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 = 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 = 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, Vec) = (pattern.chars().collect(), name.chars().collect()); + let (mut pi, mut ni, mut star, mut mark) = (0usize, 0usize, None::, 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, 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 = 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 = 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); + } +} diff --git a/crates/dns-config/src/lib.rs b/crates/dns-config/src/lib.rs new file mode 100644 index 0000000..d887b22 --- /dev/null +++ b/crates/dns-config/src/lib.rs @@ -0,0 +1,1057 @@ +//! EasyDNS configuration: schema, loading (YAML/JSON), ENV overrides and validation. +//! +//! Precedence: CLI > ENV > config file > defaults. CLI overrides are applied by the +//! binaries through [`Config::apply_overrides`]; ENV overrides by [`Config::apply_env`]. +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))] + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use ipnet::IpNet; +use serde::{Deserialize, Serialize}; + +mod bindconf; +pub mod duration; +mod include; +pub mod update_policy; +pub mod upstream; +mod validate; + +pub use validate::{ConfigError, ValidationIssue}; + +/// Root configuration document. +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(deny_unknown_fields, default)] +pub struct Config { + /// Additional files with zone definitions (and keys, ACLs, forward zones), like BIND's + /// `include "named.conf.zones";`. Paths and `*`/`?` globs in the last path component, + /// relative to this file's directory, e.g. `["zones.d/*.yaml"]`. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub include: Vec, + pub server: ServerConfig, + pub logging: LoggingConfig, + /// Named TSIG keys (`keys:` in BIND). + pub keys: Vec, + /// Named address match lists that can be referenced as `acl:`. + pub acls: std::collections::BTreeMap>, + pub recursion: RecursionConfig, + pub zones: Vec, + pub forward_zones: Vec, + pub upstreams: UpstreamsConfig, + pub resolution: ResolutionConfig, + pub cache: CacheConfig, + pub policy: PolicyConfig, + pub rate_limit: RateLimitConfig, + pub tls: TlsConfig, + pub api: ApiConfig, + pub metrics: MetricsConfig, +} + +/// Declared operating mode. Roles are actually defined by zones/recursion/upstreams; +/// the mode is validated against them so mistakes are caught early. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "kebab-case")] +pub enum Mode { + #[serde(alias = "master")] + Primary, + #[serde(alias = "slave")] + Secondary, + #[serde(alias = "resolver")] + Recursive, + Forwarder, + #[default] + #[serde(alias = "mixed")] + Hybrid, + CacheOnly, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct ServerConfig { + pub mode: Mode, + pub listen: Vec, + pub udp: bool, + pub tcp: bool, + /// Directory for persistent state (secondary snapshots, IXFR journals, audit log). + pub data_dir: PathBuf, + pub max_tcp_connections: usize, + #[serde(with = "duration")] + pub tcp_idle_timeout: Duration, + /// Largest UDP response we send (EDNS). 1232 avoids IP fragmentation. + pub max_udp_payload: u16, + /// Max in-flight queries handled concurrently (backpressure). + pub max_inflight: usize, + /// UDP sockets per listen address, bound with SO_REUSEPORT so the kernel spreads + /// queries over them and each gets its own receive loop. 0 = one per CPU (max 16). + /// Platforms without SO_REUSEPORT fall back to one socket. + pub udp_sockets: usize, + /// Base directory used to resolve relative paths (defaults to the config file's dir). + #[serde(skip_serializing_if = "Option::is_none")] + pub base_dir: Option, + /// NSID / version.bind answers are disabled unless set. + pub identity: Option, +} + +impl Default for ServerConfig { + fn default() -> Self { + Self { + mode: Mode::Hybrid, + // IPv4 on all interfaces, IPv6 loopback; recursion is limited by `recursion.allowed_clients` + listen: vec![SocketAddr::from(([0, 0, 0, 0], 53)), SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 53))], + udp: true, + tcp: true, + data_dir: PathBuf::from("data"), + max_tcp_connections: 1024, + tcp_idle_timeout: Duration::from_secs(10), + max_udp_payload: 1232, + max_inflight: 10_000, + udp_sockets: 0, + base_dir: None, + identity: None, + } + } +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum LogFormat { + #[default] + Text, + Json, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct LoggingConfig { + pub level: String, + pub format: LogFormat, + /// Per-query logging (off by default – privacy). + pub query_log: bool, + /// Mask client IPs in query logs (/24 and /48). + pub anonymize_clients: bool, +} + +impl Default for LoggingConfig { + fn default() -> Self { + Self { level: "info".into(), format: LogFormat::Text, query_log: false, anonymize_clients: true } + } +} + +/// A TSIG key. `secret` is a reference: `env:VAR`, `file:/path` or `base64:...`. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct KeyConfig { + pub name: String, + #[serde(default = "default_tsig_alg")] + pub algorithm: String, + pub secret: String, + /// Set when the key was read from a BIND-format key file (`include: [keys.conf]`). + #[serde(skip)] + pub imported_from: Option, +} + +fn default_tsig_alg() -> String { + "hmac-sha256".into() +} + +/// Remove `.` and resolve `..` components without touching the file system. +fn normalize(p: &Path) -> PathBuf { + use std::path::Component; + let mut out = PathBuf::new(); + for c in p.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + if !out.pop() { + out.push(".."); + } + } + other => out.push(other.as_os_str()), + } + } + out +} + +/// File name of the local control token inside `data_dir`. +pub const CONTROL_TOKEN_FILE: &str = "control.token"; + +/// Default recursion clients: the usual home/office LAN ranges and loopback. +/// (172.16.0.0/12 is not included; add it to `acls.lan` if your network uses it.) +pub const DEFAULT_LAN: &[&str] = &["192.168.0.0/16", "10.0.0.0/8", "127.0.0.1/32", "::1/128"]; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct RecursionConfig { + pub enabled: bool, + pub root_hints: Option, + /// Clients allowed to use recursion/forwarding (default: private LAN ranges + loopback, + /// see [`DEFAULT_LAN`]). + pub allowed_clients: Vec, + pub qname_minimization: bool, + pub dnssec_validation: bool, + /// Trust anchor file (DS or DNSKEY records, zone-file format). Built-in root KSK used if unset. + pub trust_anchors: Option, + pub max_depth: u32, + pub max_queries: u32, + pub max_cname_chain: u32, + #[serde(with = "duration")] + pub query_timeout: Duration, + #[serde(with = "duration")] + pub total_timeout: Duration, + /// Port used to reach authoritative servers (53; changeable only for test fixtures). + pub authority_port: u16, + /// Never send queries for these suffixes to the Internet (RFC 6761/6303 + private). + pub local_only_suffixes: Vec, + pub use_ipv6_transport: bool, +} + +impl Default for RecursionConfig { + fn default() -> Self { + Self { + enabled: false, + root_hints: None, + allowed_clients: DEFAULT_LAN.iter().map(|s| (*s).to_string()).collect(), + qname_minimization: true, + dnssec_validation: false, + trust_anchors: None, + max_depth: 30, + max_queries: 100, + max_cname_chain: 8, + query_timeout: Duration::from_millis(1500), + total_timeout: Duration::from_secs(10), + authority_port: 53, + local_only_suffixes: Vec::new(), + use_ipv6_transport: false, + } + } +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum ZoneType { + #[serde(alias = "master")] + Primary, + #[serde(alias = "slave")] + Secondary, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum TransferPreference { + #[default] + Ixfr, + Axfr, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct TransferClientConfig { + pub prefer: TransferPreference, + pub fallback_axfr: bool, + /// Name of a key from `keys:` used to sign SOA/IXFR/AXFR requests. + pub tsig_key: Option, + #[serde(with = "duration")] + pub timeout: Duration, + pub max_records: usize, +} + +impl Default for TransferClientConfig { + fn default() -> Self { + Self { + prefer: TransferPreference::Ixfr, + fallback_axfr: true, + tsig_key: None, + timeout: Duration::from_secs(120), + max_records: 2_000_000, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ZoneConfig { + /// File this zone was defined in (set by the loader, for error messages). + #[serde(skip)] + pub source: Option, + pub name: String, + #[serde(rename = "type")] + pub zone_type: ZoneType, + /// Zone file. A relative path is relative to `server.data_dir` (e.g. `zones/example.com.zone` + /// = `/zones/example.com.zone`). Primary: required. Secondary: optional; defaults to + /// `/zones/secondary/.zone`. + #[serde(default)] + pub file: Option, + /// Clients allowed to AXFR/IXFR this zone (default: nobody). + #[serde(default)] + pub transfer_acl: Vec, + /// Require this TSIG key for transfers (in addition to `transfer_acl`). + #[serde(default)] + pub transfer_tsig_key: Option, + /// Secondaries to NOTIFY after a change (primary only). + #[serde(default)] + pub notify: Vec, + /// Key used to sign outgoing NOTIFY (primary). + #[serde(default)] + pub notify_tsig_key: Option, + /// Primary servers to synchronise from (secondary only). + #[serde(default)] + pub primaries: Vec, + #[serde(default)] + pub transfer: TransferClientConfig, + /// Sources allowed to send NOTIFY (secondary). Defaults to the `primaries` addresses. + #[serde(default)] + pub allow_notify: Vec, + /// RFC 2136 dynamic updates. Exactly one model is used, chosen by what is set: + /// * `update_policy` – per-record rules by TSIG key (BIND `update-policy`); + /// * `update_keys` – any of these keys may change the whole zone; + /// * only `update_acl` – unsigned updates from these addresses (BIND `allow-update { IPs; }`). + /// + /// `update_acl`, when set together with keys or a policy, additionally restricts the + /// source addresses. Nothing set = updates refused. + #[serde(default)] + pub update_keys: Vec, + /// Source addresses allowed to send updates (alias: `allow_update`). + #[serde(default, alias = "allow_update")] + pub update_acl: Vec, + #[serde(default)] + pub update_policy: Vec, + #[serde(default)] + pub serial_strategy: dns_core::serial::SerialStrategy, + /// Views (by name) in which this zone is visible; empty = all. + #[serde(default)] + pub views: Vec, + /// Number of IXFR journal entries to keep. + #[serde(default = "default_journal")] + pub journal_size: usize, + /// Online DNSSEC signing (primary zones only). + #[serde(default)] + pub dnssec: Option, +} + +/// DNSSEC signing settings for a primary zone. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(deny_unknown_fields, default)] +pub struct DnssecZoneConfig { + /// Directory with private keys (`...key`), mode 0700. + pub keys_dir: PathBuf, + pub algorithm: dns_core::dnssec::KeyAlgorithm, + /// Generate a combined signing key (CSK) when the directory holds none. + pub auto_generate: bool, + #[serde(with = "duration")] + pub signature_validity: Duration, + /// Re-sign when signatures expire sooner than this. + #[serde(with = "duration")] + pub resign_before: Duration, +} + +impl Default for DnssecZoneConfig { + fn default() -> Self { + Self { + keys_dir: PathBuf::from("keys"), + algorithm: dns_core::dnssec::KeyAlgorithm::Ed25519, + auto_generate: true, + signature_validity: Duration::from_secs(14 * 86_400), + resign_before: Duration::from_secs(7 * 86_400), + } + } +} + +fn default_journal() -> usize { + 100 +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "kebab-case")] +pub enum Strategy { + RoundRobin, + Fastest, + #[default] + Failover, + Random, + Priority, +} + +/// An upstream address: `1.1.1.1:53`, `tcp://1.1.1.1:53`, `tls://1.1.1.1:853#cloudflare-dns.com`, +/// `https://dns.example/dns-query`. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ForwardZoneConfig { + pub domain: String, + pub upstreams: Vec, + #[serde(default)] + pub strategy: Strategy, + /// Optional client networks this rule applies to (empty = all). + #[serde(default)] + pub clients: Vec, + /// Fall back to local recursion if all upstreams fail. + #[serde(default)] + pub fallback_recursion: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(deny_unknown_fields, default)] +pub struct UpstreamsConfig { + pub strategy: Strategy, + /// `IP[:port]` (UDP+TCP), `tcp://IP`, `tls://IP[:853]#name` (DoT), `https://IP/path#name` (DoH). + pub servers: Vec, + /// Extra CA certificates (PEM) trusted for DoT/DoH upstreams, e.g. a private CA of an + /// internal resolver. Public resolvers need nothing: the Mozilla root store is built in. + #[serde(skip_serializing_if = "Option::is_none")] + pub tls_ca_file: Option, + #[serde(with = "duration::option", skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(with = "duration::option", skip_serializing_if = "Option::is_none")] + pub health_check_interval: Option, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum DefaultResolution { + /// Iterative resolution from the root. + Recursive, + /// Send to `upstreams`. + Forward, + /// Forward first, fall back to recursion when all upstreams fail. + ForwardThenRecursive, + /// No resolution beyond local zones (authoritative-only). + #[default] + Refuse, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(deny_unknown_fields, default)] +pub struct ResolutionConfig { + pub default: DefaultResolution, + /// Split-horizon views, evaluated in order; first matching view wins. + pub views: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ViewConfig { + pub name: String, + pub clients: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct CacheConfig { + pub enabled: bool, + pub max_entries: usize, + pub min_ttl: u32, + pub max_ttl: u32, + pub max_negative_ttl: u32, + /// Serve expired data (RFC 8767) when upstreams fail. Off by default. + pub serve_stale: bool, + pub stale_ttl: u32, + /// Cache of complete encoded answers (packet cache) answering repeated queries without + /// parsing or lookup; 0 disables it. Bounded memory: about 0.3–1 KiB per entry. + pub answer_entries: usize, + /// How long an answer from a local zone is reused. Zone changes invalidate it at once; + /// this only bounds the age. Resolved answers use their TTL (max 60 s). + #[serde(with = "duration")] + pub answer_max_age: Duration, + /// Refresh popular entries in the background shortly before they expire. + pub prefetch: bool, +} + +impl Default for CacheConfig { + fn default() -> Self { + Self { + enabled: true, + max_entries: 100_000, + min_ttl: 0, + max_ttl: 86_400, + max_negative_ttl: 3_600, + serve_stale: false, + stale_ttl: 30, + answer_entries: 20_000, + answer_max_age: Duration::from_secs(30), + prefetch: true, + } + } +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "lowercase")] +pub enum BlockAction { + #[default] + Nxdomain, + Refused, + /// 0.0.0.0 / :: for A/AAAA, NODATA for other types. + Null, + /// Configured `block_address_v4/v6` for A/AAAA, NODATA otherwise. + Address, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BlocklistConfig { + pub name: String, + /// Local file (hosts format or one domain per line, `*.` for wildcard, `/re/` regex). + #[serde(default)] + pub file: Option, + /// Remote list URL (fetched by `easydns blocklists update`; cached to data_dir). + #[serde(default)] + pub url: Option, + #[serde(default)] + pub category: Option, + #[serde(default = "yes")] + pub enabled: bool, +} + +fn yes() -> bool { + true +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct PolicyConfig { + pub blocklists: Vec, + pub allowlist: Vec, + pub block_action: BlockAction, + pub block_address_v4: std::net::Ipv4Addr, + pub block_address_v6: std::net::Ipv6Addr, + pub block_ttl: u32, + /// Clients exempt from blocking. + pub exempt_clients: Vec, + pub log_blocked: bool, +} + +impl Default for PolicyConfig { + fn default() -> Self { + Self { + blocklists: Vec::new(), + allowlist: Vec::new(), + block_action: BlockAction::Nxdomain, + block_address_v4: std::net::Ipv4Addr::UNSPECIFIED, + block_address_v6: std::net::Ipv6Addr::UNSPECIFIED, + block_ttl: 60, + exempt_clients: Vec::new(), + log_blocked: true, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct RateLimitConfig { + pub enabled: bool, + /// Sustained queries/second per client IP (IPv4 /32, IPv6 /56). + pub per_client_qps: u32, + pub burst: u32, + /// Server-wide UDP query ceiling; 0 (default) = no global limit, only per-client limits. + pub global_qps: u32, + /// Every Nth limited UDP query gets a truncated answer (RRL "slip"), others dropped. + pub slip: u32, + pub exempt_clients: Vec, +} + +impl Default for RateLimitConfig { + fn default() -> Self { + Self { + enabled: true, + per_client_qps: 200, + burst: 400, + global_qps: 0, + slip: 2, + exempt_clients: vec!["127.0.0.0/8".into(), "::1/128".into()], + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(deny_unknown_fields, default)] +pub struct TlsConfig { + pub cert_file: Option, + pub key_file: Option, + /// DNS-over-TLS listeners (e.g. `0.0.0.0:853`). + pub dot_listen: Vec, + /// DNS-over-HTTPS listeners (e.g. `0.0.0.0:443`). + pub doh_listen: Vec, + /// Serve DoH over plain HTTP (only behind a TLS-terminating reverse proxy!). + pub doh_plaintext_behind_proxy: bool, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum ApiRole { + Admin, + ReadOnly, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ApiTokenConfig { + pub name: String, + pub role: ApiRole, + /// `env:VAR`, `file:/path` or `sha256:` (hash of the token). + pub token: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct ApiConfig { + pub enabled: bool, + /// Default 127.0.0.1:9953 (loopback, non-standard port). + pub listen: SocketAddr, + pub auth_required: bool, + /// Create `/control.token` (mode 0640) on start and accept it as an admin + /// token. The `easydns` CLI reads it automatically, so local administration works + /// after installation without generating or passing a key; access is controlled by + /// file permissions (root and the `easydns` group). + pub local_token: bool, + pub tokens: Vec, + pub allowed_clients: Vec, + pub requests_per_minute: u32, +} + +impl Default for ApiConfig { + fn default() -> Self { + Self { + enabled: true, + listen: SocketAddr::from(([127, 0, 0, 1], 9953)), + auth_required: true, + local_token: true, + tokens: Vec::new(), + allowed_clients: vec!["127.0.0.0/8".into(), "::1/128".into()], + requests_per_minute: 600, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct MetricsConfig { + pub enabled: bool, + pub listen: SocketAddr, +} + +impl Default for MetricsConfig { + fn default() -> Self { + Self { enabled: true, listen: SocketAddr::from(([127, 0, 0, 1], 9090)) } + } +} + +/// Changes made through the REST API, persisted in `/api-overlay.yaml`. +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ApiOverlay { + pub zones: Vec, + pub upstreams: Vec, + pub allowlist: Option>, + pub block_action: Option, + pub block_rules: Vec, +} + +/// CLI-level overrides (highest precedence). +#[derive(Debug, Clone, Default)] +pub struct Overrides { + pub listen: Vec, + pub log_level: Option, + pub data_dir: Option, + pub api_listen: Option, +} + +impl Config { + /// Parse a configuration document (YAML is a superset of JSON). + pub fn from_str_any(text: &str, origin: &str) -> Result { + let trimmed = text.trim_start(); + let cfg: Config = if trimmed.starts_with('{') { + serde_json::from_str(text).map_err(|e| ConfigError::Parse { + file: origin.into(), + line: Some(e.line()), + message: e.to_string(), + })? + } else { + serde_norway::from_str(text).map_err(|e| ConfigError::Parse { + file: origin.into(), + line: e.location().map(|l| l.line()), + message: e.to_string(), + })? + }; + Ok(cfg) + } + + /// Load from a file, apply ENV overrides, resolve relative paths, validate. + pub fn load(path: &Path) -> Result { + let text = + std::fs::read_to_string(path).map_err(|e| ConfigError::Io { file: path.display().to_string(), message: e.to_string() })?; + let mut cfg = Self::from_str_any(&text, &path.display().to_string())?; + if cfg.server.base_dir.is_none() { + cfg.server.base_dir = path.parent().map(Path::to_path_buf); + } + cfg.expand_includes(path)?; + cfg.apply_env(|k| std::env::var(k).ok())?; + cfg.merge_api_overlay()?; + Ok(cfg) + } + + /// Load with full precedence: file < ENV < CLI overrides, then the API overlay + /// (which lives in the effective data directory). + pub fn load_with(path: &Path, overrides: &Overrides) -> Result { + let text = + std::fs::read_to_string(path).map_err(|e| ConfigError::Io { file: path.display().to_string(), message: e.to_string() })?; + let mut cfg = Self::from_str_any(&text, &path.display().to_string())?; + if cfg.server.base_dir.is_none() { + cfg.server.base_dir = path.parent().map(Path::to_path_buf); + } + cfg.expand_includes(path)?; + cfg.apply_env(|k| std::env::var(k).ok())?; + cfg.apply_overrides(overrides); + cfg.merge_api_overlay()?; + Ok(cfg) + } + + /// Read every `include:` file (recursively, max depth 8) and merge its zones, keys, + /// ACLs and forward zones into this configuration. Zones remember their source file. + pub fn expand_includes(&mut self, main: &Path) -> Result<(), ConfigError> { + let main_s = main.display().to_string(); + for z in &mut self.zones { + z.source.get_or_insert_with(|| main_s.clone()); + } + let base = main.parent().map(Path::to_path_buf).unwrap_or_default(); + let patterns = std::mem::take(&mut self.include); + let mut seen = std::collections::HashSet::new(); + if let Ok(c) = std::fs::canonicalize(main) { + seen.insert(c); + } + self.include_patterns(&patterns, &base, &main_s, 0, &mut seen)?; + self.include = patterns; + Ok(()) + } + + fn include_patterns( + &mut self, + patterns: &[String], + base: &Path, + from: &str, + depth: u32, + seen: &mut std::collections::HashSet, + ) -> Result<(), ConfigError> { + if depth > 8 { + return Err(ConfigError::Io { file: from.into(), message: "include nesting deeper than 8 levels".into() }); + } + for pat in patterns { + for file in include::expand(base, pat).map_err(|m| ConfigError::Io { file: from.into(), message: m })? { + let canon = std::fs::canonicalize(&file).unwrap_or_else(|_| file.clone()); + if !seen.insert(canon) { + return Err(ConfigError::Io { + file: from.into(), + message: format!("{} is included twice (or recursively)", file.display()), + }); + } + let fname = file.display().to_string(); + let text = std::fs::read_to_string(&file).map_err(|e| ConfigError::Io { file: fname.clone(), message: e.to_string() })?; + let inc = include::parse(&text, &fname)?; + for mut z in inc.zones { + z.source = Some(fname.clone()); + self.zones.push(z); + } + self.keys.extend(inc.keys); + self.forward_zones.extend(inc.forward_zones); + for (name, list) in inc.acls { + if self.acls.contains_key(&name) { + return Err(ConfigError::Io { file: fname.clone(), message: format!("ACL '{name}' is already defined") }); + } + self.acls.insert(name, list); + } + let nested_base = file.parent().map(Path::to_path_buf).unwrap_or_default(); + self.include_patterns(&inc.include, &nested_base, &fname, depth + 1, seen)?; + } + } + Ok(()) + } + + /// Path of the overlay file holding changes made through the REST API. + pub fn overlay_path(&self) -> PathBuf { + self.data_dir().join("api-overlay.yaml") + } + + /// Load the API overlay (empty when absent). + pub fn load_overlay(&self) -> Result { + let p = self.overlay_path(); + let Ok(text) = std::fs::read_to_string(&p) else { return Ok(ApiOverlay::default()) }; + serde_norway::from_str(&text).map_err(|e| ConfigError::Parse { + file: p.display().to_string(), + line: e.location().map(|l| l.line()), + message: e.to_string(), + }) + } + + /// Merge changes made through the API (`/api-overlay.yaml`). + pub fn merge_api_overlay(&mut self) -> Result<(), ConfigError> { + let o = self.load_overlay()?; + for z in o.zones { + if !self.zones.iter().any(|c| c.name.trim_end_matches('.').eq_ignore_ascii_case(z.name.trim_end_matches('.'))) { + self.zones.push(z); + } + } + for u in o.upstreams { + if !self.upstreams.servers.contains(&u) { + self.upstreams.servers.push(u); + } + } + if let Some(a) = o.allowlist { + self.policy.allowlist = a; + } + if let Some(a) = o.block_action { + self.policy.block_action = a; + } + if !o.block_rules.is_empty() { + self.policy.blocklists.push(BlocklistConfig { + name: "api".into(), + file: Some(self.data_dir().join("blocklists").join("api.txt")), + url: None, + category: Some("api".into()), + enabled: true, + }); + } + Ok(()) + } + + /// Apply `EASYDNS_*` environment overrides. + pub fn apply_env(&mut self, get: impl Fn(&str) -> Option) -> Result<(), ConfigError> { + if let Some(v) = get("EASYDNS_LISTEN") { + let mut out = Vec::new(); + for a in v.split(',').map(str::trim).filter(|s| !s.is_empty()) { + out.push( + a.parse() + .map_err(|_| ConfigError::Env { var: "EASYDNS_LISTEN".into(), message: format!("invalid socket address '{a}'") })?, + ); + } + self.server.listen = out; + } + if let Some(v) = get("EASYDNS_LOG_LEVEL") { + self.logging.level = v; + } + if let Some(v) = get("EASYDNS_DATA_DIR") { + self.server.data_dir = v.into(); + } + if let Some(v) = get("EASYDNS_API_LISTEN") { + self.api.listen = v + .parse() + .map_err(|_| ConfigError::Env { var: "EASYDNS_API_LISTEN".into(), message: format!("invalid socket address '{v}'") })?; + } + Ok(()) + } + + /// Apply CLI overrides. + pub fn apply_overrides(&mut self, o: &Overrides) { + if !o.listen.is_empty() { + self.server.listen = o.listen.clone(); + } + if let Some(l) = &o.log_level { + self.logging.level = l.clone(); + } + if let Some(d) = &o.data_dir { + self.server.data_dir = d.clone(); + } + if let Some(a) = o.api_listen { + self.api.listen = a; + } + } + + /// Resolve a path relative to the config file directory. + pub fn resolve_path(&self, p: &Path) -> PathBuf { + if p.is_absolute() { + return p.to_path_buf(); + } + match &self.server.base_dir { + Some(b) => b.join(p), + None => p.to_path_buf(), + } + } + + /// Local control token file used by the CLI (`api.local_token`). + pub fn control_token_path(&self) -> PathBuf { + self.data_dir().join(CONTROL_TOKEN_FILE) + } + + /// Data directory (resolved). + pub fn data_dir(&self) -> PathBuf { + self.resolve_path(&self.server.data_dir) + } + + /// Resolve a zone `file:`. Relative paths are relative to the data directory + /// (`zones/example.com.zone` → `/zones/example.com.zone`). For configurations + /// written before this rule, a relative path that exists only relative to the config + /// directory is still accepted. + pub fn zone_file_path(&self, p: &Path) -> PathBuf { + if p.is_absolute() { + return p.to_path_buf(); + } + // lexical normalisation: `../x` must work before the data directory exists + let in_data = normalize(&self.data_dir().join(p)); + if !in_data.exists() { + let legacy = self.resolve_path(p); + if legacy.is_file() { + return legacy; + } + } + in_data + } + + /// Expand an ACL list (CIDRs, bare IPs, `acl:`, `any`, `none`) into networks. + pub fn expand_acl(&self, items: &[String]) -> Result, String> { + let mut out = Vec::new(); + self.expand_acl_inner(items, &mut out, 0)?; + Ok(out) + } + + fn expand_acl_inner(&self, items: &[String], out: &mut Vec, depth: u32) -> Result<(), String> { + if depth > 8 { + return Err("ACL references nested too deeply (loop?)".into()); + } + for it in items { + let s = it.trim(); + if let Some(name) = s.strip_prefix("acl:") { + let list = self.acls.get(name).ok_or_else(|| format!("unknown ACL '{name}'"))?; + self.expand_acl_inner(list, out, depth + 1)?; + } else if s == "any" { + out.push("0.0.0.0/0".parse().map_err(|_| "acl")?); + out.push("::/0".parse().map_err(|_| "acl")?); + } else if s == "none" { + } else if let Ok(n) = s.parse::() { + out.push(n.trunc()); + } else if let Ok(ip) = s.parse::() { + out.push(IpNet::from(ip)); + } else { + return Err(format!("invalid ACL entry '{s}'")); + } + } + Ok(()) + } + + /// Resolve a secret reference (`env:`, `file:`, `base64:`). + pub fn resolve_secret(&self, reference: &str) -> Result { + if let Some(var) = reference.strip_prefix("env:") { + std::env::var(var).map_err(|_| format!("environment variable {var} is not set")) + } else if let Some(p) = reference.strip_prefix("file:") { + let path = self.resolve_path(Path::new(p)); + std::fs::read_to_string(&path) + .map(|s| s.trim().to_string()) + .map_err(|e| format!("cannot read secret file {}: {e}", path.display())) + } else if let Some(v) = reference.strip_prefix("base64:") { + Ok(v.to_string()) + } else { + Err("secret must be a reference: env:VAR, file:/path or base64:".into()) + } + } + + /// Build the TSIG key ring. + pub fn key_ring(&self) -> Result { + let mut ring = dns_core::tsig::KeyRing::default(); + for k in &self.keys { + let secret = self.resolve_secret(&k.secret).map_err(|e| format!("key {}: {e}", k.name))?; + let key = dns_core::tsig::TsigKey::new(&k.name, &k.algorithm, &secret).map_err(|e| e.to_string())?; + ring.insert(key); + } + Ok(ring) + } + + /// Validate; returns all issues found (errors and warnings). + pub fn validate(&self) -> Vec { + validate::validate(self) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn zone_path_with_parent_dir_before_data_dir_exists() { + let d = std::env::temp_dir().join(format!("edns-zp-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("z.zone"), "x").unwrap(); + let mut c = super::Config::default(); + c.server.base_dir = Some(d.clone()); + c.server.data_dir = "not-created-yet".into(); + assert_eq!(c.zone_file_path(std::path::Path::new("../z.zone")), d.join("z.zone")); + assert_eq!(c.zone_file_path(std::path::Path::new("zones/a.zone")), d.join("not-created-yet/zones/a.zone")); + let _ = std::fs::remove_dir_all(&d); + } + + use super::*; + + const SAMPLE: &str = r#" +server: + mode: hybrid + listen: ["127.0.0.1:5353"] +recursion: + enabled: true + allowed_clients: ["127.0.0.0/8", "acl:lan"] +acls: + lan: ["192.168.0.0/16"] +zones: + - name: example.net + type: slave + primaries: ["192.0.2.1:53"] + transfer: + prefer: ixfr + timeout: 30s +forward_zones: + - domain: corp.internal + upstreams: ["192.168.1.1:53"] +upstreams: + strategy: fastest + servers: ["1.1.1.1:53", "tls://9.9.9.9#dns.quad9.net"] +resolution: + default: recursive +"#; + + #[test] + fn parse_sample() { + let c = Config::from_str_any(SAMPLE, "t").unwrap(); + assert_eq!(c.zones[0].zone_type, ZoneType::Secondary); + assert_eq!(c.zones[0].transfer.timeout.as_secs(), 30); + let issues = c.validate(); + let errs: Vec<_> = issues.iter().filter(|i| i.is_error()).collect(); + assert!(errs.is_empty(), "{errs:?}"); + let acl = c.expand_acl(&c.recursion.allowed_clients).unwrap(); + assert_eq!(acl.len(), 2); + } + + #[test] + fn unknown_field_rejected_with_line() { + let e = Config::from_str_any("server:\n lisen: []\n", "c.yaml").unwrap_err(); + let s = e.to_string(); + assert!(s.contains("c.yaml:2"), "{s}"); + assert!(s.contains("lisen")); + } + + #[test] + fn detects_errors() { + let y = r#" +server: { mode: recursive } +zones: + - { name: "bad..name", type: primary } + - { name: example.org, type: secondary } +resolution: { default: forward } +api: { listen: "0.0.0.0:8080", auth_required: false } +"#; + let c = Config::from_str_any(y, "t").unwrap(); + let issues = c.validate(); + let paths: Vec<_> = issues.iter().filter(|i| i.is_error()).map(|i| i.path.clone()).collect(); + for p in ["zones[0].name", "zones[0].file", "zones[1].primaries", "resolution.default", "server.mode", "api.auth_required"] { + assert!(paths.iter().any(|x| x == p), "missing {p} in {paths:?}"); + } + } + + #[test] + fn env_and_cli_precedence() { + let mut c = Config::from_str_any(SAMPLE, "t").unwrap(); + c.apply_env(|k| (k == "EASYDNS_LISTEN").then(|| "127.0.0.1:1053".into())).unwrap(); + assert_eq!(c.server.listen[0].port(), 1053); + c.apply_overrides(&Overrides { listen: vec!["127.0.0.1:2053".parse().unwrap()], ..Default::default() }); + assert_eq!(c.server.listen[0].port(), 2053); + assert!(c.apply_env(|k| (k == "EASYDNS_LISTEN").then(|| "nope".into())).is_err()); + } + + #[test] + fn open_resolver_warns() { + let c = + Config::from_str_any("recursion: { enabled: true, allowed_clients: [any] }\nresolution: {default: recursive}", "t").unwrap(); + assert!(c.validate().iter().any(|i| i.path == "recursion.allowed_clients" && !i.is_error())); + } +} diff --git a/crates/dns-config/src/update_policy.rs b/crates/dns-config/src/update_policy.rs new file mode 100644 index 0000000..e75d0e6 --- /dev/null +++ b/crates/dns-config/src/update_policy.rs @@ -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 { + 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, + /// Record types (upper case). Empty = all types except SOA, NS, RRSIG, NSEC, NSEC3 + /// (as in BIND); `ANY` = every type. + pub types: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RuleMap { + #[serde(default)] + grant: Option, + #[serde(default)] + deny: Option, + #[serde(rename = "match")] + matches: UpdateMatch, + #[serde(default)] + name: Option, + #[serde(default)] + types: Vec, +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum RuleRepr { + Text(String), + Map(RuleMap), +} + +impl<'de> Deserialize<'de> for UpdateRule { + fn deserialize>(d: D) -> Result { + 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) -> Vec { + 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::().is_ok_and(|t| !matches!(t, dns_core::proto::rr::RecordType::Unknown(_))) +} + +impl UpdateRule { + /// Parse BIND syntax: `grant|deny [] [ ...]`. + pub fn parse(text: &str) -> Result { + 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::("{ match: zonesub }").is_err()); + let v: Vec = serde_norway::from_str("- \"grant k zonesub TXT\"\n- { deny: '*', match: zonesub }\n").unwrap(); + assert_eq!(v.len(), 2); + } +} diff --git a/crates/dns-config/src/upstream.rs b/crates/dns-config/src/upstream.rs new file mode 100644 index 0000000..4bde71f --- /dev/null +++ b/crates/dns-config/src/upstream.rs @@ -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, + /// HTTP path for https. + pub path: String, + pub original: String, +} + +impl UpstreamAddr { + pub fn parse(s: &str) -> Result { + 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::() { + 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 '#' 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()); + } +} diff --git a/crates/dns-config/src/validate.rs b/crates/dns-config/src/validate.rs new file mode 100644 index 0000000..03b7e87 --- /dev/null +++ b/crates/dns-config/src/validate.rs @@ -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, 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); + +impl V { + fn err(&mut self, path: impl Into, msg: impl Into) { + self.0.push(ValidationIssue { severity: Severity::Error, path: path.into(), message: msg.into() }); + } + fn warn(&mut self, path: impl Into, msg: impl Into) { + 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 { + 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:"); + } + } + 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 +} diff --git a/crates/dns-core/Cargo.toml b/crates/dns-core/Cargo.toml new file mode 100644 index 0000000..2c82270 --- /dev/null +++ b/crates/dns-core/Cargo.toml @@ -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 diff --git a/crates/dns-core/src/answer.rs b/crates/dns-core/src/answer.rs new file mode 100644 index 0000000..c725ece --- /dev/null +++ b/crates/dns-core/src/answer.rs @@ -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, + pub authority: Vec, + pub additional: Vec, + pub security: Security, + pub source: Source, + /// Free-form note (upstream used, block reason) for logs. + pub note: Option, +} + +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) -> Self { + let mut a = Self::new(ResponseCode::ServFail, source); + a.note = Some(note.into()); + a + } +} diff --git a/crates/dns-core/src/client.rs b/crates/dns-core/src/client.rs new file mode 100644 index 0000000..d2f4a45 --- /dev/null +++ b/crates/dns-core/src/client.rs @@ -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, +} + +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::(), 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 { + 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 { + 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, 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, 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: &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: &mut R) -> CoreResult> { + 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, + }, +} + +/// Result of a zone transfer: the flat record stream as received. +#[derive(Debug, Clone)] +pub struct TransferStream { + pub records: Vec, + 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 { + 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 { + let start = Instant::now(); + let rtype = match kind { + TransferKind::Axfr => RecordType::AXFR, + TransferKind::Ixfr { .. } => RecordType::IXFR, + }; + let mut msg = Message::new(rand::random::(), 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 = Vec::new(); + let mut messages = 0usize; + let mut total = 0usize; + let mut final_serial: Option = None; + let mut incremental: Option = 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 { + let mut m = Message::new(rand::random::(), 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) +} diff --git a/crates/dns-core/src/dnssec.rs b/crates/dns-core/src/dnssec.rs new file mode 100644 index 0000000..356274e --- /dev/null +++ b/crates/dns-core/src/dnssec.rs @@ -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, +} + +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> { + let der = PrivatePkcs8KeyDer::from(pkcs8.to_vec()); + let k: Box = 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, 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 { + 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 { + 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 { + 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 (`...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 { + 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::(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 { + 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 = 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 = 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 { + 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 = 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 = 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, 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"); + } +} diff --git a/crates/dns-core/src/error.rs b/crates/dns-core/src/error.rs new file mode 100644 index 0000000..28ee6cd --- /dev/null +++ b/crates/dns-core/src/error.rs @@ -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 for CoreError { + fn from(e: hickory_proto::ProtoError) -> Self { + CoreError::Proto(e.to_string()) + } +} + +/// Result alias. +pub type CoreResult = Result; diff --git a/crates/dns-core/src/lib.rs b/crates/dns-core/src/lib.rs new file mode 100644 index 0000000..1fefd94 --- /dev/null +++ b/crates/dns-core/src/lib.rs @@ -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::() + .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); + })); +} diff --git a/crates/dns-core/src/names.rs b/crates/dns-core/src/names.rs new file mode 100644 index 0000000..0b04552 --- /dev/null +++ b/crates/dns-core/src/names.rs @@ -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 { + 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 { + 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 + '_ { + 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 = 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."); + } +} diff --git a/crates/dns-core/src/serial.rs b/crates/dns-core/src/serial.rs new file mode 100644 index 0000000..b7a4227 --- /dev/null +++ b/crates/dns-core/src/serial.rs @@ -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 { + 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); + } +} diff --git a/crates/dns-core/src/tls.rs b/crates/dns-core/src/tls.rs new file mode 100644 index 0000000..c3ebfbf --- /dev/null +++ b/crates/dns-core/src/tls.rs @@ -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, + 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> { + 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); + +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 { + Ok(rustls::client::danger::ServerCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + m: &[u8], + c: &rustls::pki_types::CertificateDer<'_>, + d: &rustls::DigitallySignedStruct, + ) -> Result { + 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::crypto::verify_tls13_signature(m, c, d, &self.0.signature_verification_algorithms) + } + fn supported_verify_schemes(&self) -> Vec { + self.0.signature_verification_algorithms.supported_schemes() + } +} + +async fn connect_tls( + addr: SocketAddr, + server_name: &str, + cfg: Arc, +) -> CoreResult<(tokio_rustls::client::TlsStream, 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, +) -> CoreResult> { + connect_tls(addr, server_name, cfg).await.map(|(s, _, _)| s) +} + +fn info(s: &tokio_rustls::client::TlsStream, 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, +) -> CoreResult<(Vec, 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, +) -> CoreResult<(u16, Vec, 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)>> { + 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)>> { + 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 = 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)> { + 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()); + } +} diff --git a/crates/dns-core/src/tls_pool.rs b/crates/dns-core/src/tls_pool.rs new file mode 100644 index 0000000..d0644d3 --- /dev/null +++ b/crates/dns-core/src/tls_pool.rs @@ -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, alpn: &[&[u8]]) -> Arc { + 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, + idle: Mutex, Instant)>>, + max_idle: usize, +} + +impl DotPool { + pub fn new(addr: SocketAddr, tls_name: &str, base: &Arc, 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> { + 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) { + 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> { + 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>), + /// 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, + h1_cfg: Arc, + conn: Mutex>>>, + http1_only: std::sync::atomic::AtomicBool, +} + +impl DohClient { + pub fn new(addr: SocketAddr, tls_name: &str, path: &str, base: &Arc) -> 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 { + 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>, query: &[u8], method: DohMethod) -> CoreResult<(u16, Vec)> { + 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)> { + 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() + } +} diff --git a/crates/dns-core/src/tsig.rs b/crates/dns-core/src/tsig.rs new file mode 100644 index 0000000..e2724ce --- /dev/null +++ b/crates/dns-core/src/tsig.rs @@ -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, + 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", &"") + .finish() + } +} + +/// Parse an algorithm name (`hmac-sha256`, `hmac-sha512`, ...). +pub fn parse_algorithm(s: &str) -> CoreResult { + 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 { + 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> { + 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> { + 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, +} + +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 }, + /// 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, + first: bool, + pending: Vec, +} + +impl ResponseSigner { + pub fn new(key: TsigKey, request_mac: Vec) -> 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> { + 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> { + 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, + first: bool, + unsigned: Vec, + unsigned_run: usize, +} + +impl ResponseVerifier { + pub fn new(key: TsigKey, request_mac: Vec) -> 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 { + 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(); + } +} diff --git a/crates/dns-core/src/wire.rs b/crates/dns-core/src/wire.rs new file mode 100644 index 0000000..0c940fa --- /dev/null +++ b/crates/dns-core/src/wire.rs @@ -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> { + 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> { + 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> { + 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()); + } +} diff --git a/crates/dns-core/src/zonefile.rs b/crates/dns-core/src/zonefile.rs new file mode 100644 index 0000000..3117601 --- /dev/null +++ b/crates/dns-core/src/zonefile.rs @@ -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> { + 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(|| "".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(|| "".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> { + 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 = recs.iter().map(|r| format!("{} {} {}", r.name, r.record_type(), r.data)).collect(); + let mut b: Vec = 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()); + } +} diff --git a/crates/dns-core/src/zonefile_ext.rs b/crates/dns-core/src/zonefile_ext.rs new file mode 100644 index 0000000..dfcb333 --- /dev/null +++ b/crates/dns-core/src/zonefile_ext.rs @@ -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)> { + let mut out = Vec::new(); + let mut tokens: Vec = 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 = None; + let mut chars = text.chars().peekable(); + let flush_tok = |cur: &mut String, tokens: &mut Vec| { + 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 { + 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 { + if let Ok(n) = s.parse::() { + 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 { + if s.len() == 14 && s.chars().all(|c| c.is_ascii_digit()) { + let p = |a: usize, b: usize| s[a..b].parse::().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::().map_err(|_| CoreError::ZoneFile(format!("bad RRSIG time '{s}'"))) +} + +fn parse_types(toks: &[String]) -> CoreResult> { + toks.iter() + .map(|t| { + let u = t.to_ascii_uppercase(); + if let Some(n) = u.strip_prefix("TYPE") { + return n.parse::().map(RecordType::from).map_err(|_| CoreError::ZoneFile(format!("bad type {t}"))); + } + u.parse::().map_err(|_| CoreError::ZoneFile(format!("bad type {t}"))) + }) + .collect() +} + +fn generic(rtype: RecordType, rd: &[String]) -> CoreResult { + // \# + 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 { + 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 { s.parse::().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)> { + let mut origin = origin.clone(); + let mut ttl = default_ttl; + let mut last_owner: Option = None; + let mut last_ttl: Option = 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 = 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::().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::().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 { + 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); + } +} diff --git a/crates/dns-forwarder/Cargo.toml b/crates/dns-forwarder/Cargo.toml new file mode 100644 index 0000000..a2576f5 --- /dev/null +++ b/crates/dns-forwarder/Cargo.toml @@ -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 diff --git a/crates/dns-forwarder/src/lib.rs b/crates/dns-forwarder/src/lib.rs new file mode 100644 index 0000000..40c84f1 --- /dev/null +++ b/crates/dns-forwarder/src/lib.rs @@ -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, + pub circuit_open_for_ms: Option, + pub last_error: Option, + pub healthy: bool, +} + +#[derive(Debug)] +struct State { + stats: UpstreamStats, + open_until: Option, + 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, + enc: Option, +} + +impl Upstream { + fn new(addr: UpstreamAddr, priority: usize, tls: Option<&Arc>) -> 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>, + pub timeout: Duration, + rr: AtomicUsize, +} + +impl Pool { + pub fn new(name: &str, servers: &[String], strategy: Strategy, timeout: Duration) -> Result { + 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 { + let addrs = servers.iter().map(|s| UpstreamAddr::parse(s)).collect::, _>>()?; + 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> = 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>, &'static str) { + let mut v: Vec> = 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::() < 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 { + 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 { + 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 = 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 = (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 = 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}"); + } +} diff --git a/crates/dns-metrics/Cargo.toml b/crates/dns-metrics/Cargo.toml new file mode 100644 index 0000000..aeb75c5 --- /dev/null +++ b/crates/dns-metrics/Cargo.toml @@ -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 diff --git a/crates/dns-metrics/src/lib.rs b/crates/dns-metrics/src/lib.rs new file mode 100644 index 0000000..ebc53e0 --- /dev/null +++ b/crates/dns-metrics/src/lib.rs @@ -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, + 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 { + 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() -> [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 { + 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)); + } +} diff --git a/crates/dns-policy/Cargo.toml b/crates/dns-policy/Cargo.toml new file mode 100644 index 0000000..43432d8 --- /dev/null +++ b/crates/dns-policy/Cargo.toml @@ -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 diff --git a/crates/dns-policy/src/lib.rs b/crates/dns-policy/src/lib.rs new file mode 100644 index 0000000..dd873ec --- /dev/null +++ b/crates/dns-policy/src/lib.rs @@ -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); + +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 { + 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>; + +/// 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 { + 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, +} + +#[derive(Debug, Default)] +struct RuleSet { + exact: HashMap, + suffix: HashMap, + 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::().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)>, + pub action: BlockAction, + pub v4: Option, + pub v6: Option, + pub ttl: u32, + pub exempt: Acl, + pub log: bool, +} + +impl BlockPolicy { + /// Load lists from configuration. Remote lists are read from their cached copy in + /// `/blocklists/.txt` (downloaded by `easydns blocklists update`). + pub fn from_config(cfg: &Config) -> Result { + 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 { + 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 { + 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 { + 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::>(); + 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); + +impl SuffixSet { + pub fn new(items: impl IntoIterator) -> 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")); + } +} diff --git a/crates/dns-recursive/Cargo.toml b/crates/dns-recursive/Cargo.toml new file mode 100644 index 0000000..d3313da --- /dev/null +++ b/crates/dns-recursive/Cargo.toml @@ -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 diff --git a/crates/dns-recursive/src/hints.rs b/crates/dns-recursive/src/hints.rs new file mode 100644 index 0000000..debdff0 --- /dev/null +++ b/crates/dns-recursive/src/hints.rs @@ -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, 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, 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)>, String> { + let mut out: Vec<(Name, Vec)> = 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)); + } +} diff --git a/crates/dns-recursive/src/lib.rs b/crates/dns-recursive/src/lib.rs new file mode 100644 index 0000000..52960d5 --- /dev/null +++ b/crates/dns-recursive/src/lib.rs @@ -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, + 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>>, +} + +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, + fails: u32, + dead_until: Option, +} + +/// The iterative resolver. +pub struct Resolver { + settings: Settings, + roots: Vec<(Name, Vec)>, + cache: Arc, + ns: u16, + servers: Mutex>, + pub queries_sent: AtomicU64, + validator: Option, +} + +/// 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, + glue: Vec, + }, + NxDomain(Message), + NoData(Message), + /// Try another server. + Lame(String), +} + +type BoxFut<'a, T> = Pin + 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 { + 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, cache: Arc, cache_namespace: u16) -> Result { + 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) { + 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) { + 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 = 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 = a.authority.iter().filter(|r| r.record_type() == RecordType::SOA).cloned().collect(); + let sigs: Vec = 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) { + 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 = 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 = 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 = 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) { + 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 { + 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)>) { + 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::() * 50.0); + let rb = map.get(&b.0).and_then(|s| s.rtt_ms).unwrap_or(rand::random::() * 50.0); + ra.total_cmp(&rb) + }); + } + + fn server_result(&self, ip: IpAddr, rtt: Option) { + 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> = 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 { + let mut addrs: Vec<(IpAddr, Option)> = 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 = 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 = 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) +} diff --git a/crates/dns-recursive/src/validator.rs b/crates/dns-recursive/src/validator.rs new file mode 100644 index 0000000..f5d0ed7 --- /dev/null +++ b/crates/dns-recursive/src/validator.rs @@ -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), + 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>, +} + +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 { + 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 { + let mut v: Vec = self.anchors.iter().map(|(n, _)| n.clone()).collect(); + v.dedup(); + v + } + + pub(crate) fn cached(&self, zone: &Name) -> Option { + 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 { + 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 = + answer.iter().filter(|r| r.record_type() == RecordType::DNSKEY && r.name.eq_ignore_root_case(zone)).cloned().collect(); + let sigs: Vec = answer.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect(); + let dnskeys: Vec = keys.iter().filter_map(dnskey_of).cloned().collect(); + let trusted: Vec = 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 = + ds_answer.answers.iter().filter(|r| r.record_type() == RecordType::DS && r.name.eq_ignore_root_case(zone)).cloned().collect(); + let sigs: Vec = + 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 = + ka.answers.iter().filter(|r| r.record_type() == RecordType::DNSKEY && r.name.eq_ignore_root_case(zone)).cloned().collect(); + let ksigs: Vec = ka.answers.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect(); + let dnskeys: Vec = keys.iter().filter_map(dnskey_of).cloned().collect(); + let entry: Vec = 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 { + let sigs: Vec = 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 = authority.iter().filter(|r| r.record_type() == t).map(|r| r.name.clone()).collect(); + owners.dedup(); + for o in owners { + let set: Vec = + 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) -> (Security, Option) { + let sigs: Vec = answer.answers.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect(); + let mut groups: Vec<(Name, RecordType, Vec)> = 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)) +} diff --git a/crates/dns-server/Cargo.toml b/crates/dns-server/Cargo.toml new file mode 100644 index 0000000..1cd2030 --- /dev/null +++ b/crates/dns-server/Cargo.toml @@ -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 diff --git a/crates/dns-server/src/audit.rs b/crates/dns-server/src/audit.rs new file mode 100644 index 0000000..bf03e29 --- /dev/null +++ b/crates/dns-server/src/audit.rs @@ -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, + lock: Mutex<()>, +} + +impl AuditLog { + pub fn new(path: Option) -> 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 { + 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() + } +} diff --git a/crates/dns-server/src/check.rs b/crates/dns-server/src/check.rs new file mode 100644 index 0000000..c91f34a --- /dev/null +++ b/crates/dns-server/src/check.rs @@ -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 { + 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 { + let mut out: Vec = 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 +} diff --git a/crates/dns-server/src/coalesce.rs b/crates/dns-server/src/coalesce.rs new file mode 100644 index 0000000..1d0642b --- /dev/null +++ b/crates/dns-server/src/coalesce.rs @@ -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>; + +#[derive(Default)] +pub struct Coalescer { + inflight: Mutex>, +} + +/// Removes the leader's entry on completion or cancellation. +struct Leader<'a> { + c: &'a Coalescer, + key: Option, +} + +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), + Alone, +} + +impl Coalescer { + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap> { + 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(&self, key: FlightKey, resolve: F) -> Answer + where + F: FnOnce() -> Fut, + Fut: Future, + { + 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); + } +} diff --git a/crates/dns-server/src/handler.rs b/crates/dns-server/src/handler.rs new file mode 100644 index 0000000..7e36357 --- /dev/null +++ b/crates/dns-server/src/handler.rs @@ -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), + Many(Vec>), +} + +/// 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, + 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), + /// Not answered; pass the rate-limit decision (if one was taken) to [`handle_with`]. + Miss(Option), +} + +fn cache_hit(shared: &Shared, raw: &[u8], profile: u64, transport: Transport, start: Instant) -> Option> { + 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) -> 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, + raw: &[u8], + client: SocketAddr, + transport: Transport, + rl: Option, + 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| 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)) +} diff --git a/crates/dns-server/src/lib.rs b/crates/dns-server/src/lib.rs new file mode 100644 index 0000000..8dc1376 --- /dev/null +++ b/crates/dns-server/src/lib.rs @@ -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}; diff --git a/crates/dns-server/src/listener.rs b/crates/dns-server/src/listener.rs new file mode 100644 index 0000000..bdf87fc --- /dev/null +++ b/crates/dns-server/src/listener.rs @@ -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 { + 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 { + 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> { + 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, sock: Arc, inflight: Arc, shutdown: watch::Receiver) { + #[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, sock: &Arc, inflight: &Arc, pkt: &[u8], peer: SocketAddr) -> Option> { + 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 { + 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]) -> std::io::Result)>> { + let mut hdrs = MultiHeaders::::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, SocketAddr)]) -> std::io::Result { + let mut hdrs = MultiHeaders::::preallocate(out.len(), None); + let iovs: Vec<[IoSlice<'_>; 1]> = out.iter().map(|(b, _)| [IoSlice::new(b)]).collect(); + let addrs: Vec> = 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, sock: Arc, inflight: Arc, mut shutdown: watch::Receiver) { + let fd = sock.as_raw_fd(); + let mut bufs: Vec> = (0..BATCH).map(|_| vec![0u8; BUF]).collect(); + let mut out: Vec<(Vec, 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, sock: Arc, inflight: Arc, mut shutdown: watch::Receiver) { + 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(shared: Arc, 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, listener: TcpListener, mut shutdown: watch::Receiver) { + 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); + }); + } +} diff --git a/crates/dns-server/src/packet_cache.rs b/crates/dns-server/src/packet_cache.rs new file mode 100644 index 0000000..f5f9187 --- /dev/null +++ b/crates/dns-server/src/packet_cache.rs @@ -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, Arc>>; + +/// 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, + 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 { + 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 { + 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, u32)> { + let count = |i: usize| -> Option { 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, Arc>> { + 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 { + 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 { + 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 { + 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()); + } +} diff --git a/crates/dns-server/src/router.rs b/crates/dns-server/src/router.rs new file mode 100644 index 0000000..bb80ffd --- /dev/null +++ b/crates/dns-server/src/router.rs @@ -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, + pub cache_ns: u16, + pub fallback_recursion: bool, +} + +pub struct Router { + pub rules: Vec, + pub default: DefaultResolution, + pub default_pool: Option>, + pub default_ns: u16, + pub resolver: Option>, + pub cache: Arc, + /// 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, resolver: Option>) -> Result { + 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, 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 + } +} diff --git a/crates/dns-server/src/runtime.rs b/crates/dns-server/src/runtime.rs new file mode 100644 index 0000000..6543e42 --- /dev/null +++ b/crates/dns-server/src/runtime.rs @@ -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, + pub zones: Arc, + 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>, +} + +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, previous: Option<&Runtime>) -> Result<(Self, Vec>), String> { + let errors: Vec = 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, + pub cache: Arc, + runtime: RwLock>, + pub config_path: Option, + 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, metrics: Arc, config_path: Option, 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 { + 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(); + } +} diff --git a/crates/dns-server/src/server.rs b/crates/dns-server/src/server.rs new file mode 100644 index 0000000..f075463 --- /dev/null +++ b/crates/dns-server/src/server.rs @@ -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, + pub dot: Vec, + pub doh: Vec, +} + +/// Running server. +pub struct ServerHandle { + pub shared: Arc, + pub bound: Bound, + shutdown_tx: watch::Sender, + tasks: std::sync::Mutex>>, +} + +/// What a reload changed. +#[derive(Debug, Clone, Serialize, Default)] +pub struct ReloadReport { + pub zones: usize, + pub new_zones: Vec, + pub restart_required: Vec, +} + +fn spawn_secondary(e: Arc) { + 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, overrides: Overrides) -> Result { + 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 { + 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 { + 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> = 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 { + self.shutdown_tx.subscribe() + } +} diff --git a/crates/dns-server/src/tls.rs b/crates/dns-server/src/tls.rs new file mode 100644 index 0000000..e5490c1 --- /dev/null +++ b/crates/dns-server/src/tls.rs @@ -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>, + stamp: Mutex<(Option, Option)>, +} + +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 { + std::fs::metadata(p).and_then(|m| m.modified()).ok() +} + +fn load_certified_key(cert: &Path, key: &Path) -> Result { + let certs: Vec> = CertificateDer::pem_file_iter(cert) + .map_err(|e| format!("{}: {e}", cert.display()))? + .collect::>() + .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, 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 { + 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, every: Duration, mut shutdown: watch::Receiver) { + 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> { + 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, alpn: &[&[u8]]) -> Result, 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, 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, listener: TcpListener, tls: Arc, mut shutdown: watch::Receiver) { + 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>; + +fn reply(status: u16, ctype: &str, body: impl Into) -> 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, peer: SocketAddr) -> DohResponse { + if req.uri().path() != "/dns-query" { + return reply(404, "text/plain", "not found\n"); + } + let msg: Vec = 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::().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(shared: Arc, 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, listener: TcpListener, tls: Option>, mut shutdown: watch::Receiver) { + 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 { + 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); + } +} diff --git a/crates/dns-server/tests/authoritative.rs b/crates/dns-server/tests/authoritative.rs new file mode 100644 index 0000000..26d4a52 --- /dev/null +++ b/crates/dns-server/tests/authoritative.rs @@ -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; +} diff --git a/crates/dns-server/tests/common/mod.rs b/crates/dns-server/tests/common/mod.rs new file mode 100644 index 0000000..36fab1c --- /dev/null +++ b/crates/dns-server/tests/common/mod.rs @@ -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 { + let mut v: Vec = 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(what: &str, mut f: F) +where + F: FnMut() -> Fut, + Fut: std::future::Future, +{ + 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="; diff --git a/crates/dns-server/tests/dnssec.rs b/crates/dns-server/tests/dnssec.rs new file mode 100644 index 0000000..7129a8c --- /dev/null +++ b/crates/dns-server/tests/dnssec.rs @@ -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 = + 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 = + 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; +} diff --git a/crates/dns-server/tests/performance.rs b/crates/dns-server/tests/performance.rs new file mode 100644 index 0000000..2c631d4 --- /dev/null +++ b/crates/dns-server/tests/performance.rs @@ -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) { + 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 = 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; +} diff --git a/crates/dns-server/tests/resolver.rs b/crates/dns-server/tests/resolver.rs new file mode 100644 index 0000000..22a62f6 --- /dev/null +++ b/crates/dns-server/tests/resolver.rs @@ -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, + _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; + } +} diff --git a/crates/dns-server/tests/robustness.rs b/crates/dns-server/tests/robustness.rs new file mode 100644 index 0000000..c031b4d --- /dev/null +++ b/crates/dns-server/tests/robustness.rs @@ -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> = ["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 = 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; +} diff --git a/crates/dns-server/tests/transport.rs b/crates/dns-server/tests/transport.rs new file mode 100644 index 0000000..ca78b35 --- /dev/null +++ b/crates/dns-server/tests/transport.rs @@ -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 { + 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, 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; +} diff --git a/crates/dns-tools/Cargo.toml b/crates/dns-tools/Cargo.toml new file mode 100644 index 0000000..be54271 --- /dev/null +++ b/crates/dns-tools/Cargo.toml @@ -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 diff --git a/crates/dns-tools/src/bench.rs b/crates/dns-tools/src/bench.rs new file mode 100644 index 0000000..9ed1685 --- /dev/null +++ b/crates/dns-tools/src/bench.rs @@ -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, + #[arg(short, long)] + pub name: Option, + #[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, +} + +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>, + qps: u32, + duration: Duration, + total: Option, + 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 +} diff --git a/crates/dns-tools/src/bin/easybench.rs b/crates/dns-tools/src/bin/easybench.rs new file mode 100644 index 0000000..a644239 --- /dev/null +++ b/crates/dns-tools/src/bin/easybench.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::bench::main() +} diff --git a/crates/dns-tools/src/bin/easyconf.rs b/crates/dns-tools/src/bin/easyconf.rs new file mode 100644 index 0000000..0c0002c --- /dev/null +++ b/crates/dns-tools/src/bin/easyconf.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::conf::main() +} diff --git a/crates/dns-tools/src/bin/easydiff.rs b/crates/dns-tools/src/bin/easydiff.rs new file mode 100644 index 0000000..03239df --- /dev/null +++ b/crates/dns-tools/src/bin/easydiff.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::diff::main() +} diff --git a/crates/dns-tools/src/bin/easydig.rs b/crates/dns-tools/src/bin/easydig.rs new file mode 100644 index 0000000..d95874b --- /dev/null +++ b/crates/dns-tools/src/bin/easydig.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::dig::main() +} diff --git a/crates/dns-tools/src/bin/easydnssec.rs b/crates/dns-tools/src/bin/easydnssec.rs new file mode 100644 index 0000000..9f9f619 --- /dev/null +++ b/crates/dns-tools/src/bin/easydnssec.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::dnssec::main() +} diff --git a/crates/dns-tools/src/bin/easydoh.rs b/crates/dns-tools/src/bin/easydoh.rs new file mode 100644 index 0000000..4034cc9 --- /dev/null +++ b/crates/dns-tools/src/bin/easydoh.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::doh::main() +} diff --git a/crates/dns-tools/src/bin/easydot.rs b/crates/dns-tools/src/bin/easydot.rs new file mode 100644 index 0000000..55a5ae8 --- /dev/null +++ b/crates/dns-tools/src/bin/easydot.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::dot::main() +} diff --git a/crates/dns-tools/src/bin/easyhost.rs b/crates/dns-tools/src/bin/easyhost.rs new file mode 100644 index 0000000..3d0495f --- /dev/null +++ b/crates/dns-tools/src/bin/easyhost.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::host::main() +} diff --git a/crates/dns-tools/src/bin/easynslookup.rs b/crates/dns-tools/src/bin/easynslookup.rs new file mode 100644 index 0000000..50d03e1 --- /dev/null +++ b/crates/dns-tools/src/bin/easynslookup.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::nslookup::main() +} diff --git a/crates/dns-tools/src/bin/easyptr.rs b/crates/dns-tools/src/bin/easyptr.rs new file mode 100644 index 0000000..a3cbeb9 --- /dev/null +++ b/crates/dns-tools/src/bin/easyptr.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::ptr::main() +} diff --git a/crates/dns-tools/src/bin/easytrace.rs b/crates/dns-tools/src/bin/easytrace.rs new file mode 100644 index 0000000..b7e8d6c --- /dev/null +++ b/crates/dns-tools/src/bin/easytrace.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::trace::main() +} diff --git a/crates/dns-tools/src/bin/easywhois.rs b/crates/dns-tools/src/bin/easywhois.rs new file mode 100644 index 0000000..0e641f7 --- /dev/null +++ b/crates/dns-tools/src/bin/easywhois.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::whois::main() +} diff --git a/crates/dns-tools/src/bin/easyzone.rs b/crates/dns-tools/src/bin/easyzone.rs new file mode 100644 index 0000000..b182ce6 --- /dev/null +++ b/crates/dns-tools/src/bin/easyzone.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::zone::main() +} diff --git a/crates/dns-tools/src/bin/ebench.rs b/crates/dns-tools/src/bin/ebench.rs new file mode 100644 index 0000000..a644239 --- /dev/null +++ b/crates/dns-tools/src/bin/ebench.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::bench::main() +} diff --git a/crates/dns-tools/src/bin/econf.rs b/crates/dns-tools/src/bin/econf.rs new file mode 100644 index 0000000..0c0002c --- /dev/null +++ b/crates/dns-tools/src/bin/econf.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::conf::main() +} diff --git a/crates/dns-tools/src/bin/ed.rs b/crates/dns-tools/src/bin/ed.rs new file mode 100644 index 0000000..d95874b --- /dev/null +++ b/crates/dns-tools/src/bin/ed.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::dig::main() +} diff --git a/crates/dns-tools/src/bin/ediff.rs b/crates/dns-tools/src/bin/ediff.rs new file mode 100644 index 0000000..03239df --- /dev/null +++ b/crates/dns-tools/src/bin/ediff.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::diff::main() +} diff --git a/crates/dns-tools/src/bin/ednssec.rs b/crates/dns-tools/src/bin/ednssec.rs new file mode 100644 index 0000000..9f9f619 --- /dev/null +++ b/crates/dns-tools/src/bin/ednssec.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::dnssec::main() +} diff --git a/crates/dns-tools/src/bin/edoh.rs b/crates/dns-tools/src/bin/edoh.rs new file mode 100644 index 0000000..4034cc9 --- /dev/null +++ b/crates/dns-tools/src/bin/edoh.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::doh::main() +} diff --git a/crates/dns-tools/src/bin/edot.rs b/crates/dns-tools/src/bin/edot.rs new file mode 100644 index 0000000..55a5ae8 --- /dev/null +++ b/crates/dns-tools/src/bin/edot.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::dot::main() +} diff --git a/crates/dns-tools/src/bin/eh.rs b/crates/dns-tools/src/bin/eh.rs new file mode 100644 index 0000000..3d0495f --- /dev/null +++ b/crates/dns-tools/src/bin/eh.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::host::main() +} diff --git a/crates/dns-tools/src/bin/ens.rs b/crates/dns-tools/src/bin/ens.rs new file mode 100644 index 0000000..50d03e1 --- /dev/null +++ b/crates/dns-tools/src/bin/ens.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::nslookup::main() +} diff --git a/crates/dns-tools/src/bin/eptr.rs b/crates/dns-tools/src/bin/eptr.rs new file mode 100644 index 0000000..a3cbeb9 --- /dev/null +++ b/crates/dns-tools/src/bin/eptr.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::ptr::main() +} diff --git a/crates/dns-tools/src/bin/etrace.rs b/crates/dns-tools/src/bin/etrace.rs new file mode 100644 index 0000000..b7e8d6c --- /dev/null +++ b/crates/dns-tools/src/bin/etrace.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::trace::main() +} diff --git a/crates/dns-tools/src/bin/ewhois.rs b/crates/dns-tools/src/bin/ewhois.rs new file mode 100644 index 0000000..0e641f7 --- /dev/null +++ b/crates/dns-tools/src/bin/ewhois.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::whois::main() +} diff --git a/crates/dns-tools/src/bin/ezone.rs b/crates/dns-tools/src/bin/ezone.rs new file mode 100644 index 0000000..b182ce6 --- /dev/null +++ b/crates/dns-tools/src/bin/ezone.rs @@ -0,0 +1,3 @@ +fn main() -> std::process::ExitCode { + dns_tools::zone::main() +} diff --git a/crates/dns-tools/src/common.rs b/crates/dns-tools/src/common.rs new file mode 100644 index 0000000..aa93474 --- /dev/null +++ b/crates/dns-tools/src/common.rs @@ -0,0 +1,239 @@ +//! Shared helpers: resolver discovery, argument helpers, formatting, colours, JSON. +use std::io::IsTerminal; +use std::net::{IpAddr, SocketAddr}; +use std::process::ExitCode; +use std::time::Duration; + +use dns_core::client::Exchange; +use dns_core::proto::op::{Message, ResponseCode}; +use dns_core::proto::rr::{Name, Record, RecordType}; +use serde_json::{Value, json}; + +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +pub const EXIT_OK: u8 = 0; +pub const EXIT_USAGE: u8 = 1; +pub const EXIT_NO_REPLY: u8 = 9; +pub const EXIT_INTERNAL: u8 = 10; + +/// Build a current-thread Tokio runtime and run `f`. +pub fn block_on>(f: F) -> ExitCode { + dns_core::quiet_broken_pipe(); + match tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build() { + Ok(rt) => rt.block_on(f), + Err(e) => { + eprintln!("cannot start runtime: {e}"); + ExitCode::from(EXIT_INTERNAL) + } + } +} + +/// First nameserver from /etc/resolv.conf (or 127.0.0.1). +pub fn system_resolver() -> IpAddr { + std::fs::read_to_string("/etc/resolv.conf") + .ok() + .and_then(|t| { + t.lines() + .filter_map(|l| l.trim().strip_prefix("nameserver")) + .filter_map(|v| v.trim().split('%').next().and_then(|a| a.parse().ok())) + .next() + }) + .unwrap_or(IpAddr::from([127, 0, 0, 1])) +} + +/// Resolve a server argument (IP, IP:port, [v6]:port, or host name via the system resolver). +pub async fn server_addr(s: &str, port: u16) -> Result { + let s = s.trim_start_matches('@'); + if let Ok(a) = s.parse::() { + return Ok(a); + } + if let Ok(ip) = s.trim_matches(['[', ']']).parse::() { + return Ok(SocketAddr::new(ip, port)); + } + // dig syntax 1.2.3.4#5353 + if let Some((h, p)) = s.split_once('#') + && let (Ok(ip), Ok(p)) = (h.parse::(), p.parse::()) + { + return Ok(SocketAddr::new(ip, p)); + } + tokio::net::lookup_host((s, port)) + .await + .map_err(|e| format!("cannot resolve server '{s}': {e}"))? + .next() + .ok_or_else(|| format!("cannot resolve server '{s}'")) +} + +/// Parse a record type name or TYPEnnn. +pub fn parse_type(s: &str) -> Option { + let u = s.to_ascii_uppercase(); + if let Some(n) = u.strip_prefix("TYPE") { + return n.parse::().ok().map(RecordType::from); + } + u.parse::().ok().filter(|t| !matches!(t, RecordType::Unknown(_))) +} + +/// Parse durations like `2s`, `500ms`, `5` (seconds). +pub fn parse_duration(s: &str) -> Result { + dns_config::duration::parse(s) +} + +/// ANSI colours only on a TTY and when not disabled. +#[derive(Clone, Copy)] +pub struct Colors { + pub on: bool, +} + +impl Colors { + pub fn detect(no_color: bool) -> Self { + Self { on: !no_color && std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal() } + } + pub fn paint(&self, code: &str, s: &str) -> String { + if self.on { format!("\x1b[{code}m{s}\x1b[0m") } else { s.to_string() } + } + pub fn bold(&self, s: &str) -> String { + self.paint("1", s) + } + pub fn rcode(&self, r: ResponseCode) -> String { + let code = match r { + ResponseCode::NoError => "32", + ResponseCode::NXDomain => "33", + _ => "31", + }; + self.paint(code, &rcode_str(r)) + } +} + +pub fn rcode_str(r: ResponseCode) -> String { + match r { + ResponseCode::NoError => "NOERROR".into(), + ResponseCode::FormErr => "FORMERR".into(), + ResponseCode::ServFail => "SERVFAIL".into(), + ResponseCode::NXDomain => "NXDOMAIN".into(), + ResponseCode::NotImp => "NOTIMP".into(), + ResponseCode::Refused => "REFUSED".into(), + ResponseCode::YXDomain => "YXDOMAIN".into(), + ResponseCode::NotAuth => "NOTAUTH".into(), + ResponseCode::NotZone => "NOTZONE".into(), + ResponseCode::BADVERS => "BADVERS".into(), + other => format!("RCODE{}", u16::from(other)), + } +} + +pub fn flags_str(m: &Message) -> String { + let md = &m.metadata; + let mut f = Vec::new(); + if md.message_type == dns_core::proto::op::MessageType::Response { + f.push("qr"); + } + for (on, n) in [ + (md.authoritative, "aa"), + (md.truncation, "tc"), + (md.recursion_desired, "rd"), + (md.recursion_available, "ra"), + (md.authentic_data, "ad"), + (md.checking_disabled, "cd"), + ] { + if on { + f.push(n); + } + } + f.join(" ") +} + +/// Zone-file style line for a record (dig formatting). +pub fn rr_line(r: &Record) -> String { + let name = r.name.to_string(); + let pad = if name.len() < 24 { 24 - name.len() } else { 1 }; + format!("{name}{}{}\t{}\t{}\t{}", " ".repeat(pad), r.ttl, r.dns_class, r.record_type(), r.data) +} + +pub fn rr_json(r: &Record) -> Value { + json!({ "name": r.name.to_string(), "ttl": r.ttl, "class": r.dns_class.to_string(), "type": r.record_type().to_string(), "data": r.data.to_string() }) +} + +/// Structured representation of an exchange (for --json / --yaml). +pub fn exchange_json(ex: &Exchange) -> Value { + let m = &ex.message; + json!({ + "server": ex.server.to_string(), + "transport": ex.transport, + "query_time_ms": (ex.elapsed.as_secs_f64() * 1000.0 * 100.0).round() / 100.0, + "message_size": ex.size, + "tsig_verified": ex.tsig_verified, + "header": { + "id": m.metadata.id, + "opcode": format!("{:?}", m.metadata.op_code).to_uppercase(), + "status": rcode_str(m.metadata.response_code), + "flags": flags_str(m).split(' ').filter(|s| !s.is_empty()).collect::>(), + }, + "edns": m.edns.as_ref().map(|e| json!({ "version": e.version(), "udp_size": e.max_payload(), "do": e.flags().dnssec_ok })), + "question": m.queries.iter().map(|q| json!({ "name": q.name.to_string(), "class": q.query_class.to_string(), "type": q.query_type.to_string() })).collect::>(), + "answer": m.answers.iter().map(rr_json).collect::>(), + "authority": m.authorities.iter().map(rr_json).collect::>(), + "additional": m.additionals.iter().map(rr_json).collect::>(), + }) +} + +/// Print JSON or YAML. +pub fn print_structured(v: &Value, yaml: bool) { + if yaml { + print!("{}", serde_norway::to_string(v).unwrap_or_default()); + } else { + println!("{}", serde_json::to_string_pretty(v).unwrap_or_default()); + } +} + +/// Parse a name, accepting IDN input. +pub fn name_arg(s: &str) -> Result { + dns_core::names::parse_name(s).map_err(|e| e.to_string()) +} + +/// Error helper. +pub fn fail(tool: &str, code: u8, msg: impl std::fmt::Display) -> ExitCode { + eprintln!("{tool}: {msg}"); + ExitCode::from(code) +} + +/// Exit code for a transport error. +pub fn net_error(tool: &str, e: &dns_core::CoreError) -> ExitCode { + match e { + dns_core::CoreError::Timeout(_) | dns_core::CoreError::Io(_) => fail(tool, EXIT_NO_REPLY, format!("communications error: {e}")), + _ => fail(tool, EXIT_INTERNAL, e), + } +} + +/// Order-insensitive set of (type, data) for comparisons. +pub fn rrset_key(records: &[Record]) -> Vec { + let mut v: Vec = records.iter().map(|r| format!("{} {} {}", r.name.to_lowercase(), r.record_type(), r.data)).collect(); + v.sort(); + v.dedup(); + v +} + +/// Percentile of sorted samples. +pub fn percentile(sorted: &[f64], p: f64) -> f64 { + if sorted.is_empty() { + return 0.0; + } + let idx = ((sorted.len() as f64 - 1.0) * p).round() as usize; + sorted[idx.min(sorted.len() - 1)] +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn helpers() { + assert_eq!(parse_type("mx"), Some(RecordType::MX)); + assert_eq!(parse_type("TYPE65"), Some(RecordType::HTTPS)); + assert_eq!(parse_type("bogus"), None); + assert_eq!(percentile(&[1.0, 2.0, 3.0, 4.0], 0.5), 3.0); + assert_eq!(parse_duration("2s").unwrap().as_secs(), 2); + } + #[tokio::test] + async fn server_parsing() { + assert_eq!(server_addr("@1.1.1.1", 53).await.unwrap().port(), 53); + assert_eq!(server_addr("127.0.0.1#5353", 53).await.unwrap().port(), 5353); + assert_eq!(server_addr("[::1]:54", 53).await.unwrap().port(), 54); + } +} diff --git a/crates/dns-tools/src/conf.rs b/crates/dns-tools/src/conf.rs new file mode 100644 index 0000000..181f517 --- /dev/null +++ b/crates/dns-tools/src/conf.rs @@ -0,0 +1,53 @@ +//! `econf` / `easyconf` – configuration validation (named-checkconf). +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::{Parser, Subcommand}; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "econf", version = VERSION, about = "EasyConf – validate EasyDNS configuration")] +pub struct Args { + #[command(subcommand)] + pub cmd: Cmd, + #[arg(long, global = true)] + pub json: bool, +} + +#[derive(Subcommand, Debug)] +pub enum Cmd { + /// Validate a configuration file (and the zone files it references) + Check { file: PathBuf }, + /// Print the effective configuration + Print { file: PathBuf }, +} + +pub fn main() -> ExitCode { + let a = Args::parse(); + match a.cmd { + Cmd::Check { file } => match dns_config::Config::load(&file) { + Ok(cfg) => { + let f = dns_server::check::check_config(&cfg); + let errors = f.iter().filter(|x| x.severity == "error").count(); + if a.json { + print_structured(&serde_json::to_value(&f).unwrap_or_default(), false); + } else { + for x in &f { + println!("{x}"); + } + println!("{}: {}", file.display(), if errors == 0 { "OK" } else { "FAILED" }); + } + if errors == 0 { ExitCode::SUCCESS } else { ExitCode::from(1) } + } + Err(e) => fail("econf", 1, e), + }, + Cmd::Print { file } => match dns_config::Config::load(&file) { + Ok(cfg) => { + print!("{}", serde_norway::to_string(&cfg).unwrap_or_default()); + ExitCode::SUCCESS + } + Err(e) => fail("econf", 1, e), + }, + } +} diff --git a/crates/dns-tools/src/diff.rs b/crates/dns-tools/src/diff.rs new file mode 100644 index 0000000..6fe1912 --- /dev/null +++ b/crates/dns-tools/src/diff.rs @@ -0,0 +1,124 @@ +//! `ediff` / `easydiff` – compare answers from several resolvers. +//! RRset order is ignored; TTL differences are reported separately and do not +//! count as a mismatch (TTLs decrease in caches). +use std::process::ExitCode; + +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 = "ediff", version = VERSION, about = "EasyDiff – compare DNS answers from several servers")] +pub struct Args { + pub name: String, + /// Record type and servers (@1.1.1.1 @8.8.8.8 ...); type defaults to A + pub rest: Vec, + #[arg(short, long, default_value_t = 53)] + pub port: u16, + #[arg(long)] + pub json: bool, + /// Treat TTL differences as mismatches + #[arg(long)] + pub strict_ttl: bool, +} + +pub fn main() -> ExitCode { + let a = Args::parse(); + let name = match name_arg(&a.name) { + Ok(n) => n, + Err(e) => return fail("ediff", EXIT_USAGE, e), + }; + let mut t = RecordType::A; + let mut servers = Vec::new(); + for r in &a.rest { + if let Some(s) = r.strip_prefix('@') { + servers.push(s.to_string()); + } else if let Some(x) = parse_type(r) { + t = x; + } else { + servers.push(r.clone()); + } + } + if servers.is_empty() { + servers.push(system_resolver().to_string()); + } + let _ = a.strict_ttl; + block_on(run_compare(&name, t, &servers, a.port, a.json, QueryOptions::default())) +} + +/// Compare and print; exit 0 when all agree, 1 on differences, 9 when a server fails. +pub async fn run_compare(name: &Name, t: RecordType, servers: &[String], port: u16, json_out: bool, opts: QueryOptions) -> ExitCode { + let mut rows = Vec::new(); + for s in servers { + let addr = match server_addr(s, port).await { + Ok(a) => a, + Err(e) => return fail("ediff", EXIT_USAGE, e), + }; + let res = query(addr, name, t, &opts).await; + rows.push((s.clone(), res)); + } + let mut sets = Vec::new(); + let mut failed = false; + let mut out = Vec::new(); + for (s, r) in &rows { + match r { + Ok(ex) => { + let m = &ex.message; + let key = rrset_key(&m.answers); + let ttls: Vec = m.answers.iter().map(|r| r.ttl).collect(); + out.push(json!({ "server": s, "status": rcode_str(m.metadata.response_code), "flags": flags_str(m), "answers": key, "ttls": ttls, "ms": ex.elapsed.as_secs_f64() * 1000.0 })); + sets.push((rcode_str(m.metadata.response_code), key)); + } + Err(e) => { + failed = true; + out.push(json!({ "server": s, "error": e.to_string() })); + } + } + } + let consistent = sets.windows(2).all(|w| w[0] == w[1]); + if json_out { + print_structured( + &json!({ "name": name.to_string(), "type": t.to_string(), "consistent": consistent && !failed, "results": out }), + false, + ); + } else { + println!(";; {name} {t}"); + for r in &out { + if let Some(e) = r.get("error") { + println!("{:<22} ERROR {}", r["server"].as_str().unwrap_or(""), e); + continue; + } + println!( + "{:<22} {:<9} [{}] {:>7.1} ms ttl {:?}", + r["server"].as_str().unwrap_or(""), + r["status"].as_str().unwrap_or(""), + r["flags"].as_str().unwrap_or(""), + r["ms"].as_f64().unwrap_or(0.0), + r["ttls"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64()).collect::>()).unwrap_or_default() + ); + for a in r["answers"].as_array().into_iter().flatten() { + println!(" {}", a.as_str().unwrap_or("")); + } + } + println!( + ";; {}", + if failed { + "some servers failed" + } else if consistent { + "all servers agree" + } else { + "DIFFERENCES FOUND" + } + ); + } + if failed { + ExitCode::from(EXIT_NO_REPLY) + } else if consistent { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } +} diff --git a/crates/dns-tools/src/dig.rs b/crates/dns-tools/src/dig.rs new file mode 100644 index 0000000..0708318 --- /dev/null +++ b/crates/dns-tools/src/dig.rs @@ -0,0 +1,498 @@ +//! `ed` / `easydig` – dig replacement. +//! +//! Supports the common dig syntax: `@server`, `-p`, `-t`, `-c`, `-q`, `-x`, `-y`, `-4/-6`, +//! `+short`, `+trace`, `+dnssec`, `+tcp`, `+[no]recurse`, `+cd`, `+time=`, `+tries=`, +//! `+bufsize=`, `+[no]edns`, `+[no]all`, `+[no]question|answer|authority|additional|stats|cmd`, +//! plus `--json`, `--yaml`, `--watch`, `--compare`, `--benchmark`, `--timeout`, `--server`, +//! `--port`, `--no-color`. +use std::net::IpAddr; +use std::process::ExitCode; +use std::time::Duration; + +use dns_core::client::{QueryOptions, build_query, exchange}; +use dns_core::proto::rr::{DNSClass, Name, RecordType}; +use dns_core::tsig::TsigKey; + +use crate::common::*; + +#[derive(Debug, Clone)] +pub struct DigOpts { + pub server: Option, + pub port: u16, + pub name: Option, + pub rtype: Option, + pub class: DNSClass, + pub short: bool, + pub trace: bool, + pub dnssec: bool, + pub tcp: bool, + pub recurse: bool, + pub cd: bool, + pub ignore_tc: bool, + pub json: bool, + pub yaml: bool, + pub watch: Option, + pub compare: Vec, + pub benchmark: Option, + pub timeout: Duration, + pub tries: u32, + pub bufsize: u16, + pub edns: bool, + pub show: Sections, + pub no_color: bool, + pub v4_only: bool, + pub v6_only: bool, + pub tsig: Option, +} + +#[derive(Debug, Clone, Copy)] +pub struct Sections { + pub cmd: bool, + pub question: bool, + pub answer: bool, + pub authority: bool, + pub additional: bool, + pub stats: bool, + pub comments: bool, +} + +impl Sections { + fn all(v: bool) -> Self { + Self { cmd: v, question: v, answer: v, authority: v, additional: v, stats: v, comments: v } + } +} + +impl Default for DigOpts { + fn default() -> Self { + Self { + server: None, + port: 53, + name: None, + rtype: None, + class: DNSClass::IN, + short: false, + trace: false, + dnssec: false, + tcp: false, + recurse: true, + cd: false, + ignore_tc: false, + json: false, + yaml: false, + watch: None, + compare: Vec::new(), + benchmark: None, + timeout: Duration::from_secs(5), + tries: 3, + bufsize: 1232, + edns: true, + show: Sections::all(true), + no_color: false, + v4_only: false, + v6_only: false, + tsig: None, + } + } +} + +pub const USAGE: &str = "Usage: ed [@server] [-p port] [-t type] [-x addr] [-y [alg:]name:key] name [type] [class] [+opts] [--json|--yaml] [--watch DUR] [--compare S1,S2] [--benchmark N] [--timeout DUR]"; + +/// Parse dig-style arguments. +pub fn parse_args(args: &[String]) -> Result { + let mut o = DigOpts::default(); + let mut it = args.iter().peekable(); + let need = |it: &mut std::iter::Peekable>, flag: &str| -> Result { + it.next().cloned().ok_or_else(|| format!("option {flag} requires an argument")) + }; + while let Some(a) = it.next() { + let a = a.as_str(); + if let Some(s) = a.strip_prefix('@') { + o.server = Some(s.to_string()); + } else if let Some(p) = a.strip_prefix('+') { + let (neg, p) = match p.strip_prefix("no") { + Some(rest) => (true, rest), + None => (false, p), + }; + let (key, val) = p.split_once('=').map(|(k, v)| (k, Some(v))).unwrap_or((p, None)); + match key { + "short" => o.short = !neg, + "trace" => o.trace = !neg, + "dnssec" | "do" => o.dnssec = !neg, + "tcp" | "vc" => o.tcp = !neg, + "recurse" | "rec" => o.recurse = !neg, + "cd" | "cdflag" => o.cd = !neg, + "ignore" => o.ignore_tc = !neg, + "edns" => o.edns = !neg, + "all" => o.show = Sections::all(!neg), + "cmd" => o.show.cmd = !neg, + "question" => o.show.question = !neg, + "answer" => o.show.answer = !neg, + "authority" => o.show.authority = !neg, + "additional" => o.show.additional = !neg, + "stats" => o.show.stats = !neg, + "comments" => o.show.comments = !neg, + "time" | "timeout" => o.timeout = Duration::from_secs(val.and_then(|v| v.parse().ok()).ok_or("+time=N")?), + "tries" => o.tries = val.and_then(|v| v.parse().ok()).ok_or("+tries=N")?, + "retry" => o.tries = val.and_then(|v| v.parse::().ok()).ok_or("+retry=N")? + 1, + "bufsize" => o.bufsize = val.and_then(|v| v.parse().ok()).ok_or("+bufsize=N")?, + "json" => o.json = !neg, + "yaml" => o.yaml = !neg, + "multiline" | "cookie" | "nsid" | "identify" | "ttlid" | "class" | "ttlunits" => {} + other => return Err(format!("unknown option +{other}")), + } + } else if a == "-x" { + let ip: IpAddr = need(&mut it, "-x")?.parse().map_err(|_| "invalid address for -x")?; + o.name = Some(dns_core::names::reverse_name(ip)); + o.rtype = Some(RecordType::PTR); + } else if a == "-p" || a == "--port" { + o.port = need(&mut it, a)?.parse().map_err(|_| "invalid port")?; + } else if a == "-t" { + let v = need(&mut it, "-t")?; + o.rtype = Some(parse_type(&v).ok_or_else(|| format!("unknown type {v}"))?); + } else if a == "-c" { + let v = need(&mut it, "-c")?; + o.class = v.to_ascii_uppercase().parse().map_err(|_| format!("unknown class {v}"))?; + } else if a == "-q" { + o.name = Some(name_arg(&need(&mut it, "-q")?)?); + } else if a == "-y" { + let v = need(&mut it, "-y")?; + let parts: Vec<&str> = v.split(':').collect(); + let (alg, name, secret) = match parts.as_slice() { + [n, s] => ("hmac-sha256", *n, *s), + [a, n, s] => (*a, *n, *s), + _ => return Err("-y expects [alg:]name:base64secret".into()), + }; + o.tsig = Some(TsigKey::new(name, alg, secret).map_err(|e| e.to_string())?); + } else if a == "-4" { + o.v4_only = true; + } else if a == "-6" { + o.v6_only = true; + } else if a == "--json" { + o.json = true; + } else if a == "--yaml" { + o.yaml = true; + } else if a == "--no-color" { + o.no_color = true; + } else if a == "--server" { + o.server = Some(need(&mut it, a)?); + } else if a == "--timeout" { + o.timeout = parse_duration(&need(&mut it, a)?)?; + } else if a == "--watch" { + o.watch = Some(parse_duration(&need(&mut it, a)?)?); + } else if a == "--compare" { + o.compare = need(&mut it, a)?.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(); + } else if a == "--benchmark" { + o.benchmark = Some(need(&mut it, a)?.parse().map_err(|_| "--benchmark N")?); + } else if a.starts_with('-') && a.len() > 1 { + return Err(format!("unknown option {a}")); + } else if o.name.is_some() && o.rtype.is_none() && parse_type(a).is_some() { + o.rtype = parse_type(a); + } else if o.name.is_some() && matches!(a.to_ascii_uppercase().as_str(), "IN" | "CH" | "HS" | "ANY") { + o.class = a.to_ascii_uppercase().parse().map_err(|_| "class")?; + } else if o.name.is_none() { + o.name = Some(name_arg(a)?); + } else if o.rtype.is_none() { + return Err(format!("unknown type '{a}'")); + } else { + return Err(format!("unexpected argument '{a}'")); + } + } + if o.name.is_none() { + o.name = Some(Name::root()); + o.rtype.get_or_insert(RecordType::NS); + } + Ok(o) +} + +pub fn query_options(o: &DigOpts) -> QueryOptions { + QueryOptions { + timeout: o.timeout, + retries: o.tries.saturating_sub(1), + tcp_only: o.tcp || matches!(o.rtype, Some(RecordType::AXFR | RecordType::IXFR)), + ignore_tc: o.ignore_tc, + edns: o.edns, + edns_payload: o.bufsize, + dnssec_ok: o.dnssec, + recursion_desired: o.recurse, + checking_disabled: o.cd, + tsig: o.tsig.clone(), + } +} + +/// Print a full exchange in dig format. +pub fn print_dig(ex: &dns_core::client::Exchange, o: &DigOpts, c: Colors, cmdline: &str) { + let m = &ex.message; + let s = &o.show; + if s.cmd { + println!("\n; <<>> EasyDig {VERSION} <<>> {cmdline}"); + println!(";; global options: +cmd"); + } + if s.comments { + println!(";; Got answer:"); + println!( + ";; ->>HEADER<<- opcode: {}, status: {}, id: {}", + format!("{:?}", m.metadata.op_code).to_uppercase(), + c.rcode(m.metadata.response_code), + m.metadata.id + ); + println!( + ";; flags: {}; QUERY: {}, ANSWER: {}, AUTHORITY: {}, ADDITIONAL: {}", + flags_str(m), + m.queries.len(), + m.answers.len(), + m.authorities.len(), + m.additionals.len() + usize::from(m.edns.is_some()) + ); + if !o.recurse && !m.metadata.recursion_available { + } else if o.recurse && !m.metadata.recursion_available { + println!(";; WARNING: recursion requested but not available"); + } + if let Some(e) = &m.edns { + println!("\n;; OPT PSEUDOSECTION:"); + println!("; EDNS: version: {}, flags:{}; udp: {}", e.version(), if e.flags().dnssec_ok { " do" } else { "" }, e.max_payload()); + } + } + if s.question { + println!("\n{}", c.bold(";; QUESTION SECTION:")); + for q in &m.queries { + println!(";{}\t\t{}\t{}", q.name, q.query_class, q.query_type); + } + } + for (show, title, recs) in [ + (s.answer, ";; ANSWER SECTION:", &m.answers), + (s.authority, ";; AUTHORITY SECTION:", &m.authorities), + (s.additional, ";; ADDITIONAL SECTION:", &m.additionals), + ] { + if show && !recs.is_empty() { + println!("\n{}", c.bold(title)); + for r in recs { + println!("{}", rr_line(r)); + } + } + } + if let Some(sig) = &m.signature + && s.additional + { + println!(";; TSIG: key {} ({}){}", sig.name, sig.data.algorithm, if ex.tsig_verified { " verified" } else { "" }); + } + if s.stats { + println!("\n;; Query time: {} msec", ex.elapsed.as_millis()); + println!( + ";; SERVER: {}#{}({}) ({})", + ex.server.ip(), + ex.server.port(), + ex.server.ip(), + format!("{:?}", ex.transport).to_uppercase() + ); + println!(";; WHEN: {}", now_string()); + println!(";; MSG SIZE rcvd: {}\n", ex.size); + } +} + +/// UTC timestamp (RFC 3339-ish) without extra dependencies. +pub fn now_string() -> String { + let t = dns_core::tsig::now(); + let (d, s) = (t / 86400, t % 86400); + let (y, m, dd) = civil(d as i64); + format!("{y:04}-{m:02}-{dd:02} {:02}:{:02}:{:02} UTC", s / 3600, (s / 60) % 60, s % 60) +} + +fn civil(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = (z - era * 146_097) as u64; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + 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; + let y = yoe as i64 + era * 400; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +pub fn print_short(m: &dns_core::proto::op::Message) { + for r in &m.answers { + println!("{}", r.data); + } +} + +pub fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + if args.iter().any(|a| a == "-h" || a == "--help") { + println!("{USAGE}\n\nSee `man ed` or docs/cli-tools.md for all options."); + return ExitCode::SUCCESS; + } + if args.iter().any(|a| a == "-v" || a == "--version") { + println!("EasyDig {VERSION}"); + return ExitCode::SUCCESS; + } + let o = match parse_args(&args) { + Ok(o) => o, + Err(e) => return fail("ed", EXIT_USAGE, format!("{e}\n{USAGE}")), + }; + let cmdline = args.join(" "); + block_on(run(o, cmdline)) +} + +pub async fn run(o: DigOpts, cmdline: String) -> ExitCode { + let c = Colors::detect(o.no_color); + let name = o.name.clone().unwrap_or_else(Name::root); + let rtype = o.rtype.unwrap_or(RecordType::A); + if o.trace { + return crate::trace::run_trace(&name, rtype, o.json || o.yaml, o.yaml, o.dnssec, c).await; + } + if !o.compare.is_empty() { + return crate::diff::run_compare(&name, rtype, &o.compare, o.port, o.json, query_options(&o)).await; + } + let server = match &o.server { + Some(s) => match server_addr(s, o.port).await { + Ok(a) => a, + Err(e) => return fail("ed", EXIT_USAGE, e), + }, + None => std::net::SocketAddr::new(system_resolver(), o.port), + }; + if (o.v4_only && server.is_ipv6()) || (o.v6_only && server.is_ipv4()) { + return fail("ed", EXIT_USAGE, "server address family does not match -4/-6"); + } + if let Some(n) = o.benchmark { + return crate::bench::run_simple(server, &name, rtype, n, 10, o.timeout).await; + } + if matches!(rtype, RecordType::AXFR | RecordType::IXFR) { + return axfr(server, &name, rtype, &o, c).await; + } + let opts = query_options(&o); + let mut previous: Option> = None; + loop { + let mut msg = build_query(&name, rtype, &opts); + if let Some(q) = msg.queries.first_mut() { + q.set_query_class(o.class); + } + match exchange(server, msg, &opts).await { + Ok(ex) => { + if let Some(iv) = o.watch { + let now = rrset_key(&ex.message.answers); + let changed = previous.as_ref().is_some_and(|p| *p != now); + let tag = if previous.is_none() { + "initial" + } else if changed { + "CHANGED" + } else { + "same" + }; + println!( + "{} [{tag}] {} {} {} ms", + now_string(), + rcode_str(ex.message.metadata.response_code), + ex.message.answers.len(), + ex.elapsed.as_millis() + ); + if previous.is_none() || changed { + for r in &ex.message.answers { + println!(" {}", rr_line(r)); + } + } + previous = Some(now); + tokio::select! { + _ = tokio::time::sleep(iv) => continue, + _ = tokio::signal::ctrl_c() => return ExitCode::SUCCESS, + } + } + if o.json || o.yaml { + print_structured(&exchange_json(&ex), o.yaml); + } else if o.short { + print_short(&ex.message); + } else { + print_dig(&ex, &o, c, &cmdline); + } + return ExitCode::SUCCESS; + } + Err(e) => { + if o.watch.is_some() { + println!("{} [error] {e}", now_string()); + tokio::time::sleep(o.watch.unwrap_or(Duration::from_secs(5))).await; + continue; + } + if !o.short && !o.json { + println!(";; communications error to {server}: {e}"); + println!(";; no servers could be reached"); + } + return net_error("ed", &e); + } + } + } +} + +async fn axfr(server: std::net::SocketAddr, name: &Name, rtype: RecordType, o: &DigOpts, c: Colors) -> ExitCode { + let kind = if rtype == RecordType::IXFR { + // dig syntax ixfr=SERIAL is not supported; request IXFR from serial 0 (full) + let soa = dns_core::proto::rr::Record::from_rdata( + name.clone(), + 0, + dns_core::proto::rr::RData::SOA(dns_core::proto::rr::rdata::SOA::new(name.clone(), name.clone(), 0, 0, 0, 0, 0)), + ); + dns_core::client::TransferKind::Ixfr { current_soa: Box::new(soa) } + } else { + dns_core::client::TransferKind::Axfr + }; + let lim = dns_core::client::TransferLimits { timeout: o.timeout.max(Duration::from_secs(30)), ..Default::default() }; + match dns_core::client::transfer(server, name, &kind, o.tsig.as_ref(), lim).await { + Ok(st) => { + if o.json || o.yaml { + print_structured( + &serde_json::json!({ "records": st.records.iter().map(rr_json).collect::>(), "messages": st.messages, "bytes": st.bytes, "tsig_verified": st.tsig_verified }), + o.yaml, + ); + } else { + println!("\n; <<>> EasyDig {VERSION} <<>> {} {name} @{server}", rtype); + for r in &st.records { + println!("{}", rr_line(r)); + } + println!( + "{}", + c.bold(&format!( + ";; XFR size: {} records (messages {}, bytes {}){}", + st.records.len(), + st.messages, + st.bytes, + if st.tsig_verified { ", TSIG verified" } else { "" } + )) + ); + println!(";; Query time: {} msec\n;; SERVER: {server}", st.elapsed.as_millis()); + } + ExitCode::SUCCESS + } + Err(e) => { + println!("; Transfer failed: {e}"); + net_error("ed", &e) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn p(s: &str) -> DigOpts { + parse_args(&s.split_whitespace().map(String::from).collect::>()).unwrap() + } + #[test] + fn dig_syntax() { + let o = p("@1.1.1.1 example.com MX +short +tcp"); + assert_eq!(o.server.as_deref(), Some("1.1.1.1")); + assert_eq!(o.rtype, Some(RecordType::MX)); + assert!(o.short && o.tcp); + let o = p("-x 192.0.2.1"); + assert_eq!(o.name.unwrap().to_string(), "1.2.0.192.in-addr.arpa."); + assert_eq!(o.rtype, Some(RecordType::PTR)); + let o = p("example.com --server 127.0.0.1 --port 5353 --timeout 2s +norecurse +noall +answer"); + assert_eq!(o.port, 5353); + assert!(!o.recurse && o.show.answer && !o.show.question); + let o = p(""); + assert_eq!(o.rtype, Some(RecordType::NS)); + assert!(parse_args(&["+bogus".into()]).is_err()); + let o = p("example.com --compare 1.1.1.1,8.8.8.8 --json"); + assert_eq!(o.compare.len(), 2); + assert!(o.json); + let o = p("-t aaaa example.com CH"); + assert_eq!((o.rtype, o.class), (Some(RecordType::AAAA), DNSClass::CH)); + } +} diff --git a/crates/dns-tools/src/dnssec.rs b/crates/dns-tools/src/dnssec.rs new file mode 100644 index 0000000..0cc4027 --- /dev/null +++ b/crates/dns-tools/src/dnssec.rs @@ -0,0 +1,165 @@ +//! `ednssec` / `easydnssec` – DNSSEC chain-of-trust diagnostics (delv-like). +//! +//! Resolves iteratively from the root with validation and reports, for every zone cut on +//! the way to the name, its DS/DNSKEY key tags and key state, then the validation result +//! of the answer: secure, insecure, bogus (with the reason) or indeterminate. +use std::process::ExitCode; +use std::sync::Arc; +use std::time::Duration; + +use clap::Parser; +use dns_core::answer::Security; +use dns_core::proto::rr::{Name, RecordType}; +use dns_recursive::validator::KeyState; +use serde_json::json; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "ednssec", version = VERSION, about = "EasyDNSSEC – validate a name and show the chain of trust")] +pub struct Args { + pub name: String, + #[arg(default_value = "A")] + pub rtype: String, + /// Trust anchor file (DS/DNSKEY records); default: built-in IANA root KSKs + #[arg(long)] + pub anchors: Option, + #[arg(long)] + pub root_hints: Option, + #[arg(long, default_value_t = 53, hide = true)] + pub port: u16, + #[arg(short, long)] + pub verbose: bool, + #[arg(long)] + pub json: bool, + #[arg(long)] + pub no_color: bool, +} + +pub fn main() -> ExitCode { + block_on(run(Args::parse())) +} + +fn state_str(s: &KeyState) -> (&'static str, String) { + match s { + KeyState::Secure(k) => ( + "secure", + format!( + "{} DNSKEY(s): {}", + k.len(), + k.iter().filter_map(|k| k.calculate_key_tag().ok()).map(|t| t.to_string()).collect::>().join(", ") + ), + ), + KeyState::Insecure => ("insecure", "no DS in parent (provably unsigned) or unsupported algorithm".into()), + KeyState::Bogus(e) => ("bogus", e.clone()), + } +} + +pub async fn run(a: Args) -> ExitCode { + let c = Colors::detect(a.no_color); + let (Ok(name), Some(t)) = (name_arg(&a.name), parse_type(&a.rtype)) else { return fail("ednssec", EXIT_USAGE, "invalid name or type") }; + let hints = match dns_recursive::hints::load(a.root_hints.as_deref()) { + Ok(h) => h, + Err(e) => return fail("ednssec", EXIT_USAGE, e), + }; + let cache = Arc::new(dns_cache::Cache::new(&dns_config::CacheConfig { max_entries: 20_000, ..Default::default() })); + let settings = dns_recursive::Settings { + max_depth: 30, + max_queries: 300, + max_cname: 8, + query_timeout: Duration::from_secs(2), + total_timeout: Duration::from_secs(30), + port: a.port, + qname_minimization: true, + ipv6: false, + max_subqueries_depth: 4, + dnssec: true, + }; + let mut r = match dns_recursive::Resolver::new(settings, hints, cache, 0) { + Ok(r) => r, + Err(e) => return fail("ednssec", EXIT_INTERNAL, e), + }; + if let Some(p) = &a.anchors { + let recs = match dns_core::zonefile::parse_file(p, &Name::root()) { + Ok(r) => r, + Err(e) => return fail("ednssec", EXIT_USAGE, e), + }; + if let Err(e) = r.set_trust_anchors(&recs) { + return fail("ednssec", EXIT_USAGE, e); + } + } + let ans = r.resolve(&name, t).await; + // zone cuts on the path (ancestors that have an SOA at their apex) + let mut zones: Vec = Vec::new(); + let mut anc: Vec = dns_core::names::ancestors(&name).collect(); + anc.reverse(); + for z in anc { + let soa = r.resolve(&z, RecordType::SOA).await; + if soa.answers.iter().any(|x| x.record_type() == RecordType::SOA && x.name.eq_ignore_root_case(&z)) { + zones.push(z); + } + } + let mut chain = Vec::new(); + for z in &zones { + let st = r.zone_key_state(z).await; + let ds = if z.is_root() { + Vec::new() + } else { + r.resolve(z, RecordType::DS).await.answers.iter().filter_map(dns_core::dnssec::ds_of).map(|d| d.key_tag()).collect() + }; + let (s, detail) = state_str(&st); + chain.push((z.to_string(), s, detail, ds)); + } + let sec = ans.security; + let label = match sec { + Security::Secure => "secure", + Security::Insecure => "insecure", + Security::Bogus => "bogus", + Security::Indeterminate => "indeterminate", + }; + if a.json { + print_structured( + &json!({ + "name": name.to_string(), "type": t.to_string(), "status": rcode_str(ans.rcode), "validation": label, "reason": ans.note, + "chain": chain.iter().map(|(z, s, d, ds)| json!({"zone": z, "state": s, "detail": d, "ds_key_tags": ds})).collect::>(), + "answer": ans.answers.iter().filter(|r| a.verbose || r.record_type() != RecordType::RRSIG).map(rr_json).collect::>(), + }), + false, + ); + } else { + println!("; EasyDNSSEC {VERSION} {name} {t}\n"); + println!("{}", c.bold(";; chain of trust")); + for (z, s, d, ds) in &chain { + let col = match *s { + "secure" => c.paint("32", s), + "insecure" => c.paint("33", s), + _ => c.paint("31", s), + }; + let ds_s = if z == "." { + "trust anchor".to_string() + } else if ds.is_empty() { + "no DS".into() + } else { + format!("DS {ds:?}") + }; + println!(";; {z:<32} {col:<10} {ds_s:<22} {d}"); + } + println!(); + let verdict = match sec { + Security::Secure => c.paint("32", "; fully validated"), + Security::Insecure => c.paint("33", "; unsigned answer (insecure)"), + Security::Bogus => c.paint("31", &format!("; validation FAILED: {}", ans.note.clone().unwrap_or_default())), + Security::Indeterminate => c.paint("31", &format!("; could not validate: {}", ans.note.clone().unwrap_or_default())), + }; + println!("{verdict}"); + println!(";; status {}", rcode_str(ans.rcode)); + for rr in ans.answers.iter().filter(|r| a.verbose || r.record_type() != RecordType::RRSIG) { + println!("{}", rr_line(rr)); + } + } + match sec { + Security::Secure | Security::Insecure => ExitCode::SUCCESS, + Security::Bogus => ExitCode::from(2), + Security::Indeterminate => ExitCode::from(EXIT_NO_REPLY), + } +} diff --git a/crates/dns-tools/src/doh.rs b/crates/dns-tools/src/doh.rs new file mode 100644 index 0000000..3a38c28 --- /dev/null +++ b/crates/dns-tools/src/doh.rs @@ -0,0 +1,148 @@ +//! `edoh` / `easydoh` – DNS-over-HTTPS diagnostics (RFC 8484 GET/POST). +use std::process::ExitCode; +use std::time::Duration; + +use clap::Parser; +use dns_core::client::{QueryOptions, build_query}; +use dns_core::proto::op::Message; +use dns_core::tls::DohMethod; +use serde_json::json; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "edoh", version = VERSION, about = "EasyDoH – test a DNS-over-HTTPS endpoint")] +pub struct Args { + /// URL, e.g. https://1.1.1.1/dns-query or https://127.0.0.1:8443/dns-query + pub url: String, + pub name: String, + #[arg(default_value = "A")] + pub rtype: String, + /// HTTP method + #[arg(long, default_value = "post", value_parser = ["get", "post"])] + pub method: String, + /// TLS server name (default: URL host) + #[arg(long)] + pub tls_name: Option, + #[arg(long)] + pub ca: Option, + #[arg(long)] + pub insecure: bool, + #[arg(long, default_value = "5s")] + pub timeout: String, + #[arg(long)] + pub json: bool, + /// Use HTTP/2 (as browsers do) instead of HTTP/1.1; reports whether h2 was negotiated + #[arg(long)] + pub http2: bool, +} + +pub fn main() -> ExitCode { + block_on(run(Args::parse())) +} + +pub async fn run(a: Args) -> ExitCode { + let Some(rest) = a.url.strip_prefix("https://") else { return fail("edoh", EXIT_USAGE, "URL must start with https://") }; + let (hostport, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + let path = if path.is_empty() { "/dns-query" } else { path }; + let host = hostport + .rsplit_once(':') + .filter(|(h, _)| !h.ends_with(']') || h.starts_with('[')) + .map(|(h, _)| h) + .unwrap_or(hostport) + .trim_matches(['[', ']']); + let addr = match server_addr(hostport, 443).await { + Ok(x) => x, + Err(e) => return fail("edoh", EXIT_USAGE, e), + }; + let (Ok(name), Some(t)) = (name_arg(&a.name), parse_type(&a.rtype)) else { return fail("edoh", EXIT_USAGE, "invalid name or type") }; + let ca = match &a.ca { + Some(p) => match std::fs::read(p) { + Ok(b) => Some(b), + Err(e) => return fail("edoh", EXIT_USAGE, format!("{}: {e}", p.display())), + }, + None => None, + }; + let cfg = match dns_core::tls::client_config(ca.as_deref(), a.insecure, &[b"http/1.1"]) { + Ok(c) => c, + Err(e) => return fail("edoh", EXIT_USAGE, e), + }; + let sni = a.tls_name.clone().unwrap_or_else(|| host.to_string()); + let q = build_query(&name, t, &QueryOptions::default()); + let Ok(bytes) = q.to_vec() else { return fail("edoh", EXIT_INTERNAL, "encode") }; + let method = if a.method == "get" { DohMethod::Get } else { DohMethod::Post }; + let timeout = parse_duration(&a.timeout).unwrap_or(Duration::from_secs(5)); + if a.http2 { + let base = match dns_core::tls::client_config(ca.as_deref(), a.insecure, &[]) { + Ok(c) => c, + Err(e) => return fail("edoh", EXIT_USAGE, e), + }; + let c = dns_core::tls_pool::DohClient::new(addr, &sni, path, &base); + let start = std::time::Instant::now(); + return match c.exchange(&bytes, method, timeout).await { + Ok((status, body)) => { + let total = start.elapsed().as_secs_f64() * 1000.0; + let proto = if c.uses_http2() { "HTTP/2" } else { "HTTP/1.1 (server did not offer h2)" }; + let m = Message::from_vec(&body).ok(); + if a.json { + print_structured( + &json!({ "url": a.url, "http_status": status, "protocol": proto, "total_ms": total, + "status": m.as_ref().map(|m| rcode_str(m.metadata.response_code)), + "answer": m.as_ref().map(|m| m.answers.iter().map(rr_json).collect::>()) }), + false, + ); + } else { + println!(";; DoH {} {} over {proto} -> HTTP {status}, total {total:.1} ms", a.method.to_uppercase(), a.url); + if let Some(m) = &m { + println!(";; status {} flags: {}", rcode_str(m.metadata.response_code), flags_str(m)); + for r in &m.answers { + println!("{}", rr_line(r)); + } + } + } + if status == 200 && m.is_some() { ExitCode::SUCCESS } else { ExitCode::from(1) } + } + Err(e) => net_error("edoh", &e), + }; + } + let start = std::time::Instant::now(); + match dns_core::tls::doh_exchange(addr, &sni, path, &bytes, method, timeout, cfg).await { + Ok((status, body, info)) => { + let total = start.elapsed().as_secs_f64() * 1000.0; + let m = Message::from_vec(&body).ok(); + if a.json { + print_structured( + &json!({ "url": a.url, "http_status": status, "method": a.method.to_uppercase(), "tls": info, "total_ms": total, + "status": m.as_ref().map(|m| rcode_str(m.metadata.response_code)), + "answer": m.as_ref().map(|m| m.answers.iter().map(rr_json).collect::>()) }), + false, + ); + } else { + println!(";; DoH {} {} -> HTTP {status}", a.method.to_uppercase(), a.url); + println!( + ";; TLS {} {} ALPN {:?}{}", + info.protocol, + info.cipher_suite, + info.alpn, + if a.insecure { " — NOT VERIFIED" } else { ", certificate verified" } + ); + println!(";; connect {:.1} ms, handshake {:.1} ms, total {total:.1} ms", info.connect_ms, info.handshake_ms); + match &m { + Some(m) => { + println!(";; status {} flags: {}", rcode_str(m.metadata.response_code), flags_str(m)); + for r in &m.answers { + println!("{}", rr_line(r)); + } + } + None => println!( + ";; body is not a DNS message ({} bytes): {}", + body.len(), + String::from_utf8_lossy(&body[..body.len().min(200)]) + ), + } + } + if status == 200 && m.is_some() { ExitCode::SUCCESS } else { ExitCode::from(1) } + } + Err(e) => net_error("edoh", &e), + } +} diff --git a/crates/dns-tools/src/dot.rs b/crates/dns-tools/src/dot.rs new file mode 100644 index 0000000..d94c16e --- /dev/null +++ b/crates/dns-tools/src/dot.rs @@ -0,0 +1,97 @@ +//! `edot` / `easydot` – DNS-over-TLS diagnostics. +use std::process::ExitCode; +use std::time::Duration; + +use clap::Parser; +use dns_core::client::{QueryOptions, build_query}; +use dns_core::proto::op::Message; +use serde_json::json; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "edot", version = VERSION, about = "EasyDoT – test a DNS-over-TLS server")] +pub struct Args { + /// Server IP[:port] (default port 853) + pub server: String, + pub name: String, + #[arg(default_value = "A")] + pub rtype: String, + /// TLS server name (SNI and certificate check); defaults to the server argument + #[arg(long)] + pub tls_name: Option, + /// Extra CA certificate (PEM) to trust + #[arg(long)] + pub ca: Option, + /// Skip certificate verification (diagnostics only!) + #[arg(long)] + pub insecure: bool, + #[arg(long, default_value = "5s")] + pub timeout: String, + #[arg(long)] + pub json: bool, +} + +pub fn main() -> ExitCode { + block_on(run(Args::parse())) +} + +pub async fn run(a: Args) -> ExitCode { + let addr = match server_addr(&a.server, 853).await { + Ok(x) => x, + Err(e) => return fail("edot", EXIT_USAGE, e), + }; + let (Ok(name), Some(t)) = (name_arg(&a.name), parse_type(&a.rtype)) else { return fail("edot", EXIT_USAGE, "invalid name or type") }; + let timeout = parse_duration(&a.timeout).unwrap_or(Duration::from_secs(5)); + let ca = match &a.ca { + Some(p) => match std::fs::read(p) { + Ok(b) => Some(b), + Err(e) => return fail("edot", EXIT_USAGE, format!("{}: {e}", p.display())), + }, + None => None, + }; + let cfg = match dns_core::tls::client_config(ca.as_deref(), a.insecure, &[b"dot"]) { + Ok(c) => c, + Err(e) => return fail("edot", EXIT_USAGE, e), + }; + let sni = a.tls_name.clone().unwrap_or_else(|| addr.ip().to_string()); + let q = build_query(&name, t, &QueryOptions::default()); + let bytes = match q.to_vec() { + Ok(b) => b, + Err(e) => return fail("edot", EXIT_INTERNAL, e), + }; + let start = std::time::Instant::now(); + match dns_core::tls::dot_exchange(addr, &sni, &bytes, timeout, cfg).await { + Ok((raw, info)) => { + let total = start.elapsed().as_secs_f64() * 1000.0; + let m = match Message::from_vec(&raw) { + Ok(m) => m, + Err(e) => return fail("edot", EXIT_INTERNAL, format!("invalid DNS response: {e}")), + }; + if a.json { + print_structured( + &json!({ "server": addr.to_string(), "tls_name": sni, "tls": info, "total_ms": total, "status": rcode_str(m.metadata.response_code), + "answer": m.answers.iter().map(rr_json).collect::>(), "certificate_verified": !a.insecure }), + false, + ); + } else { + println!(";; DoT {addr} (SNI {sni})"); + println!( + ";; TLS {} {} ALPN {:?}, {} peer certificate(s){}", + info.protocol, + info.cipher_suite, + info.alpn, + info.peer_certificates, + if a.insecure { " — NOT VERIFIED" } else { ", verified" } + ); + println!(";; connect {:.1} ms, handshake {:.1} ms, total {total:.1} ms", info.connect_ms, info.handshake_ms); + println!(";; status {} flags: {}", rcode_str(m.metadata.response_code), flags_str(&m)); + for r in &m.answers { + println!("{}", rr_line(r)); + } + } + ExitCode::SUCCESS + } + Err(e) => net_error("edot", &e), + } +} diff --git a/crates/dns-tools/src/host.rs b/crates/dns-tools/src/host.rs new file mode 100644 index 0000000..023211d --- /dev/null +++ b/crates/dns-tools/src/host.rs @@ -0,0 +1,160 @@ +//! `eh` / `easyhost` – host replacement. +use std::net::IpAddr; +use std::process::ExitCode; + +use clap::Parser; +use dns_core::client::{QueryOptions, query}; +use dns_core::proto::op::ResponseCode; +use dns_core::proto::rr::{RData, RecordType}; +use serde_json::json; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "eh", version = VERSION, about = "EasyHost – simple DNS lookups (host replacement)")] +pub struct Args { + /// Name or IP address (IP → reverse lookup) + pub target: String, + /// Server to query + pub server: Option, + /// Query type + #[arg(short = 't', long = "type")] + pub rtype: Option, + /// Query common types (A, AAAA, MX, NS, TXT, SOA, CAA) + #[arg(short = 'a', long = "all")] + pub all: bool, + /// Use TCP + #[arg(short = 'T', long)] + pub tcp: bool, + /// Port + #[arg(short, long, default_value_t = 53)] + pub port: u16, + /// Timeout (e.g. 2s) + #[arg(short = 'W', long, default_value = "5s")] + pub timeout: String, + /// Retries + #[arg(short = 'R', long, default_value_t = 1)] + pub retries: u32, + /// Verbose (dig-like) output + #[arg(short, long)] + pub verbose: bool, + #[arg(long)] + pub json: bool, +} + +fn describe(r: &dns_core::proto::rr::Record) -> String { + let owner = r.name.to_string(); + let n = owner.trim_end_matches('.'); + match &r.data { + RData::A(a) => format!("{n} has address {a}"), + RData::AAAA(a) => format!("{n} has IPv6 address {a}"), + RData::MX(mx) => format!("{n} mail is handled by {} {}", mx.preference, mx.exchange), + RData::CNAME(c) => format!("{n} is an alias for {}", c.0), + RData::PTR(p) => format!("{n} domain name pointer {}", p.0), + RData::NS(ns) => format!("{n} name server {}", ns.0), + RData::TXT(_) => format!("{n} descriptive text {}", r.data), + RData::SOA(_) => format!("{n} has SOA record {}", r.data), + RData::SRV(_) => format!("{n} has SRV record {}", r.data), + RData::CAA(_) => format!("{n} has CAA record {}", r.data), + other => format!("{n} has {} record {other}", r.record_type()), + } +} + +pub fn main() -> ExitCode { + let a = Args::parse(); + block_on(run(a)) +} + +pub async fn run(a: Args) -> ExitCode { + let timeout = match parse_duration(&a.timeout) { + Ok(t) => t, + Err(e) => return fail("eh", EXIT_USAGE, e), + }; + let server = match &a.server { + Some(s) => match server_addr(s, a.port).await { + Ok(x) => x, + Err(e) => return fail("eh", EXIT_USAGE, e), + }, + None => std::net::SocketAddr::new(system_resolver(), a.port), + }; + let (name, types): (_, Vec) = if let Ok(ip) = a.target.parse::() { + (dns_core::names::reverse_name(ip), vec![RecordType::PTR]) + } else { + let n = match name_arg(&a.target) { + Ok(n) => n, + Err(e) => return fail("eh", EXIT_USAGE, e), + }; + let t = if let Some(t) = &a.rtype { + match parse_type(t) { + Some(t) => vec![t], + None => return fail("eh", EXIT_USAGE, format!("invalid type: {t}")), + } + } else if a.all { + vec![RecordType::A, RecordType::AAAA, RecordType::MX, RecordType::NS, RecordType::TXT, RecordType::SOA, RecordType::CAA] + } else { + vec![RecordType::A, RecordType::AAAA, RecordType::MX] + }; + (n, t) + }; + let opts = QueryOptions { timeout, retries: a.retries, tcp_only: a.tcp, ..Default::default() }; + let mut out = Vec::new(); + let mut code = ExitCode::SUCCESS; + let mut seen_cname = std::collections::HashSet::new(); + if a.server.is_some() && !a.json { + println!( + "Using domain server:\nName: {}\nAddress: {}#{}\nAliases: \n", + a.server.as_deref().unwrap_or(""), + server.ip(), + server.port() + ); + } + for t in &types { + let ex = match query(server, &name, *t, &opts).await { + Ok(ex) => ex, + Err(e) => { + if !a.json { + println!(";; connection timed out; no servers could be reached ({e})"); + } + return net_error("eh", &e); + } + }; + let m = &ex.message; + match m.metadata.response_code { + ResponseCode::NoError => {} + rc => { + if a.json { + out.push(json!({ "type": t.to_string(), "status": rcode_str(rc) })); + } else { + println!("Host {} not found: {}({})", a.target, u16::from(rc), rcode_str(rc)); + } + code = ExitCode::from(1); + break; + } + } + if a.verbose && !a.json { + println!("Trying \"{name}\" ({t})"); + for r in &m.answers { + println!("{}", rr_line(r)); + } + println!("Received {} bytes from {} in {} ms\n", ex.size, ex.server, ex.elapsed.as_millis()); + continue; + } + for r in &m.answers { + if r.record_type() == RecordType::CNAME && !seen_cname.insert(r.data.to_string()) { + continue; + } + if a.json { + out.push(rr_json(r)); + } else { + println!("{}", describe(r)); + } + } + if m.answers.is_empty() && a.rtype.is_some() && !a.json { + println!("{} has no {} record", name.to_string().trim_end_matches('.'), t); + } + } + if a.json { + print_structured(&json!({ "name": name.to_string(), "server": server.to_string(), "records": out }), false); + } + code +} diff --git a/crates/dns-tools/src/lib.rs b/crates/dns-tools/src/lib.rs new file mode 100644 index 0000000..d70224a --- /dev/null +++ b/crates/dns-tools/src/lib.rs @@ -0,0 +1,22 @@ +//! EasyDNS Tools – practical replacements for common BIND utilities, built on the +//! shared EasyDNS engine. Each tool lives in its own module and is exposed as two +//! binaries (short and long name, e.g. `ed` and `easydig`). +//! +//! Common exit codes: 0 success (a valid DNS answer, including NXDOMAIN, unless the +//! tool documents otherwise), 1 usage error, 9 no reply / timeout, 10 internal error. +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))] + +pub mod bench; +pub mod common; +pub mod conf; +pub mod diff; +pub mod dig; +pub mod dnssec; +pub mod doh; +pub mod dot; +pub mod host; +pub mod nslookup; +pub mod ptr; +pub mod trace; +pub mod whois; +pub mod zone; diff --git a/crates/dns-tools/src/nslookup.rs b/crates/dns-tools/src/nslookup.rs new file mode 100644 index 0000000..7fd78eb --- /dev/null +++ b/crates/dns-tools/src/nslookup.rs @@ -0,0 +1,207 @@ +//! `ens` / `easynslookup` – nslookup replacement with interactive mode. +use std::io::{BufRead, Write}; +use std::net::{IpAddr, SocketAddr}; +use std::process::ExitCode; +use std::time::Duration; + +use dns_core::client::{QueryOptions, query}; +use dns_core::proto::op::ResponseCode; +use dns_core::proto::rr::{RData, RecordType}; + +use crate::common::*; + +struct State { + server: SocketAddr, + rtype: RecordType, + port: u16, + timeout: Duration, + recurse: bool, + tcp: bool, +} + +fn usage() -> &'static str { + "Usage: ens [-type=T] [-port=N] [-timeout=S] [-norecurse] [-vc] [name] [server]\n ens --interactive" +} + +async fn lookup(st: &State, target: &str) -> bool { + let (name, t) = match target.parse::() { + Ok(ip) => (dns_core::names::reverse_name(ip), RecordType::PTR), + Err(_) => match name_arg(target) { + Ok(n) => (n, st.rtype), + Err(e) => { + println!("*** invalid name {target}: {e}"); + return false; + } + }, + }; + let opts = QueryOptions { timeout: st.timeout, retries: 1, recursion_desired: st.recurse, tcp_only: st.tcp, ..Default::default() }; + println!("Server:\t\t{}\nAddress:\t{}#{}\n", st.server.ip(), st.server.ip(), st.server.port()); + let types = if t == RecordType::A && st.rtype == RecordType::A { vec![RecordType::A, RecordType::AAAA] } else { vec![t] }; + let mut ok = true; + let mut printed_header = false; + for t in types { + match query(st.server, &name, t, &opts).await { + Ok(ex) => { + let m = &ex.message; + if m.metadata.response_code != ResponseCode::NoError { + println!("** server can't find {}: {}", name.to_string().trim_end_matches('.'), rcode_str(m.metadata.response_code)); + ok = false; + break; + } + if !m.metadata.authoritative && !printed_header && !m.answers.is_empty() { + println!("Non-authoritative answer:"); + printed_header = true; + } + for r in &m.answers { + let n = r.name.to_string(); + let n = n.trim_end_matches('.'); + match &r.data { + RData::A(a) => println!("Name:\t{n}\nAddress: {a}"), + RData::AAAA(a) => println!("Name:\t{n}\nAddress: {a}"), + RData::CNAME(c) => println!("{n}\tcanonical name = {}", c.0), + RData::PTR(p) => println!("{n}\tname = {}", p.0), + RData::MX(mx) => println!("{n}\tmail exchanger = {} {}", mx.preference, mx.exchange), + RData::NS(ns) => println!("{n}\tnameserver = {}", ns.0), + RData::TXT(_) => println!("{n}\ttext = {}", r.data), + RData::SOA(s) => println!( + "{n}\n\torigin = {}\n\tmail addr = {}\n\tserial = {}\n\trefresh = {}\n\tretry = {}\n\texpire = {}\n\tminimum = {}", + s.mname, s.rname, s.serial, s.refresh, s.retry, s.expire, s.minimum + ), + other => println!("{n}\t{} = {other}", r.record_type()), + } + } + if m.answers.is_empty() && t == st.rtype { + println!("*** No {t} records available for {}", name.to_string().trim_end_matches('.')); + } + } + Err(e) => { + println!(";; connection timed out; no servers could be reached ({e})"); + return false; + } + } + } + println!(); + ok +} + +fn apply_set(st: &mut State, arg: &str) -> Result<(), String> { + let a = arg.trim_start_matches('-'); + let (k, v) = a.split_once('=').map(|(k, v)| (k.to_ascii_lowercase(), Some(v))).unwrap_or((a.to_ascii_lowercase(), None)); + match (k.as_str(), v) { + ("type" | "querytype" | "q" | "ty", Some(v)) => st.rtype = parse_type(v).ok_or_else(|| format!("unknown type {v}"))?, + ("port" | "po", Some(v)) => st.port = v.parse().map_err(|_| "invalid port")?, + ("timeout" | "ti", Some(v)) => st.timeout = Duration::from_secs(v.parse().map_err(|_| "invalid timeout")?), + ("norecurse" | "norec", None) => st.recurse = false, + ("recurse" | "rec", None) => st.recurse = true, + ("vc", None) => st.tcp = true, + ("novc", None) => st.tcp = false, + _ => return Err(format!("unknown option {arg}")), + } + st.server.set_port(st.port); + Ok(()) +} + +pub fn main() -> ExitCode { + block_on(run(std::env::args().skip(1).collect())) +} + +pub async fn run(args: Vec) -> ExitCode { + let mut st = State { + server: SocketAddr::new(system_resolver(), 53), + rtype: RecordType::A, + port: 53, + timeout: Duration::from_secs(5), + recurse: true, + tcp: false, + }; + let mut interactive = false; + let mut pos = Vec::new(); + for a in &args { + match a.as_str() { + "-h" | "--help" => { + println!("{}", usage()); + return ExitCode::SUCCESS; + } + "--version" => { + println!("EasyNSLookup {VERSION}"); + return ExitCode::SUCCESS; + } + "--interactive" | "-i" => interactive = true, + s if s.starts_with('-') && s.len() > 1 => { + if let Err(e) = apply_set(&mut st, s) { + return fail("ens", EXIT_USAGE, format!("{e}\n{}", usage())); + } + } + s => pos.push(s.to_string()), + } + } + if pos.len() > 1 { + match server_addr(&pos[1], st.port).await { + Ok(a) => st.server = a, + Err(e) => return fail("ens", EXIT_USAGE, e), + } + } + if pos.is_empty() { + interactive = true; + } + if !interactive { + return if lookup(&st, &pos[0]).await { ExitCode::SUCCESS } else { ExitCode::from(1) }; + } + let stdin = std::io::stdin(); + loop { + print!("> "); + let _ = std::io::stdout().flush(); + let mut line = String::new(); + if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { + return ExitCode::SUCCESS; + } + let line = line.trim(); + let mut parts = line.split_whitespace(); + match parts.next() { + None => continue, + Some("exit" | "quit") => return ExitCode::SUCCESS, + Some("server" | "lserver") => match parts.next() { + Some(s) => match server_addr(s, st.port).await { + Ok(a) => { + st.server = a; + println!("Default server: {s}\nAddress: {}#{}", a.ip(), a.port()); + } + Err(e) => println!("*** {e}"), + }, + None => println!("Default server: {}", st.server), + }, + Some("set") => match parts.next() { + Some("all") => println!( + "Default server: {}\n type = {}\n port = {}\n timeout = {:?}\n {}recurse\n {}vc", + st.server, + st.rtype, + st.port, + st.timeout, + if st.recurse { "" } else { "no" }, + if st.tcp { "" } else { "no" } + ), + Some(opt) => { + if let Err(e) = apply_set(&mut st, opt) { + println!("*** {e}"); + } + } + None => println!("*** set requires an option"), + }, + Some("help" | "?") => { + println!("Commands: NAME, server IP, set type=T, set port=N, set timeout=S, set [no]recurse, set [no]vc, set all, exit") + } + Some(name) => { + if let Some(srv) = parts.next() { + let mut tmp = + State { server: st.server, rtype: st.rtype, port: st.port, timeout: st.timeout, recurse: st.recurse, tcp: st.tcp }; + if let Ok(a) = server_addr(srv, st.port).await { + tmp.server = a; + } + lookup(&tmp, name).await; + } else { + lookup(&st, name).await; + } + } + } + } +} diff --git a/crates/dns-tools/src/ptr.rs b/crates/dns-tools/src/ptr.rs new file mode 100644 index 0000000..74a951b --- /dev/null +++ b/crates/dns-tools/src/ptr.rs @@ -0,0 +1,101 @@ +//! `eptr` / `easyptr` – reverse DNS for IPv4/IPv6 (several addresses at once). +use std::net::IpAddr; +use std::process::ExitCode; + +use clap::Parser; +use dns_core::client::{QueryOptions, query}; +use dns_core::proto::op::ResponseCode; +use dns_core::proto::rr::{RData, RecordType}; +use serde_json::json; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "eptr", version = VERSION, about = "EasyPTR – reverse DNS lookups")] +pub struct Args { + /// IPv4/IPv6 addresses + #[arg(required = true)] + pub addresses: Vec, + /// Server (default: system resolver) + #[arg(short, long)] + pub server: Option, + #[arg(short, long, default_value_t = 53)] + pub port: u16, + /// Also verify forward-confirmed reverse DNS (PTR → A/AAAA matches) + #[arg(long)] + pub verify: bool, + #[arg(long)] + pub json: bool, +} + +pub fn main() -> ExitCode { + block_on(run(Args::parse())) +} + +pub async fn run(a: Args) -> ExitCode { + let server = match &a.server { + Some(s) => match server_addr(s, a.port).await { + Ok(x) => x, + Err(e) => return fail("eptr", EXIT_USAGE, e), + }, + None => std::net::SocketAddr::new(system_resolver(), a.port), + }; + let opts = QueryOptions::default(); + let mut results = Vec::new(); + let mut code = ExitCode::SUCCESS; + for addr in &a.addresses { + let Ok(ip) = addr.parse::() else { + return fail("eptr", EXIT_USAGE, format!("not an IP address: {addr}")); + }; + let rname = dns_core::names::reverse_name(ip); + let res = match query(server, &rname, RecordType::PTR, &opts).await { + Ok(ex) => ex, + Err(e) => return net_error("eptr", &e), + }; + let ptrs: Vec = res + .message + .answers + .iter() + .filter_map(|r| match &r.data { + RData::PTR(p) => Some(p.0.to_string()), + _ => None, + }) + .collect(); + let mut fcrdns = None; + if a.verify { + let mut ok = false; + for p in &ptrs { + let Ok(n) = name_arg(p) else { continue }; + let t = if ip.is_ipv4() { RecordType::A } else { RecordType::AAAA }; + if let Ok(ex) = query(server, &n, t, &opts).await { + ok |= ex.message.answers.iter().any(|r| r.data.ip_addr() == Some(ip)); + } + } + fcrdns = Some(ok); + } + let rc = res.message.metadata.response_code; + if rc != ResponseCode::NoError || ptrs.is_empty() { + code = ExitCode::from(1); + } + if a.json { + results.push( + json!({ "address": addr, "reverse_name": rname.to_string(), "status": rcode_str(rc), "ptr": ptrs, "fcrdns": fcrdns }), + ); + } else if ptrs.is_empty() { + println!("{addr}\t{} ({})", rcode_str(rc), rname); + } else { + for p in &ptrs { + let v = match fcrdns { + Some(true) => " [forward-confirmed]", + Some(false) => " [NOT forward-confirmed]", + None => "", + }; + println!("{addr}\t{p}{v}"); + } + } + } + if a.json { + print_structured(&json!(results), false); + } + code +} diff --git a/crates/dns-tools/src/trace.rs b/crates/dns-tools/src/trace.rs new file mode 100644 index 0000000..697e906 --- /dev/null +++ b/crates/dns-tools/src/trace.rs @@ -0,0 +1,161 @@ +//! `etrace` / `easytrace` – follow delegations from the root (dig +trace). +use std::process::ExitCode; +use std::sync::Arc; +use std::time::Duration; + +use clap::Parser; +use dns_core::proto::rr::{Name, RecordType}; +use serde_json::json; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "etrace", version = VERSION, about = "EasyTrace – trace the delegation path root → TLD → authoritative")] +pub struct Args { + pub name: String, + #[arg(default_value = "A")] + pub rtype: String, + /// Also show DS/DNSKEY presence for each zone cut + #[arg(long)] + pub dnssec: bool, + /// Root hints file (default: built-in) + #[arg(long)] + pub root_hints: Option, + /// Port of authoritative servers (testing) + #[arg(long, default_value_t = 53, hide = true)] + pub port: u16, + /// Maximum referrals to follow + #[arg(long, default_value_t = 30)] + pub max_depth: u32, + /// Use IPv6 transport too + #[arg(short = '6', long)] + pub ipv6: bool, + #[arg(long)] + pub json: bool, + #[arg(long)] + pub no_color: bool, +} + +pub fn main() -> ExitCode { + let a = Args::parse(); + let Some(t) = parse_type(&a.rtype) else { return fail("etrace", EXIT_USAGE, format!("unknown type {}", a.rtype)) }; + let name = match name_arg(&a.name) { + Ok(n) => n, + Err(e) => return fail("etrace", EXIT_USAGE, e), + }; + block_on(trace_with( + &name, + t, + a.json, + false, + a.dnssec, + Colors::detect(a.no_color), + a.root_hints.as_deref(), + a.port, + a.max_depth, + a.ipv6, + )) +} + +/// Entry used by `ed +trace`. +pub async fn run_trace(name: &Name, t: RecordType, json_out: bool, yaml: bool, dnssec: bool, c: Colors) -> ExitCode { + trace_with(name, t, json_out, yaml, dnssec, c, None, 53, 30, false).await +} + +#[allow(clippy::too_many_arguments)] +pub async fn trace_with( + name: &Name, + t: RecordType, + json_out: bool, + yaml: bool, + dnssec: bool, + c: Colors, + hints: Option<&std::path::Path>, + port: u16, + max_depth: u32, + ipv6: bool, +) -> ExitCode { + let hints = match dns_recursive::hints::load(hints) { + Ok(h) => h, + Err(e) => return fail("etrace", EXIT_USAGE, e), + }; + let cache = Arc::new(dns_cache::Cache::new(&dns_config::CacheConfig { max_entries: 10_000, ..Default::default() })); + let settings = dns_recursive::Settings { + max_depth, + max_queries: 200, + max_cname: 8, + query_timeout: Duration::from_secs(2), + total_timeout: Duration::from_secs(30), + port, + qname_minimization: false, + ipv6, + max_subqueries_depth: 4, + dnssec, + }; + let r = match dns_recursive::Resolver::new(settings, hints, cache, 0) { + Ok(r) => r, + Err(e) => return fail("etrace", EXIT_INTERNAL, e), + }; + let (ans, steps) = r.resolve_traced(name, t).await; + let mut ds_info = Vec::new(); + if dnssec { + let mut zones: Vec = steps.iter().map(|s| s.zone.clone()).collect(); + zones.dedup(); + for z in zones { + let zn = name_arg(&z).unwrap_or_else(|_| Name::root()); + let dnskey = r.resolve(&zn, RecordType::DNSKEY).await; + let ds = if zn.is_root() { None } else { Some(r.resolve(&zn, RecordType::DS).await) }; + ds_info.push(( + z, + dnskey.answers.iter().filter(|x| x.record_type() == RecordType::DNSKEY).count(), + ds.map(|d| d.answers.iter().filter(|x| x.record_type() == RecordType::DS).count()), + )); + } + } + if json_out { + print_structured( + &json!({ + "name": name.to_string(), "type": t.to_string(), "status": rcode_str(ans.rcode), + "steps": steps, + "answer": ans.answers.iter().map(rr_json).collect::>(), + "note": ans.note, + "dnssec": ds_info.iter().map(|(z, k, d)| json!({"zone": z, "dnskeys": k, "ds": d})).collect::>(), + }), + yaml, + ); + } else { + println!("\n; <<>> EasyTrace {VERSION} <<>> {name} {t}"); + let mut last_zone = String::new(); + for s in &steps { + if s.zone != last_zone { + println!("\n{}", c.bold(&format!(";; zone {}", s.zone))); + last_zone = s.zone.clone(); + } + println!( + ";; {:<40} {:<22} {:>7.1} ms {:<9} {}", + format!("{} ({})", s.server_name.as_deref().unwrap_or("?"), s.server), + format!("{} {}", s.qname, s.qtype), + s.elapsed_ms, + s.rcode, + s.outcome + ); + } + if !ds_info.is_empty() { + println!("\n{}", c.bold(";; DNSSEC")); + for (z, k, d) in &ds_info { + println!( + ";; {z:<30} DNSKEY: {k:<3} DS in parent: {}", + d.map(|x| x.to_string()).unwrap_or_else(|| "(trust anchor)".into()) + ); + } + } + println!("\n;; status: {} queries: {}", c.rcode(ans.rcode), steps.len()); + for rr in &ans.answers { + println!("{}", rr_line(rr)); + } + if let Some(n) = &ans.note { + println!(";; note: {n}"); + } + } + if ans.rcode == dns_core::proto::op::ResponseCode::ServFail { ExitCode::from(EXIT_NO_REPLY) } else { ExitCode::SUCCESS } +} diff --git a/crates/dns-tools/src/whois.rs b/crates/dns-tools/src/whois.rs new file mode 100644 index 0000000..51025bf --- /dev/null +++ b/crates/dns-tools/src/whois.rs @@ -0,0 +1,170 @@ +//! `ewhois` / `easywhois` – RDAP (preferred) and WHOIS lookups. +//! +//! This is a separate component from the DNS engine: RDAP uses the IANA bootstrap +//! registry over HTTPS; classic WHOIS (TCP/43) is used with `--whois` or as fallback. +use std::net::IpAddr; +use std::process::ExitCode; +use std::time::Duration; + +use clap::Parser; +use serde_json::Value; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "ewhois", version = VERSION, about = "EasyWhois – RDAP/WHOIS lookups for domains and IP addresses")] +pub struct Args { + pub query: String, + /// Use classic WHOIS (port 43) instead of RDAP + #[arg(long)] + pub whois: bool, + /// WHOIS server (default: whois.iana.org with referral) + #[arg(long)] + pub server: Option, + #[arg(long, default_value = "15s")] + pub timeout: String, + #[arg(long)] + pub json: bool, +} + +async fn rdap(q: &str, timeout: Duration) -> Result { + let (registry, key) = match q.parse::() { + Ok(IpAddr::V4(_)) => ("https://data.iana.org/rdap/ipv4.json", q.to_string()), + Ok(IpAddr::V6(_)) => ("https://data.iana.org/rdap/ipv6.json", q.to_string()), + Err(_) => ("https://data.iana.org/rdap/dns.json", q.trim_end_matches('.').rsplit('.').next().unwrap_or("").to_ascii_lowercase()), + }; + let (st, body) = dns_core::tls::https_get(registry, timeout, 4 * 1024 * 1024).await.map_err(|e| format!("RDAP bootstrap: {e}"))?; + if st != 200 { + return Err(format!("RDAP bootstrap HTTP {st}")); + } + let boot: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?; + let mut base = None; + for svc in boot["services"].as_array().into_iter().flatten() { + let keys = svc[0].as_array().cloned().unwrap_or_default(); + let hit = keys.iter().filter_map(Value::as_str).any(|k| match q.parse::() { + Ok(ip) => k.parse::().map(|n| n.contains(ip)).unwrap_or(false), + Err(_) => k.eq_ignore_ascii_case(&key), + }); + if hit { + base = svc[1].as_array().and_then(|u| u.iter().filter_map(Value::as_str).find(|u| u.starts_with("https://"))).map(String::from); + break; + } + } + let base = base.ok_or("no RDAP service found for this query")?; + let kind = if q.parse::().is_ok() { "ip" } else { "domain" }; + let url = format!("{}/{kind}/{}", base.trim_end_matches('/'), q.trim_end_matches('.')); + let (st, body) = dns_core::tls::https_get(&url, timeout, 4 * 1024 * 1024).await.map_err(|e| format!("{url}: {e}"))?; + if st == 404 { + return Err("not found".into()); + } + if st != 200 { + return Err(format!("{url}: HTTP {st}")); + } + serde_json::from_slice(&body).map_err(|e| e.to_string()) +} + +mod ipnet_lite { + use std::net::IpAddr; + pub struct Net(IpAddr, u8); + impl std::str::FromStr for Net { + type Err = (); + fn from_str(s: &str) -> Result { + let (a, p) = s.split_once('/').ok_or(())?; + Ok(Net(a.parse().map_err(|_| ())?, p.parse().map_err(|_| ())?)) + } + } + impl Net { + pub fn contains(&self, ip: IpAddr) -> bool { + match (self.0, ip) { + (IpAddr::V4(n), IpAddr::V4(i)) => self.1 <= 32 && (self.1 == 0 || (u32::from(n) ^ u32::from(i)) >> (32 - self.1) == 0), + (IpAddr::V6(n), IpAddr::V6(i)) => self.1 <= 128 && (self.1 == 0 || (u128::from(n) ^ u128::from(i)) >> (128 - self.1) == 0), + _ => false, + } + } + } +} + +async fn whois43(server: &str, q: &str, timeout: Duration) -> Result { + let fut = async { + let mut s = tokio::net::TcpStream::connect((server, 43)).await.map_err(|e| format!("{server}: {e}"))?; + s.write_all(format!("{q}\r\n").as_bytes()).await.map_err(|e| e.to_string())?; + let mut buf = Vec::new(); + s.take(1024 * 1024).read_to_end(&mut buf).await.map_err(|e| e.to_string())?; + Ok(String::from_utf8_lossy(&buf).to_string()) + }; + tokio::time::timeout(timeout, fut).await.map_err(|_| format!("{server}: timeout"))? +} + +fn summarise(v: &Value) { + let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("-").to_string(); + println!("Handle: {}", s("/handle")); + if let Some(n) = v.get("ldhName").and_then(Value::as_str) { + println!("Domain: {n}"); + } + if let (Some(a), Some(b)) = (v.get("startAddress").and_then(Value::as_str), v.get("endAddress").and_then(Value::as_str)) { + println!("Range: {a} - {b}"); + } + if let Some(n) = v.get("name").and_then(Value::as_str) { + println!("Name: {n}"); + } + for st in v["status"].as_array().into_iter().flatten().filter_map(Value::as_str) { + println!("Status: {st}"); + } + for ev in v["events"].as_array().into_iter().flatten() { + println!("Event: {:<20} {}", ev["eventAction"].as_str().unwrap_or(""), ev["eventDate"].as_str().unwrap_or("")); + } + for ns in v["nameservers"].as_array().into_iter().flatten() { + println!("NS: {}", ns["ldhName"].as_str().unwrap_or("")); + } + for e in v["entities"].as_array().into_iter().flatten() { + let roles: Vec<&str> = e["roles"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let fname = e + .pointer("/vcardArray/1") + .and_then(Value::as_array) + .and_then(|a| a.iter().find(|x| x[0] == "fn")) + .and_then(|x| x[3].as_str()) + .unwrap_or("-"); + println!("Entity: {:<30} {}", fname, roles.join(",")); + } +} + +pub fn main() -> ExitCode { + block_on(run(Args::parse())) +} + +pub async fn run(a: Args) -> ExitCode { + let timeout = parse_duration(&a.timeout).unwrap_or(Duration::from_secs(15)); + if !a.whois { + match rdap(&a.query, timeout).await { + Ok(v) => { + if a.json { + print_structured(&v, false); + } else { + summarise(&v); + } + return ExitCode::SUCCESS; + } + Err(e) if e == "not found" => return fail("ewhois", 1, "no match"), + Err(e) => eprintln!("ewhois: RDAP failed ({e}); falling back to WHOIS"), + } + } + let first = a.server.clone().unwrap_or_else(|| "whois.iana.org".into()); + let mut text = match whois43(&first, &a.query, timeout).await { + Ok(t) => t, + Err(e) => return fail("ewhois", EXIT_NO_REPLY, e), + }; + if a.server.is_none() + && let Some(refer) = + text.lines().find_map(|l| l.strip_prefix("refer:").or_else(|| l.strip_prefix("whois:")).map(|s| s.trim().to_string())) + && let Ok(t) = whois43(&refer, &a.query, timeout).await + { + text = t; + } + if a.json { + print_structured(&serde_json::json!({ "query": a.query, "whois": text }), false); + } else { + print!("{text}"); + } + ExitCode::SUCCESS +} diff --git a/crates/dns-tools/src/zone.rs b/crates/dns-tools/src/zone.rs new file mode 100644 index 0000000..9787d1c --- /dev/null +++ b/crates/dns-tools/src/zone.rs @@ -0,0 +1,84 @@ +//! `ezone` / `easyzone` – zone file validation (named-checkzone). +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::{Parser, Subcommand}; + +use crate::common::*; + +#[derive(Parser, Debug)] +#[command(name = "ezone", version = VERSION, about = "EasyZone – validate zone files")] +pub struct Args { + #[command(subcommand)] + pub cmd: Cmd, + #[arg(long, global = true)] + pub json: bool, +} + +#[derive(Subcommand, Debug)] +pub enum Cmd { + /// Check one zone file + Check { + file: PathBuf, + #[arg(short, long)] + origin: String, + }, + /// Check all primary zones of a configuration + Validate { + #[arg(long)] + all: bool, + #[arg(short, long, default_value = "/etc/easydns/config.yaml")] + config: PathBuf, + }, + /// Print a zone in canonical sorted form + Canonical { + file: PathBuf, + #[arg(short, long)] + origin: String, + }, +} + +fn report(findings: &[dns_server::check::Finding], json: bool) -> ExitCode { + let errors = findings.iter().filter(|f| f.severity == "error").count(); + if json { + print_structured(&serde_json::to_value(findings).unwrap_or_default(), false); + } else { + for f in findings { + println!("{f}"); + } + println!("{}", if errors == 0 { "OK" } else { "FAILED" }); + } + if errors == 0 { ExitCode::SUCCESS } else { ExitCode::from(1) } +} + +pub fn main() -> ExitCode { + let a = Args::parse(); + match a.cmd { + Cmd::Check { file, origin } => report(&dns_server::check::check_zone_file(&file, &origin), a.json), + Cmd::Validate { config, .. } => match dns_config::Config::load(&config) { + Ok(cfg) => { + let mut f = Vec::new(); + for z in cfg.zones.iter().filter(|z| z.zone_type == dns_config::ZoneType::Primary) { + if let Some(file) = &z.file { + f.extend(dns_server::check::check_zone_file(&cfg.resolve_path(file), &z.name)); + } + } + report(&f, a.json) + } + Err(e) => fail("ezone", EXIT_USAGE, e), + }, + Cmd::Canonical { file, origin } => { + let o = match name_arg(&origin) { + Ok(o) => o, + Err(e) => return fail("ezone", EXIT_USAGE, e), + }; + match dns_core::zonefile::parse_file(&file, &o) { + Ok(r) => { + print!("{}", dns_core::zonefile::emit(&o, &r)); + ExitCode::SUCCESS + } + Err(e) => fail("ezone", 1, e), + } + } + } +} diff --git a/crates/dns-tools/tests/cli.rs b/crates/dns-tools/tests/cli.rs new file mode 100644 index 0000000..32fc9ab --- /dev/null +++ b/crates/dns-tools/tests/cli.rs @@ -0,0 +1,93 @@ +//! Run the tool binaries against a local EasyDNS server and check output + exit codes. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::process::Command; + +fn run(bin: &str, args: &[&str]) -> (i32, String) { + let out = Command::new(bin).args(args).env("NO_COLOR", "1").output().unwrap(); + (out.status.code().unwrap_or(-1), String::from_utf8_lossy(&out.stdout).to_string() + &String::from_utf8_lossy(&out.stderr)) +} + +#[tokio::test(flavor = "multi_thread")] +async fn tools_against_local_server() { + let dir = std::env::temp_dir().join(format!("easydns-tools-{}", 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\n@ IN MX 10 mail\nns IN A 127.0.0.1\nmail IN A 192.0.2.25\nwww IN A 192.0.2.10\nwww IN AAAA 2001:db8::10\n", + ) + .unwrap(); + std::fs::write( + dir.join("r.zone"), + "$TTL 60\n@ IN SOA ns.example.test. hm 1 3600 600 86400 60\n@ IN NS ns.example.test.\n10 IN PTR www.example.test.\n", + ) + .unwrap(); + let yaml = "server: { listen: [\"127.0.0.1:0\"], data_dir: data }\napi: { enabled: false }\nzones:\n - { name: example.test, type: primary, file: z.zone, transfer_acl: [\"127.0.0.1/32\"] }\n - { name: 2.0.192.in-addr.arpa, type: primary, file: r.zone }\n"; + std::fs::write(dir.join("config.yaml"), yaml).unwrap(); + let cfg = dns_config::Config::load(&dir.join("config.yaml")).unwrap(); + let h = dns_server::Server::start(cfg, None, Default::default()).await.unwrap(); + let port = h.bound.dns[0].port().to_string(); + let srv = "@127.0.0.1".to_string(); + let ed = env!("CARGO_BIN_EXE_ed"); + + let p = port.clone(); + let (s, ed_out, short, json, nx, ax, eh_out, ens, eptr, ezone, econf, ediff, bad) = tokio::task::spawn_blocking({ + let srv = srv.clone(); + let dir = dir.clone(); + move || { + ( + 0, + run(ed, &[&srv, "-p", &p, "www.example.test", "A"]), + run(ed, &[&srv, "-p", &p, "www.example.test", "AAAA", "+short"]), + run(ed, &[&srv, "-p", &p, "example.test", "MX", "--json"]), + run(ed, &[&srv, "-p", &p, "nope.example.test"]), + run(ed, &[&srv, "-p", &p, "example.test", "AXFR"]), + run(env!("CARGO_BIN_EXE_eh"), &["-p", &p, "www.example.test", "127.0.0.1"]), + run(env!("CARGO_BIN_EXE_ens"), &[&format!("-port={p}"), "www.example.test", "127.0.0.1"]), + run(env!("CARGO_BIN_EXE_eptr"), &["-s", "127.0.0.1", "-p", &p, "192.0.2.10", "--json"]), + run(env!("CARGO_BIN_EXE_ezone"), &["check", dir.join("z.zone").to_str().unwrap(), "--origin", "example.test"]), + run(env!("CARGO_BIN_EXE_econf"), &["check", dir.join("config.yaml").to_str().unwrap()]), + run(env!("CARGO_BIN_EXE_ediff"), &["www.example.test", "A", &format!("127.0.0.1:{p}"), &format!("127.0.0.1:{p}")]), + run(ed, &["+nonsense"]), + ) + } + }) + .await + .unwrap(); + let _ = s; + assert_eq!(ed_out.0, 0, "{}", ed_out.1); + assert!( + ed_out.1.contains("status: NOERROR") && ed_out.1.contains("192.0.2.10") && ed_out.1.contains("flags: qr aa rd"), + "{}", + ed_out.1 + ); + assert_eq!(short.1.trim(), "2001:db8::10"); + let v: serde_json::Value = serde_json::from_str(&json.1).unwrap(); + assert_eq!(v["header"]["status"], "NOERROR"); + assert_eq!(v["answer"][0]["data"], "10 mail.example.test."); + assert!(nx.0 == 0 && nx.1.contains("NXDOMAIN"), "dig semantics: NXDOMAIN is still exit 0"); + assert!(ax.1.contains("XFR size") && ax.0 == 0, "{}", ax.1); + assert!( + eh_out.1.contains("www.example.test has address 192.0.2.10") && eh_out.1.contains("has IPv6 address 2001:db8::10"), + "{}", + eh_out.1 + ); + assert!(ens.1.contains("Address: 192.0.2.10"), "{}", ens.1); + let v: serde_json::Value = serde_json::from_str(&eptr.1).unwrap(); + assert_eq!(v[0]["ptr"][0], "www.example.test."); + assert_eq!(ezone.0, 0, "{}", ezone.1); + assert!(ezone.1.contains("serial 1")); + assert_eq!(econf.0, 0, "{}", econf.1); + assert_eq!(ediff.0, 0, "{}", ediff.1); + assert!(ediff.1.contains("all servers agree")); + assert_eq!(bad.0, 1, "usage error exit code"); + + // a broken zone file fails validation with exit 1 + std::fs::write(dir.join("bad.zone"), "@ IN SOA ns hm 1 2 3 4 5\nx IN CNAME y\nx IN A 192.0.2.1\n").unwrap(); + let (code, out) = run(env!("CARGO_BIN_EXE_ezone"), &["check", dir.join("bad.zone").to_str().unwrap(), "-o", "example.test"]); + assert_eq!(code, 1, "{out}"); + // timeout -> exit 9 + let (code, _) = run(ed, &["@127.0.0.1", "-p", "9", "example.test", "--timeout", "300ms", "+tries=1"]); + assert_eq!(code, 9); + h.shutdown().await; +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..aeadf22 --- /dev/null +++ b/deny.toml @@ -0,0 +1,10 @@ +[advisories] +yanked = "deny" +[licenses] +allow = ["MIT", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Unicode-3.0", "Zlib", "CDLA-Permissive-2.0", "MPL-2.0"] +confidence-threshold = 0.8 +[bans] +multiple-versions = "warn" +[sources] +unknown-registry = "deny" +unknown-git = "deny" diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile new file mode 100644 index 0000000..30729c9 --- /dev/null +++ b/deploy/docker/Dockerfile @@ -0,0 +1,23 @@ +# syntax=docker/dockerfile:1 +# Multi-stage build; final image runs as an unprivileged user. +FROM rust:1-bookworm AS build +WORKDIR /src +COPY . . +RUN cargo build --release --locked -p dns-cli -p dns-tools \ + && mkdir -p /out \ + && cp target/release/easydns /out/ \ + && for t in ed eh ens etrace ednssec eptr ezone econf ebench ewhois edoh edot ediff; do cp target/release/$t /out/; done + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libcap2-bin && rm -rf /var/lib/apt/lists/* \ + && useradd --system --home /etc/easydns/data --shell /usr/sbin/nologin easydns \ + && mkdir -p /etc/easydns/zones.d /etc/easydns/keys.d /etc/easydns/data/zones && chown -R easydns:easydns /etc/easydns/data +COPY --from=build /out/ /usr/local/bin/ +COPY config/root.hints /etc/easydns/root.hints +RUN setcap cap_net_bind_service=+ep /usr/local/bin/easydns +USER easydns +VOLUME ["/etc/easydns/data"] +EXPOSE 53/udp 53/tcp 853/tcp +HEALTHCHECK --interval=30s --timeout=3s CMD ["/usr/local/bin/ed", "@127.0.0.1", "+short", "+time=2", "+tries=1", "version.bind", "TXT", "CH"] +ENTRYPOINT ["/usr/local/bin/easydns"] +CMD ["run", "--config", "/etc/easydns/config.yaml"] diff --git a/deploy/docker/Dockerfile.deb b/deploy/docker/Dockerfile.deb new file mode 100644 index 0000000..af2be38 --- /dev/null +++ b/deploy/docker/Dockerfile.deb @@ -0,0 +1,49 @@ +# syntax=docker/dockerfile:1 +# Builds EasyDNS .deb packages inside Docker. Used by scripts/build-deb.sh: +# docker buildx build -f deploy/docker/Dockerfile.deb --platform linux/amd64 \ +# --build-arg VERSION=0.1.0 --output type=local,dest=dist . +ARG DEBIAN_RELEASE=bookworm +FROM rust:1-${DEBIAN_RELEASE} AS build +ARG VERSION=0.1.0 +ARG REVISION=1 +ARG TARGETPLATFORM +WORKDIR /src +COPY . . +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/src/target,id=easydns-target-${TARGETPLATFORM} \ + cargo build --release --locked -p dns-cli -p dns-tools \ + && mkdir -p /pkg/usr/bin /pkg/usr/share/man/man1 /pkg/usr/share/bash-completion/completions \ + /pkg/usr/share/zsh/vendor-completions /pkg/usr/share/fish/vendor_completions.d \ + /pkg/lib/systemd/system /pkg/usr/lib/sysusers.d /pkg/etc/easydns/zones.d /pkg/etc/easydns/keys.d /pkg/usr/share/doc/easydns \ + && install -m 0755 -s target/release/easydns /pkg/usr/bin/easydns \ + && for t in easydig easyhost easynslookup easytrace easydnssec easyptr easyzone easyconf easybench easywhois easydoh easydot easydiff; do \ + install -m 0755 -s target/release/$t /pkg/usr/bin/$t; done \ + && target/release/easydns man > /pkg/usr/share/man/man1/easydns.1 && gzip -9n /pkg/usr/share/man/man1/easydns.1 \ + && target/release/easydns completions bash > /pkg/usr/share/bash-completion/completions/easydns \ + && target/release/easydns completions zsh > /pkg/usr/share/zsh/vendor-completions/_easydns \ + && target/release/easydns completions fish > /pkg/usr/share/fish/vendor_completions.d/easydns.fish \ + && install -m 0644 deploy/systemd/easydns.service deploy/systemd/easydns-blocklists.service deploy/systemd/easydns-blocklists.timer /pkg/lib/systemd/system/ \ + && install -m 0644 deploy/systemd/easydns.sysusers /pkg/usr/lib/sysusers.d/easydns.conf \ + && install -m 0640 config/config.yaml /pkg/etc/easydns/config.yaml \ + && install -m 0644 config/root.hints /pkg/etc/easydns/root.hints \ + && cp README.md CHANGELOG.md KNOWN_ISSUES.md LICENSE LICENSE-MIT /pkg/usr/share/doc/easydns/ \ + && cp -r docs config zones /pkg/usr/share/doc/easydns/ + +FROM debian:${DEBIAN_RELEASE}-slim AS package +ARG VERSION=0.1.0 +ARG REVISION=1 +COPY --from=build /pkg /pkg +COPY deploy/packaging/debian /debian-src +RUN apt-get update && apt-get install -y --no-install-recommends dpkg-dev >/dev/null && rm -rf /var/lib/apt/lists/* \ + && ARCH="$(dpkg --print-architecture)" \ + && mkdir -p /pkg/DEBIAN /out \ + && sed -e "s/@VERSION@/${VERSION}-${REVISION}/" -e "s/@ARCH@/${ARCH}/" \ + -e "s/@SIZE@/$(du -sk /pkg | cut -f1)/" /debian-src/control > /pkg/DEBIAN/control \ + && install -m 0755 /debian-src/postinst /debian-src/prerm /debian-src/postrm /pkg/DEBIAN/ \ + && printf '/etc/easydns/config.yaml\n/etc/easydns/root.hints\n' > /pkg/DEBIAN/conffiles \ + && dpkg-deb --root-owner-group -Zxz --build /pkg "/out/easydns_${VERSION}-${REVISION}_${ARCH}.deb" \ + && dpkg-deb --info "/out/easydns_${VERSION}-${REVISION}_${ARCH}.deb" >/dev/null \ + && (cd /out && sha256sum *.deb > "easydns_${VERSION}-${REVISION}_${ARCH}.deb.sha256") + +FROM scratch AS export +COPY --from=package /out/ / diff --git a/deploy/grafana/easydns.json b/deploy/grafana/easydns.json new file mode 100644 index 0000000..4f99c91 --- /dev/null +++ b/deploy/grafana/easydns.json @@ -0,0 +1,26 @@ +{ + "title": "EasyDNS", + "uid": "easydns", + "schemaVersion": 39, + "time": { "from": "now-6h", "to": "now" }, + "templating": { "list": [ { "name": "DS", "type": "datasource", "query": "prometheus" } ] }, + "panels": [ + { "type": "timeseries", "title": "Queries per second", "gridPos": {"x":0,"y":0,"w":12,"h":8}, + "targets": [ { "expr": "sum by (transport) (rate(dns_queries_total[1m]))" } ] }, + { "type": "timeseries", "title": "Responses by RCODE", "gridPos": {"x":12,"y":0,"w":12,"h":8}, + "targets": [ { "expr": "sum by (rcode) (rate(dns_responses_total[1m]))" } ] }, + { "type": "stat", "title": "Cache hit rate", "gridPos": {"x":0,"y":8,"w":6,"h":4}, + "targets": [ { "expr": "rate(dns_cache_hits_total[5m]) / (rate(dns_cache_hits_total[5m]) + rate(dns_cache_misses_total[5m]))" } ] }, + { "type": "timeseries", "title": "Latency p50/p95/p99", "gridPos": {"x":6,"y":8,"w":18,"h":8}, + "targets": [ + { "expr": "histogram_quantile(0.5, rate(dns_query_duration_seconds_bucket[5m]))", "legendFormat": "p50" }, + { "expr": "histogram_quantile(0.95, rate(dns_query_duration_seconds_bucket[5m]))", "legendFormat": "p95" }, + { "expr": "histogram_quantile(0.99, rate(dns_query_duration_seconds_bucket[5m]))", "legendFormat": "p99" } ] }, + { "type": "timeseries", "title": "Answer sources", "gridPos": {"x":0,"y":16,"w":12,"h":8}, + "targets": [ { "expr": "sum by (source) (rate(dns_answers_by_source_total[1m]))" } ] }, + { "type": "table", "title": "Zones", "gridPos": {"x":12,"y":16,"w":12,"h":8}, + "targets": [ { "expr": "dns_zone_serial" }, { "expr": "dns_zone_expired" } ] }, + { "type": "timeseries", "title": "Blocked / rate limited / DNSSEC bogus", "gridPos": {"x":0,"y":24,"w":24,"h":8}, + "targets": [ { "expr": "rate(dns_blocked_total[5m])" }, { "expr": "rate(dns_rate_limited_total[5m])" }, { "expr": "rate(dns_dnssec_bogus_total[5m])" } ] } + ] +} diff --git a/deploy/install.sh b/deploy/install.sh new file mode 100755 index 0000000..29e1d44 --- /dev/null +++ b/deploy/install.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env sh +# Install EasyDNS binaries. Short tool names (ed, eh, ...) are only linked when they do +# not collide with existing commands (e.g. the classic `ed` editor); long names +# (easydig, easyhost, ...) are always installed. +# usage: deploy/install.sh [PREFIX] [--force-short-names] +set -eu +PREFIX="${1:-/usr/local}" +FORCE="${2:-}" +BIN="$PREFIX/bin" +SRC="${EASYDNS_BUILD_DIR:-target/release}" +mkdir -p "$BIN" +install -m 0755 "$SRC/easydns" "$BIN/easydns" +for pair in edns:easydns ed:easydig eh:easyhost ens:easynslookup etrace:easytrace ednssec:easydnssec eptr:easyptr \ + ezone:easyzone econf:easyconf ebench:easybench ewhois:easywhois edoh:easydoh edot:easydot ediff:easydiff; do + short="${pair%%:*}"; long="${pair##*:}" + install -m 0755 "$SRC/$long" "$BIN/$long" + existing="$(command -v "$short" 2>/dev/null || true)" + if [ -n "$existing" ] && [ "$existing" != "$BIN/$short" ] && [ "$FORCE" != "--force-short-names" ]; then + echo "skip: '$short' already exists at $existing – use '$long' (or --force-short-names)" + continue + fi + ln -sf "$long" "$BIN/$short" +done +echo "installed into $BIN" +for sh in bash zsh fish; do + "$BIN/easydns" completions "$sh" > "easydns.$sh" 2>/dev/null && echo "completion: easydns.$sh" || true +done diff --git a/deploy/packaging/debian/control b/deploy/packaging/debian/control new file mode 100644 index 0000000..db07a03 --- /dev/null +++ b/deploy/packaging/debian/control @@ -0,0 +1,17 @@ +Package: easydns +Version: @VERSION@ +Architecture: @ARCH@ +Maintainer: EasyDNS maintainers +Installed-Size: @SIZE@ +Depends: libc6 (>= 2.34), ca-certificates, adduser +Section: net +Priority: optional +Homepage: https://example.invalid/easydns +Description: DNS server: primary, secondary, recursive, forwarder, hybrid + EasyDNS is an authoritative (primary/secondary with AXFR/IXFR, NOTIFY, TSIG, + DNSSEC signing), recursive (iterative, DNSSEC-validating), forwarding and hybrid + DNS server with DoT/DoH, REST API and Prometheus metrics. + . + Includes the EasyDNS Tools: easydig, easyhost, easynslookup, easytrace, + easydnssec, easyptr, easyzone, easyconf, easybench, easywhois, easydoh, + easydot and easydiff (short names ed, eh, ... are created when free). diff --git a/deploy/packaging/debian/postinst b/deploy/packaging/debian/postinst new file mode 100644 index 0000000..2c601c6 --- /dev/null +++ b/deploy/packaging/debian/postinst @@ -0,0 +1,46 @@ +#!/bin/sh +set -e +TOOLS="edns:easydns ed:easydig eh:easyhost ens:easynslookup etrace:easytrace ednssec:easydnssec eptr:easyptr ezone:easyzone econf:easyconf ebench:easybench ewhois:easywhois edoh:easydoh edot:easydot ediff:easydiff" +if [ "$1" = "configure" ]; then + if ! getent passwd easydns >/dev/null; then + adduser --system --group --home /etc/easydns/data --no-create-home --shell /usr/sbin/nologin easydns >/dev/null + fi + # /etc/easydns: config, zones.d/, keys.d/ (root:easydns, not world-readable – may hold keys) + install -d -o root -g easydns -m 0750 /etc/easydns /etc/easydns/zones.d /etc/easydns/keys.d + # data_dir: zone files (data/zones/), secondary copies, journals, control token + install -d -o easydns -g easydns -m 0750 /etc/easydns/data /etc/easydns/data/zones + chgrp easydns /etc/easydns/config.yaml 2>/dev/null || true + chmod 0640 /etc/easydns/config.yaml 2>/dev/null || true + # Short tool names only when the name is free (e.g. `ed` is often the line editor). + for pair in $TOOLS; do + s="${pair%%:*}"; l="${pair##*:}" + if [ ! -e "/usr/bin/$s" ] && ! command -v "$s" >/dev/null 2>&1; then + ln -s "$l" "/usr/bin/$s" + fi + done + if [ -d /run/systemd/system ]; then + systemctl daemon-reload >/dev/null || true + if [ -n "$2" ] && systemctl is-active --quiet easydns.service; then + # Upgrade of a running server: restart only if the new version accepts the + # configuration (checked as the service user); otherwise keep the old one running. + if command -v runuser >/dev/null 2>&1; then + CHECK="runuser -u easydns -- /usr/bin/easydns check-config --config /etc/easydns/config.yaml" + else + CHECK="/usr/bin/easydns check-config --config /etc/easydns/config.yaml" + fi + if $CHECK >/tmp/easydns-upgrade-check.log 2>&1; then + systemctl restart easydns.service && echo "EasyDNS upgraded from $2 and restarted." + rm -f /tmp/easydns-upgrade-check.log + else + echo "WARNING: the new EasyDNS rejects /etc/easydns/config.yaml; the previous version keeps running." + echo " details: /tmp/easydns-upgrade-check.log fix, then: systemctl restart easydns" + fi + elif [ -z "$2" ]; then + echo "EasyDNS installed (hybrid: authoritative + recursive for LAN)." + echo " config: /etc/easydns/config.yaml zones: /etc/easydns/data/zones/" + echo " new zone: easydns zone create example.com --ns ns1.example.com --ip 192.0.2.1" + echo " start: systemctl enable --now easydns then: easydns status" + fi + fi +fi +exit 0 diff --git a/deploy/packaging/debian/postrm b/deploy/packaging/debian/postrm new file mode 100644 index 0000000..c877398 --- /dev/null +++ b/deploy/packaging/debian/postrm @@ -0,0 +1,18 @@ +#!/bin/sh +set -e +TOOLS="edns:easydns ed:easydig eh:easyhost ens:easynslookup etrace:easytrace ednssec:easydnssec eptr:easyptr ezone:easyzone econf:easyconf ebench:easybench ewhois:easywhois edoh:easydoh edot:easydot ediff:easydiff" +if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then + # remove only symlinks we created + for pair in $TOOLS; do + s="${pair%%:*}"; l="${pair##*:}" + if [ -L "/usr/bin/$s" ] && [ "$(readlink "/usr/bin/$s")" = "$l" ]; then rm -f "/usr/bin/$s"; fi + done +fi +if [ "$1" = "purge" ]; then + # /etc/easydns holds your zone files and keys: never deleted automatically + rm -f /etc/easydns/data/control.token + echo "EasyDNS purged. /etc/easydns (zones, keys, data) was kept – remove it manually if no longer needed." + +fi +[ -d /run/systemd/system ] && systemctl daemon-reload >/dev/null 2>&1 || true +exit 0 diff --git a/deploy/packaging/debian/prerm b/deploy/packaging/debian/prerm new file mode 100755 index 0000000..a890b21 --- /dev/null +++ b/deploy/packaging/debian/prerm @@ -0,0 +1,6 @@ +#!/bin/sh +set -e +if [ "$1" = "remove" ] && [ -d /run/systemd/system ]; then + systemctl stop easydns.service easydns-blocklists.timer >/dev/null 2>&1 || true +fi +exit 0 diff --git a/deploy/packaging/nfpm.yaml b/deploy/packaging/nfpm.yaml new file mode 100644 index 0000000..43548e3 --- /dev/null +++ b/deploy/packaging/nfpm.yaml @@ -0,0 +1,55 @@ +# Build .deb and .rpm with nfpm (https://nfpm.goreleaser.com): +# ARCH=amd64 VERSION=0.1.0 nfpm pkg -f deploy/packaging/nfpm.yaml -p deb +# ARCH=arm64 VERSION=0.1.0 nfpm pkg -f deploy/packaging/nfpm.yaml -p rpm +name: easydns +arch: "${ARCH}" +platform: linux +version: "${VERSION}" +maintainer: "EasyDNS maintainers" +description: | + EasyDNS: authoritative (primary/secondary), recursive, forwarding and hybrid DNS + server with DoT/DoH, DNSSEC and the EasyDNS Tools (easydig, easyhost, ...). +license: MIT +contents: + - src: target/release/easydns + dst: /usr/bin/easydns + - src: target/release/easydig + dst: /usr/bin/easydig + - src: target/release/easyhost + dst: /usr/bin/easyhost + - src: target/release/easynslookup + dst: /usr/bin/easynslookup + - src: target/release/easytrace + dst: /usr/bin/easytrace + - src: target/release/easydnssec + dst: /usr/bin/easydnssec + - src: target/release/easyptr + dst: /usr/bin/easyptr + - src: target/release/easyzone + dst: /usr/bin/easyzone + - src: target/release/easyconf + dst: /usr/bin/easyconf + - src: target/release/easybench + dst: /usr/bin/easybench + - src: target/release/easywhois + dst: /usr/bin/easywhois + - src: target/release/easydoh + dst: /usr/bin/easydoh + - src: target/release/easydot + dst: /usr/bin/easydot + - src: target/release/easydiff + dst: /usr/bin/easydiff + - src: deploy/systemd/easydns.service + dst: /usr/lib/systemd/system/easydns.service + - src: deploy/systemd/easydns.sysusers + dst: /usr/lib/sysusers.d/easydns.conf + - src: config/config.yaml + dst: /etc/easydns/config.yaml + type: config|noreplace + - src: config/root.hints + dst: /etc/easydns/root.hints + type: config|noreplace + - src: target/man/easydns.1 + dst: /usr/share/man/man1/easydns.1 +scripts: + postinstall: deploy/packaging/postinstall.sh diff --git a/deploy/packaging/postinstall.sh b/deploy/packaging/postinstall.sh new file mode 100644 index 0000000..f9746d1 --- /dev/null +++ b/deploy/packaging/postinstall.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Create the service user and short tool names when they do not collide. +set -e +systemd-sysusers /usr/lib/sysusers.d/easydns.conf 2>/dev/null || true +mkdir -p /etc/easydns/zones.d /etc/easydns/keys.d /etc/easydns/data/zones +chown -R easydns:easydns /etc/easydns/data 2>/dev/null || true +chgrp easydns /etc/easydns /etc/easydns/zones.d /etc/easydns/keys.d /etc/easydns/config.yaml 2>/dev/null || true +chmod 0750 /etc/easydns /etc/easydns/zones.d /etc/easydns/keys.d /etc/easydns/data 2>/dev/null || true +for pair in edns:easydns ed:easydig eh:easyhost ens:easynslookup etrace:easytrace ednssec:easydnssec eptr:easyptr ezone:easyzone econf:easyconf ebench:easybench ewhois:easywhois edoh:easydoh edot:easydot ediff:easydiff; do + s="${pair%%:*}"; l="${pair##*:}" + if ! command -v "$s" >/dev/null 2>&1; then ln -s "/usr/bin/$l" "/usr/bin/$s"; fi +done +systemctl daemon-reload 2>/dev/null || true diff --git a/deploy/release.sh b/deploy/release.sh new file mode 100755 index 0000000..950a969 --- /dev/null +++ b/deploy/release.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Build release archives + checksums for x86_64 and aarch64 (requires `cross` or native toolchains). +set -euo pipefail +VERSION="$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)" +mkdir -p dist target/man +for TARGET in x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu; do + if command -v cross >/dev/null; then B=cross; else B=cargo; fi + $B build --release --locked --target "$TARGET" -p dns-cli -p dns-tools + D="dist/easydns-$VERSION-$TARGET"; mkdir -p "$D" + cp target/$TARGET/release/{easydns,easydig,easyhost,easynslookup,easytrace,easydnssec,easyptr,easyzone,easyconf,easybench,easywhois,easydoh,easydot,easydiff} "$D/" + cp -r config README.md LICENSE* deploy/systemd deploy/install.sh "$D/" + tar -C dist -czf "$D.tar.gz" "$(basename "$D")" +done +target/release/easydns man > target/man/easydns.1 || true +(cd dist && sha256sum ./*.tar.gz > SHA256SUMS) +echo "artifacts in dist/" diff --git a/deploy/systemd/easydns-blocklists.service b/deploy/systemd/easydns-blocklists.service new file mode 100644 index 0000000..7283854 --- /dev/null +++ b/deploy/systemd/easydns-blocklists.service @@ -0,0 +1,9 @@ +[Unit] +Description=Update EasyDNS block lists +After=network-online.target + +[Service] +Type=oneshot +User=easydns +EnvironmentFile=-/etc/easydns/easydns.env +ExecStart=/usr/bin/easydns blocklists update --config /etc/easydns/config.yaml diff --git a/deploy/systemd/easydns-blocklists.timer b/deploy/systemd/easydns-blocklists.timer new file mode 100644 index 0000000..41aa4ca --- /dev/null +++ b/deploy/systemd/easydns-blocklists.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Daily EasyDNS block list update + +[Timer] +OnCalendar=daily +RandomizedDelaySec=1h +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/deploy/systemd/easydns.service b/deploy/systemd/easydns.service new file mode 100644 index 0000000..43786e0 --- /dev/null +++ b/deploy/systemd/easydns.service @@ -0,0 +1,52 @@ +[Unit] +Description=EasyDNS server +Documentation=https://example.invalid/easydns/docs +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=easydns +Group=easydns +ExecStartPre=/usr/bin/easydns check-config --config /etc/easydns/config.yaml +ExecStart=/usr/bin/easydns run --config /etc/easydns/config.yaml +ExecReload=/bin/kill -HUP $MAINPID +Restart=on-failure +RestartSec=2s +EnvironmentFile=-/etc/easydns/easydns.env +StateDirectory=easydns +StateDirectoryMode=0750 +ConfigurationDirectory=easydns +LimitNOFILE=65536 +TasksMax=4096 + +# Bind to port 53 without root +AmbientCapabilities=CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +NoNewPrivileges=yes + +# Sandbox +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged @resources +UMask=0027 +ReadWritePaths=/etc/easydns/data + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/easydns.sysusers b/deploy/systemd/easydns.sysusers new file mode 100644 index 0000000..a70c326 --- /dev/null +++ b/deploy/systemd/easydns.sysusers @@ -0,0 +1 @@ +u easydns - "EasyDNS server" /etc/easydns/data /usr/sbin/nologin diff --git a/dev.sh b/dev.sh new file mode 100644 index 0000000..8a76c23 --- /dev/null +++ b/dev.sh @@ -0,0 +1,142 @@ +#!/usr/bin/env bash +# EasyDNS developer helper. Runs everything from source with `cargo` (debug build), +# with a throw-away configuration and state in ./.dev (git-ignored). +# +# ./dev.sh run primary+recursive+forwarder+API on 127.0.0.1:5353 (default) +# ./dev.sh run-secondary second instance on 127.0.0.1:5354, secondary of the first one +# ./dev.sh dnssec like `run`, with example.com signed online (keys in .dev/keys) +# ./dev.sh q NAME [TYPE] query the dev server with `ed` (cargo run) +# ./dev.sh api PATH GET an API path with the dev admin token (e.g. ./dev.sh api /status) +# ./dev.sh tool NAME ... run any tool, e.g. ./dev.sh tool eh -p 5353 example.com 127.0.0.1 +# ./dev.sh check fmt + clippy -D warnings + tests (the CI acceptance commands) +# ./dev.sh test [ARGS] cargo test --workspace [ARGS] +# ./dev.sh e2e release build + scripts/e2e.sh (needs dig/host/nslookup) +# ./dev.sh watch restart `run` on source changes (needs cargo-watch) +# ./dev.sh reset delete ./.dev +# +# Environment: DEV_PORT (5353), DEV_API (9953), DEV_METRICS (9090), DEV_LOG (debug), +# DEV_UPSTREAMS (forwarder upstreams, default "1.1.1.1,9.9.9.9"). +set -euo pipefail +cd "$(dirname "$0")" +ROOT="$PWD" +DEV="$ROOT/.dev" +PORT="${DEV_PORT:-5353}" +API="${DEV_API:-9953}" +METRICS="${DEV_METRICS:-9090}" +LOG="${DEV_LOG:-debug,hyper=info,h2=info}" +UPSTREAMS="${DEV_UPSTREAMS:-1.1.1.1,9.9.9.9}" + +mkdir -p "$DEV" +# Stable dev secrets (generated once, never committed). +[ -f "$DEV/tsig.secret" ] || head -c 32 /dev/urandom | base64 > "$DEV/tsig.secret" +[ -f "$DEV/admin.token" ] || echo "dev-$(head -c 12 /dev/urandom | base64 | tr -dc 'a-zA-Z0-9')" > "$DEV/admin.token" +chmod 600 "$DEV"/*.secret "$DEV"/*.token 2>/dev/null || true +mkdir -p "$DEV/data/zones" # same layout as an installation: zone files in /zones/ +[ -f "$DEV/data/zones/example.com.zone" ] || cp "$ROOT/zones/example.com.zone" "$DEV/data/zones/example.com.zone" +[ -f "$DEV/data/zones/reverse.zone" ] || cp "$ROOT/zones/2.0.192.in-addr.arpa.zone" "$DEV/data/zones/reverse.zone" +[ -f "$DEV/block.txt" ] || printf 'ads.example\n*.tracker.example\n' > "$DEV/block.txt" + +upstreams_yaml() { local IFS=,; for u in $UPSTREAMS; do printf '"%s", ' "$u"; done | sed 's/, $//'; } + +write_primary_config() { + local dnssec="${1:-}" + cat > "$DEV/config.yaml" <> EasyDNS dev: DNS 127.0.0.1:$PORT API http://127.0.0.1:$API (token: $(cat "$DEV/admin.token")) metrics http://127.0.0.1:$METRICS/metrics" + echo ">> try: ./dev.sh q www.example.com | ./dev.sh api /status | dig @127.0.0.1 -p $PORT example.com SOA" + EASYDNS_LOG="$LOG" cargo run -q -p dns-cli --bin easydns -- run --config "$1" +} + +cmd="${1:-run}"; shift || true +case "$cmd" in + run) + [ -f "$DEV/config.yaml" ] || write_primary_config + cargo run -q -p dns-cli --bin easydns -- check-config --config "$DEV/config.yaml" + run_easydns "$DEV/config.yaml" + ;; + dnssec) + write_primary_config $'\n dnssec: { keys_dir: keys, auto_generate: true }' + echo ">> DS for the parent will be printed by: cargo run -p dns-cli --bin easydns -- dnssec ds --zone example.com --dir .dev/keys" + run_easydns "$DEV/config.yaml" + ;; + run-secondary) + mkdir -p "$DEV/secondary" + cp "$DEV/tsig.secret" "$DEV/secondary/tsig.secret" + cat > "$DEV/secondary/config.yaml" <> secondary on 127.0.0.1:$((PORT+1)) (primary: ./dev.sh run)" + EASYDNS_LOG="$LOG" cargo run -q -p dns-cli --bin easydns -- run --config "$DEV/secondary/config.yaml" + ;; + q) + [ $# -ge 1 ] || { echo "usage: ./dev.sh q NAME [TYPE] [+opts]" >&2; exit 1; } + cargo run -q -p dns-tools --bin ed -- @127.0.0.1 -p "$PORT" "$@" + ;; + api) + path="${1:-/status}" + curl -fsS -H "Authorization: Bearer $(cat "$DEV/admin.token")" "http://127.0.0.1:$API/api/v1$path"; echo + ;; + tool) + [ $# -ge 1 ] || { echo "usage: ./dev.sh tool NAME [ARGS]" >&2; exit 1; } + t="$1"; shift + cargo run -q -p dns-tools --bin "$t" -- "$@" + ;; + check) + cargo fmt --all -- --check + cargo clippy --workspace --all-targets --all-features -- -D warnings + cargo test --workspace --all-features + ;; + test) + cargo test --workspace "$@" + ;; + e2e) + cargo build --release -p dns-cli -p dns-tools + BIN=target/release ./scripts/e2e.sh + ;; + watch) + command -v cargo-watch >/dev/null || { echo "install with: cargo install cargo-watch" >&2; exit 1; } + [ -f "$DEV/config.yaml" ] || write_primary_config + EASYDNS_LOG="$LOG" cargo watch -w crates -x "run -q -p dns-cli --bin easydns -- run --config $DEV/config.yaml" + ;; + reset) + rm -rf "$DEV"; echo "removed $DEV" + ;; + -h|--help|help) + sed -n '2,20p' "$0" + ;; + *) + echo "unknown command: $cmd (see ./dev.sh help)" >&2; exit 1 + ;; +esac diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..030d98e --- /dev/null +++ b/docs/api.md @@ -0,0 +1,40 @@ +# REST API (`/api/v1`) + +Bearer tokens (`Authorization: Bearer `); roles: `admin` (all) and `read-only` (GET). +Default listener: `127.0.0.1:9953`. The server creates a local admin token in +`/control.token` (0640, `api.local_token`), used automatically by the `easydns` +CLI; define `api.tokens` for remote tools and automation. +Errors: `{"error": {"status": 403, "message": "..."}}`. Machine-readable description: +`GET /api/v1/openapi.json`. + +| Method | Endpoint | Notes | +|---|---|---| +| GET | `/api/v1/health`, `/healthz`, `/readyz` | public | +| GET | `/api/v1/status` | version, mode, roles, listeners, zone states | +| GET | `/api/v1/stats` | counters, latency quantiles, cache hit rate | +| GET/POST | `/api/v1/zones` | list (`?page&per_page&name&kind`) / create primary zone (`zone_file` or `ns` + `hostmaster`) | +| GET/PUT/DELETE | `/api/v1/zones/{zone}` | details + ETag / replace contents (`zone_file`) / delete API-created zone (409 for config zones) | +| GET/POST | `/api/v1/zones/{zone}/records` | list (`?name&type&page&per_page`) / add `{name,type,ttl,data}` | +| PUT/DELETE | `/api/v1/zones/{zone}/records/{id}` | replace / delete; `If-Match: ""` → 412 on conflict | +| POST | `/api/v1/zones/{zone}/notify` | send NOTIFY | +| POST | `/api/v1/zones/{zone}/sync` | refresh a secondary now | +| GET | `/api/v1/zones/{zone}/transfers` | transfer history (in/out) | +| GET/DELETE | `/api/v1/cache` | stats / flush (`?domain=`) | +| GET/POST | `/api/v1/upstreams` | status / add upstream (persisted, reload) | +| GET/PUT | `/api/v1/policies` | ACLs, views, rate limit, policy / update allowlist, block action | +| GET/POST | `/api/v1/blocklists` | lists / add a rule | +| POST | `/api/v1/config/reload` | hot reload with rollback | +| GET | `/api/v1/audit` | audit log tail (`?n=`) | +| GET | `/api/v1/query?name=&type=` | resolve through this server | + +All state-changing calls are audited (`/audit.log`, JSON lines). Record IDs are +stable hashes of (name, type, data). Changes made via the API persist in the zone files +and in `/api-overlay.yaml`. + +```bash +T=$(sudo cat /etc/easydns/data/control.token) # or a token from api.tokens +curl -H "Authorization: Bearer $T" localhost:9953/api/v1/zones +curl -X POST -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \ + -d '{"name":"www","type":"A","ttl":300,"data":"192.0.2.10"}' \ + localhost:9953/api/v1/zones/example.com/records +``` diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..dca1c00 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,86 @@ +# Architecture + +``` +crates/ + dns-core protocol helpers on hickory-proto: client (UDP→TCP, AXFR/IXFR streams, NOTIFY), + TSIG (RFC 8945, multi-message), RFC 1982 serials, zone files (+DNSSEC/RFC 3597 + pre-processor), DNSSEC primitives (sign/verify/DS/NSEC/NSEC3), DoT/DoH client + dns-config YAML/JSON schema, ENV/CLI precedence, offline validation with locations + dns-authoritative Zone (immutable snapshot + RFC 1034/4592 lookup), journal (IXFR), xfr, + store (Primary/Secondary entries, atomic swap), secondary (SOA timers), + update (RFC 2136), signing (online DNSSEC) + dns-cache bounded LRU answer/RRset cache, namespaces per route, RFC 2308 + dns-recursive iterative resolver, root hints, validator (DNSSEC chain of trust) + dns-forwarder upstream pools, strategies, circuit breaker, health checks + dns-policy ACLs, views, rate limiter, block/allow lists, local-only names + dns-server listeners (UDP/TCP/DoT/DoH), dispatcher (handler), router (hybrid), + encoded-answer cache, query coalescing, + runtime snapshot + hot reload, audit log, offline checks + dns-api REST API (axum), auth/roles, metrics endpoint + dns-metrics low-cardinality counters/histograms, Prometheus text, logging setup + dns-cli `easydns` + dns-tools ed, eh, ens, etrace, ednssec, eptr, ezone, econf, ebench, ewhois, edoh, edot, ediff +``` + +## Data flow + +Each listener reads a message and calls `handler::handle(shared, bytes, peer, transport)`, +which returns zero, one or many encoded messages (zone transfers). The handler takes an +`Arc` snapshot at the start of every query; a reload builds a complete new +`Runtime` and swaps the pointer, so in-flight queries finish on the configuration they +started with and a failed reload leaves the old one active (rollback). + +Fast path: before parsing, `handler::handle_with` (and, for UDP, `udp_fast_path` inside +the receive loop) looks the raw query up in the **encoded-answer cache** +(`packet_cache.rs`), keyed by the query bytes and the client profile. A hit is the +stored response with the ID, question case and TTLs patched – no parsing, policy, +lookup or encoding. Misses take the full path; their responses are stored if cacheable. +Zone publication (`ZoneEntry::install`), expiry changes, reloads and cache flushes bump a +generation number that invalidates all stored answers. On Linux the UDP loop receives +and sends in batches (`recvmmsg`/`sendmmsg`). + +## Zone data + +A `Zone` is immutable and validated on construction (single SOA at the apex, apex NS, +no CNAME conflicts, all data in-zone, TTL normalisation per RRset). Changes always build a +new `Zone` and publish it with one pointer swap (`ZoneEntry::install`), therefore a query +can never observe a half-applied change. IXFR diffs are computed between snapshots and +appended to a JSON-lines journal (`/journal/.jnl`, wire-format records). + +### Why files and not SQLite? + +The spec asks for a durable backend for zones, transfer journals and admin data and to +justify the choice. EasyDNS uses plain files because: +* zones stay in BIND format, editable and diffable by operators (spec: "identycznie do bind"); +* the only mutable data is append-only (journal, audit) or replaced atomically + (`write tmp → fsync → rename → fsync dir`), which needs no transactions; +* no extra native dependency, trivial backup (`tar` of `/etc/easydns` + `/etc/easydns/data`). +Schema "migrations" are version-tolerant readers: unknown journal lines truncate the +journal (IXFR then falls back to AXFR); snapshots are plain zone files. + +| Path (`data_dir`) | Content | +|---|---| +| `zones/secondary/.zone` + `.meta.json` | last valid secondary copy + last successful refresh | +| `journal/.jnl` | IXFR differences | +| `signed/.zone` | last signed version of DNSSEC zones (keeps signatures stable across restarts) | +| `zones/` | zones created via the API | +| `api-overlay.yaml` | API changes (zones, upstreams, allowlist, block rules) merged on load | +| `blocklists/` | downloaded/API block lists | +| `audit.log` | JSON lines of administrative actions | + +## Hybrid decision order + +1. local authoritative zone (most specific, visible in the client's view) → AA answer; +2. client not allowed to recurse → REFUSED; +3. local-only names (RFC 6761/6303, configurable) → NXDOMAIN, never sent out; +4. allow/block policy; +5. conditional forwarding (longest suffix, optional client ACL); +6. default resolution: `recursive`, `forward`, `forwardthenrecursive` or `refuse`. + +Each route has its own cache namespace; authoritative data is never cached. + +## Extension points + +* Transports: implement a listener that feeds `handler::handle` (DoQ/DoH3 planned). +* Zone backends: `ZoneEntry` owns loading/persisting; a database backend would replace + `load_primary_file`/`modify` while keeping snapshot publication unchanged. diff --git a/docs/cli-tools.md b/docs/cli-tools.md new file mode 100644 index 0000000..ef2514c --- /dev/null +++ b/docs/cli-tools.md @@ -0,0 +1,117 @@ +# CLI: `easydns` and EasyDNS Tools + +## easydns + +``` +easydns run [--listen ADDR]... [--log-level L] [--data-dir D] +easydns check-config | config validate | config show +easydns status | version | query NAME [TYPE] | reload +easydns zone create ZONE [--ns NAME[=IP]]... [--ip IP]... [--email E] [--allow-transfer IP]... + [--notify IP]... [--allow-update IP]... [--ttl S] [--dry-run] [--force] [--reload] +easydns zones list|show|sync|notify|transfers|records ZONE (`zone` is an alias of `zones`) +easydns cache clear [--domain D] | cache stats +easydns upstreams list +easydns blocklists update easydns root-hints update +easydns dnssec keygen --zone Z --dir D [--role csk|ksk|zsk] [--algorithm ed25519] +easydns dnssec ds --zone Z --dir D +easydns hash-token TOKEN easydns tools +easydns completions bash|zsh|fish|elvish|powershell easydns man +``` +Global: `-c/--config` (default `/etc/easydns/config.yaml`), `--api URL`, `--token` +(`EASYDNS_API_TOKEN`), `--json`. +Exit codes: 0 ok, 1 operation failed, 2 invalid usage/configuration, 3 API unreachable. + +**No key needed locally.** Commands that talk to the running server (`status`, `reload`, +`zones …`, `cache …`, `query`) use the API on `127.0.0.1:9953`. Without `--token` the CLI +reads the server's local control token from `/control.token` (created by the +server, mode 0640, readable by root and the `easydns` group). So after installation +`sudo easydns status` simply works; add your admin user to the `easydns` group to drop +`sudo`. `--token` is only needed for remote servers or when `api.local_token: false`. + +### Creating a zone + +`easydns zone create` writes a minimal, valid primary zone – SOA, NS, glue for in-zone +name servers and optional apex addresses – into `/zones/.zone` +(`/etc/easydns/data/zones/`) and its definition into `/etc/easydns/zones.d/.yaml`. +The zone is parsed and validated before anything is written; existing files are never +overwritten without `--force`. + +```bash +# name servers inside the zone need an address (glue) +easydns zone create example.com --ns ns1.example.com=192.0.2.10 --ns ns2.example.net --ip 192.0.2.80 +# external name servers only, mailbox, secondary allowed to transfer + NOTIFY, reload at once +easydns zone create example.org --ns ns1.example.net --ns ns2.example.net \ + --email dns-admin@example.net --allow-transfer 198.51.100.20 --notify 198.51.100.20 --reload +# preview only +easydns zone create example.net --ns ns.example.org --dry-run +``` + +Result for the first command: +``` +; example.com. – created by `easydns zone create` +$ORIGIN example.com. +$TTL 3600 +@ IN SOA ns1.example.com. hostmaster.example.com. ( + 2026112201 ; serial + 3600 ; refresh + 900 ; retry + 1209600 ; expire + 300 ) ; negative TTL +@ IN NS ns1.example.com. +@ IN NS ns2.example.net. +ns1 IN A 192.0.2.10 +@ IN A 192.0.2.80 +``` +```yaml +# /etc/easydns/zones.d/example.com.yaml +- name: example.com + type: primary + file: zones/example.com.zone +``` + +| Option | Meaning (default) | +|---|---| +| `--ns NAME[=IP]` | name server, repeatable (`ns1.`; in-zone names need `=IP` unless `--ip` is given) | +| `--ip IP` | `@ A`/`@ AAAA`, repeatable; also glue for a default `ns1` without its own address | +| `--email` | SOA mailbox (`hostmaster@`) | +| `--ttl` | `$TTL` (3600) | +| `--allow-transfer IP` | `transfer_acl` – secondaries allowed to transfer, **no key needed** | +| `--notify IP[:PORT]` | secondaries to NOTIFY | +| `--allow-update IP` | RFC 2136 updates from these addresses without a key | +| `--no-config` | write only the zone file and print the definition | +| `--dry-run`, `--force`, `--reload` | preview / overwrite / reload the server afterwards | + +Serial: `YYYYMMDD01`. Files are created mode 0640 and, when run as root, owned by the +owner of the data directory (the `easydns` user), so the server can later write DDNS and +API changes. Then add records to the file and run `easydns reload` (or use the REST API). + +## Tools + +Every tool has a short and a long binary name, `--help`, `--version`, `--json` where the +output is structured. Exit codes: 0 success (a DNS answer, also NXDOMAIN for `ed`), +1 usage error / negative result (eh, eptr) / differences (ediff), 9 no reply, 10 internal error. + +| Tool | Replaces | Examples | +|---|---|---| +| `ed` / `easydig` | dig | `ed @1.1.1.1 example.com MX +short`, `ed -x 8.8.8.8`, `ed example.com +dnssec +tcp`, `ed example.com --json`, `--yaml`, `--watch 5s`, `--compare 1.1.1.1,8.8.8.8`, `--benchmark 1000`, `-y hmac-sha256:key:SECRET example.com AXFR` | +| `eh` / `easyhost` | host | `eh example.com`, `eh -t MX example.com`, `eh 8.8.8.8`, `eh --all example.com`, `eh --json example.com` | +| `ens` / `easynslookup` | nslookup | `ens example.com 8.8.8.8`, `ens -type=MX example.com`, `ens --interactive` (`server X`, `set type=AAAA`, `exit`) | +| `etrace` / `easytrace` | dig +trace | `etrace example.com --dnssec --json` | +| `ednssec` / `easydnssec` | delv | `ednssec example.com A -v` (secure/insecure/bogus with reason; exit 2 = bogus) | +| `eptr` / `easyptr` | dig -x | `eptr 192.0.2.1 2001:db8::1 --verify` (forward-confirmed) | +| `ezone` / `easyzone` | named-checkzone | `ezone check zones/example.com.zone --origin example.com`, `ezone validate --all -c config.yaml`, `ezone canonical ...` | +| `econf` / `easyconf` | named-checkconf | `econf check config.yaml`, `econf print config.yaml` | +| `ebench` / `easybench` | dnsperf | `ebench @127.0.0.1 --qps 1000 --duration 30s -c 50 -d queries.txt` (high load needs `--i-own-this-server`) | +| `ediff` / `easydiff` | – | `ediff example.com MX @1.1.1.1 @8.8.8.8 --json` (order-insensitive, TTL shown not compared) | +| `edoh` / `easydoh` | – | `edoh https://1.1.1.1/dns-query example.com --method get`, `--http2` (reports whether h2 was negotiated) | +| `edot` / `easydot` | – | `edot 1.1.1.1 example.com --tls-name cloudflare-dns.com` | +| `ewhois` / `easywhois` | whois | `ewhois example.com` (RDAP via IANA bootstrap), `ewhois --whois 192.0.2.1` | + +Output colours are used only on a TTY (`--no-color`, `NO_COLOR`). The default server is the +first `nameserver` in `/etc/resolv.conf`. + +`ed` and `eh` can clash with existing commands (`ed` is the classic editor). The installer +links short names only when they are free; long names are always installed. + +Compatibility is tested by *meaning*: `scripts/e2e.sh` compares `ed … +short` with `dig … +short` +after sorting (RRset order and TTLs may differ). diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..0c36bff --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,208 @@ +# Configuration + +`config.yaml` (JSON is accepted too). Unknown keys are rejected with file/line information. +Precedence: **CLI > ENV > file > defaults**, then changes made through the API +(`/api-overlay.yaml`) are merged. + +Validate offline: `easydns check-config -c config.yaml` or `econf check config.yaml` +(also loads every primary zone file). Exit code 2 on errors. + +## Default installation layout + +| Path | Contents | Owner / mode | +|---|---|---| +| `/etc/easydns/config.yaml` | main configuration ([config/config.yaml](../config/config.yaml)) | root:easydns 0640 | +| `/etc/easydns/zones.d/*.yaml` | zone definitions, one file per zone (`easydns zone create` writes here) | root:easydns 0750 | +| `/etc/easydns/keys.d/*.conf` | TSIG keys – BIND `key "…" { … };` files copied unchanged | root:easydns 0640 | +| `/etc/easydns/data/` | `server.data_dir`: everything the server writes | easydns:easydns 0750 | +| `/etc/easydns/data/zones/` | zone files of primary zones (`file: zones/example.com.zone`) | easydns | +| `/etc/easydns/data/zones/secondary/` | copies of secondary zones (+ `.meta.json`) | easydns | +| `/etc/easydns/data/journal/` | IXFR journals | easydns | +| `/etc/easydns/data/control.token` | local admin token for the CLI | easydns 0640 | +| `/etc/easydns/data/audit.log`, `api-overlay.yaml`, `signed/` | audit trail, API changes, signed zones | easydns | + +The default configuration runs a **hybrid** node: authoritative for the zones in +`zones.d/`, recursive resolver for `acls.lan` (`192.168.0.0/16`, `10.0.0.0/8`, +`127.0.0.1/32`; add `172.16.0.0/12` if you use it), listening on `0.0.0.0:53` and +`[::1]:53`. + +## Zone file paths + +A relative zone `file:` is relative to `server.data_dir`: `file: zones/example.com.zone` +is `/etc/easydns/data/zones/example.com.zone`. Absolute paths are used as they are. +(Older configurations whose relative paths point next to the config file keep working: +if the file is not found under `data_dir` but exists relative to the configuration +directory, that one is used.) + +## Include files + +Zone definitions (and keys, ACLs, forward zones) can be split into separate files, like +BIND's `include "named.conf.zones";`: + +```yaml +# /etc/easydns/config.yaml +include: + - "zones.d/*.yaml" # glob in the file name; sorted; empty directory is fine + - "keys.yaml" # literal path; must exist +server: { ... } +``` + +An included file is either a **list of zones**: +```yaml +- { name: example.org, type: secondary, primaries: ["192.0.2.53:53"] } +- { name: example.net, type: secondary, primaries: ["192.0.2.53:53"] } +``` +or a **mapping** with any of `zones`, `keys`, `acls`, `forward_zones` and a nested +`include` (relative to that file): +```yaml +keys: [ { name: example-net-xfr, secret: "env:DNS_TSIG_EXAMPLE_NET" } ] +acls: { example-net-primaries: ["198.51.100.10/32"] } +zones: [ { name: example.net, type: secondary, primaries: ["198.51.100.10:53"], transfer: { tsig_key: example-net-xfr } } ] +``` + +A file whose first statement is a BIND **`key`** statement is read as a BIND key file, so +`keys.conf` from a BIND server can be included unchanged: +``` +key "ddns.example.com" { + algorithm hmac-sha512; + secret "base64-secret"; +}; +``` +Only `key { algorithm; secret; };` is accepted there (comments `#`, `//`, `/* */` allowed); +any other statement is an error with its line number. Keep such files `0640 root:easydns` +– `check-config` warns when they are world-readable. + +Rules: include patterns are relative to the including file; zone `file:` paths are +relative to `data_dir` (see above) and `file:` secret references to the **main** +configuration file's directory; +hidden files and `*~` backups are skipped; recursive/duplicate includes and redefined ACLs +are errors; duplicate zones are reported with the file they come from; nesting depth ≤ 8. +Includes are re-read on every reload, so adding a zone = drop a file into `zones.d/` and +run `easydns reload`. Zone files themselves support BIND `$INCLUDE`. + +## Environment overrides + +| Variable | Effect | +|---|---| +| `EASYDNS_LISTEN` | comma-separated listen addresses | +| `EASYDNS_LOG_LEVEL` | log level / filter | +| `EASYDNS_DATA_DIR` | data directory | +| `EASYDNS_API_LISTEN` | API listen address | +| `EASYDNS_LOG` | full `tracing` filter (e.g. `info,query=info`) | + +CLI: `easydns run --listen 127.0.0.1:5353 --log-level debug --data-dir /tmp/x`. + +## Secrets + +TSIG secrets and API tokens are **references**: `env:VAR`, `file:/path` or (discouraged, +warned) `base64:...`; API tokens may also be `sha256:` (`easydns hash-token`). +TSIG keys can also come from BIND key files in `keys.d/` (see above). +Secrets are never logged (`TsigKey` redacts itself in debug output). + +TSIG keys are **optional** everywhere: zone transfers, NOTIFY and dynamic updates can be +authorised by IP address alone (see [zone-transfer-variants.md](zone-transfer-variants.md) +and [primary.md](primary.md#dynamic-updates-rfc-2136)). + +The local API token (`api.local_token`, default on) is created by the server in +`/control.token` with mode 0640; the `easydns` CLI reads it automatically, so +`easydns status`, `easydns reload` etc. work right after installation for root and members +of the `easydns` group, without generating or passing a key. Set `local_token: false` to +require explicit tokens only. + +## Sections (defaults in brackets) + +```yaml +server: + mode: hybrid # primary|master, secondary|slave, recursive|resolver, forwarder, hybrid|mixed, cache-only + listen: ["0.0.0.0:53", "[::1]:53"] # [::] addresses are IPv6-only, so they can be listed next to 0.0.0.0 + udp: true + tcp: true + data_dir: data # relative to the config file → /etc/easydns/data + max_tcp_connections: 1024 + tcp_idle_timeout: 10s + max_udp_payload: 1232 + max_inflight: 10000 # server-wide limit of UDP queries being processed at once + udp_sockets: 0 # UDP sockets per address (SO_REUSEPORT); 0 = one per CPU, max 16 + identity: null # answers id.server/version.bind (CH TXT) only when set +logging: { level: info, format: text|json, query_log: false, anonymize_clients: true } +keys: [ { name, algorithm: hmac-sha256, secret: "env:..." } ] +acls: { name: ["10.0.0.0/8", "acl:other", "any", "none"] } +recursion: + enabled: false + root_hints: null # built-in IANA hints when unset + allowed_clients: ["192.168.0.0/16", "10.0.0.0/8", "127.0.0.1/32", "::1/128"] + qname_minimization: true + dnssec_validation: false + trust_anchors: null # DS/DNSKEY file; built-in root KSKs when unset + max_depth: 30 + max_queries: 100 + max_cname_chain: 8 + query_timeout: 1500ms + total_timeout: 10s + local_only_suffixes: [] + use_ipv6_transport: false +zones: # see primary.md / secondary.md + - name: example.com + type: primary + file: zones/example.com.zone # relative to data_dir + transfer_acl: [] # IPs allowed to AXFR/IXFR + transfer_tsig_key: null # optional key for transfers + notify: [] # secondaries to NOTIFY + notify_tsig_key: null + update_acl: [] # alias allow_update; alone = updates by IP without a key + update_keys: [] # keys that may change the whole zone + update_policy: [] # BIND-style rules: "grant name|subdomain|wildcard|zonesub|self|selfsub [name] [types]" + serial_strategy: increment + journal_size: 100 + views: [] + dnssec: null +forward_zones: [ { domain, upstreams, strategy, clients, fallback_recursion } ] +upstreams: { strategy: failover, servers: [], timeout: 2s, health_check_interval: 30s, tls_ca_file: null } +resolution: { default: refuse|recursive|forward|forwardthenrecursive, views: [ { name, clients } ] } +cache: { enabled: true, max_entries: 100000, min_ttl: 0, max_ttl: 86400, max_negative_ttl: 3600, serve_stale: false, stale_ttl: 30, + answer_entries: 20000, # encoded-answer (packet) cache; 0 = off + answer_max_age: 30s, # max reuse of local-zone answers (zone changes invalidate at once) + prefetch: true } # refresh popular resolver entries before they expire +policy: { blocklists: [ { name, file|url, category, enabled } ], allowlist: [], block_action: nxdomain|refused|null|address, + block_address_v4: 0.0.0.0, block_address_v6: "::", block_ttl: 60, exempt_clients: [], log_blocked: true } +rate_limit: { enabled: true, per_client_qps: 200, burst: 400, global_qps: 0, slip: 2, exempt_clients: [loopback] } # global_qps 0 = no server-wide cap +tls: { cert_file, key_file, dot_listen: [], doh_listen: [], doh_plaintext_behind_proxy: false } # certificate files re-read within 60 s of a change +api: { enabled: true, listen: 127.0.0.1:9953, auth_required: true, local_token: true, tokens: [], allowed_clients: [loopback], requests_per_minute: 600 } +metrics: { enabled: true, listen: 127.0.0.1:9090 } +``` + +Durations accept `500ms`, `2s`, `5m`, `1h`, `1d` or plain seconds. + +### Encoded-answer cache (`cache.answer_entries`) + +Complete responses are kept in encoded form and reused for identical queries: the copy +gets the client's message ID and question spelling, and TTLs of resolved data are +counted down. A hit costs no parsing, no policy evaluation and no zone lookup, and UDP +hits are answered directly in the receive loop (batched with `sendmmsg` on Linux). + +* The key includes everything that can change the answer: the query (flags, EDNS, DO bit, + UDP size) and the client's view, recursion permission, block-list exemption, + client-specific forward rules and transport (UDP/TCP). TSIG-signed queries are never + cached; only NOERROR/NXDOMAIN answers are stored. +* Zone changes (file reload, API, DDNS, re-signing, secondary transfer or expiry), a + configuration reload and `easydns cache clear` invalidate it immediately. +* With `logging.query_log: true` the cache is bypassed, so every query is logged. +* Memory: about 0.3–1 KiB per entry (20 000 entries ≈ 6–20 MB at most). +* Metrics: `dns_answer_cache_hits_total`, `…_misses_total`, `…_inserts_total`, `dns_answer_cache_entries`. + +## Upstream syntax + +`1.1.1.1`, `1.1.1.1:53`, `[2606:4700::1111]:53`, `tcp://1.1.1.1`, +`tls://1.1.1.1#cloudflare-dns.com`, `https://1.1.1.1/dns-query#cloudflare-dns.com` +(`#name` is the TLS certificate name and is mandatory for TLS upstreams). +DoT upstreams use a pool of persistent connections; DoH upstreams use one persistent, +multiplexed HTTP/2 connection (HTTP/1.1 if the server lacks h2). Certificates are checked +against the built-in Mozilla roots plus `upstreams.tls_ca_file`. See +[secure-dns.md](secure-dns.md). + +## Hot reload + +`kill -HUP `, `systemctl reload easydns`, `easydns reload` or `POST /api/v1/config/reload`. +The new configuration is validated and built completely before it is switched in; on any +error the running configuration stays active. Settings that need a restart are reported +(`restart_required`). diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..2aa2801 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,88 @@ +# Deployment + +## After installing the .deb package + +```bash +sudo apt install ./dist/easydns_0.1.0-1_amd64.deb +sudo easydns zone create example.com --ns ns1.example.com=192.0.2.10 --ip 192.0.2.80 +sudo systemctl enable --now easydns +sudo easydns status # no key to generate or pass +easydig @127.0.0.1 example.com SOA +short +``` +The package installs the default hybrid configuration (`/etc/easydns/config.yaml`: +`0.0.0.0:53` + `[::1]:53`, recursion for `192.168.0.0/16`, `10.0.0.0/8`, `127.0.0.1`), +creates `/etc/easydns/{zones.d,keys.d,data/zones}` and the `easydns` user. Layout: +[configuration.md](configuration.md#default-installation-layout). On hosts where +systemd-resolved occupies `127.0.0.53:53` there is no conflict (different address); if +another DNS server listens on `0.0.0.0:53`, stop it or change `server.listen`. + +## Upgrading the package (keeping your configuration) + +```bash +sudo tar czf /root/easydns-backup-$(date +%F).tgz /etc/easydns # config, zones, keys, data +scripts/build-deb.sh # → dist/easydns__.deb +sudo apt install -o Dpkg::Options::=--force-confold ./dist/easydns_*_amd64.deb +``` +* `/etc/easydns/config.yaml` and `root.hints` are conffiles: `--force-confold` keeps your + version without asking; the new default is saved next to it as `config.yaml.dpkg-dist` + (without the option dpkg asks – answer **N** to keep yours). +* Files in `zones.d/`, `keys.d/` and `data/` are never touched by the package. +* A running server is restarted only if the new version accepts the configuration + (`easydns check-config` as the `easydns` user); otherwise the old version keeps + running and the reason is in `/tmp/easydns-upgrade-check.log`. +* Secondary zone copies from older versions (`data/secondary/`) are moved automatically + to `data/zones/secondary/` on the first start, so zones are served immediately. +* After the upgrade: `sudo easydns check-config`, `journalctl -u easydns -n 50`, and + query a few zones (`easydig @127.0.0.1 example.com SOA +short`). + +## systemd (manual installation) + +```bash +sudo useradd --system --home /etc/easydns/data --shell /usr/sbin/nologin easydns +sudo deploy/install.sh /usr # binaries (+ short tool names when free) +sudo install -d -o root -g easydns -m 0750 /etc/easydns /etc/easydns/zones.d /etc/easydns/keys.d +sudo install -d -o easydns -g easydns -m 0750 /etc/easydns/data /etc/easydns/data/zones +sudo install -m 0640 -g easydns config/config.yaml /etc/easydns/config.yaml # or config/primary.yaml, secondary.yaml, … +sudo cp deploy/systemd/easydns.service /etc/systemd/system/ +sudo systemctl daemon-reload && sudo systemctl enable --now easydns +sudo systemctl reload easydns # hot reload (SIGHUP) +``` +Secrets for `env:` references (optional) go to `/etc/easydns/easydns.env` (mode 0640). +Block list updates: `deploy/systemd/easydns-blocklists.{service,timer}`. + +## Docker + +`docker compose up -d` builds `deploy/docker/Dockerfile` (multi-stage, Debian slim, +non-root, `CAP_NET_BIND_SERVICE` only, read-only root). Mount `./config` to `/etc/easydns` +and keep `/etc/easydns/data` on a volume. Multi-arch: +`docker buildx build --platform linux/amd64,linux/arm64 -f deploy/docker/Dockerfile .` + +## Ports + +53/udp+tcp (DNS), 853/tcp (DoT, optional), DoH port as configured (e.g. 443), 9953 API (loopback) and +9090 metrics on loopback by default. Do not expose the API, metrics or recursion to the +Internet without explicit ACLs and TLS (reverse proxy). + +## Packages and archives + +`scripts/build-deb.sh [--arch amd64,arm64] [--debian bookworm] [--revision N] [--test]` builds +`dist/easydns_-_.deb` entirely inside Docker (`deploy/docker/Dockerfile.deb`, +control/maintainer scripts in `deploy/packaging/debian/`); `--test` installs the package in a +clean container and runs a smoke query. The package installs a `easydns` system user, the +systemd units, `/etc/easydns/config.yaml` (conffile), man page, completions, and creates short +tool names only where they are free. + + +`deploy/release.sh` builds x86_64/aarch64 archives with SHA256SUMS; `deploy/packaging/nfpm.yaml` +builds .deb/.rpm (`nfpm pkg -p deb|rpm`). `cargo install --path crates/dns-cli` and +`--path crates/dns-tools` work too. `easydns --version` prints version and commit. + +## Backup / restore / upgrade + +* Back up `/etc/easydns` – one directory holds everything: config, `zones.d/`, + `keys.d/` (secrets!) and `data/` (zone files, snapshots, journals, signed zones, audit log). +* Purging the package never deletes `/etc/easydns` (your zones and keys). +* Restore: put the directories back and start; secondaries re-validate EXPIRE on startup. +* Upgrades are in place; formats are versionless/forward-tolerant (zone files, JSON + lines). Rollback = previous binary + the same directories. A corrupt journal is + truncated automatically (IXFR then falls back to AXFR). diff --git a/docs/dnssec.md b/docs/dnssec.md new file mode 100644 index 0000000..f8dbb1a --- /dev/null +++ b/docs/dnssec.md @@ -0,0 +1,203 @@ +# DNSSEC + +## Step by step: signing your domain and registering it with the registrar + +Example: zone `example.com` served by EasyDNS as primary (`ns1.example.com`) with one +secondary (`ns2.example.net`). The domain is registered through a registrar (the +"operator" whose panel you use to manage name servers); the registry of the TLD +(e.g. `.com`, `.pl`) accepts the DS record only from the registrar. + +### 0. Before you start + +- [ ] Every authoritative server of the domain gets the zone from this EasyDNS primary + (EasyDNS or BIND secondaries transfer the *signed* zone unchanged). A secondary that + is not fed from this primary would serve unsigned data – fix that first. +- [ ] The registrar supports DNSSEC (look for "DNSSEC" / "DS records" in the domain panel, + or ask support). Most panels accept algorithm **13 (ECDSA P-256)**; algorithm 15 + (Ed25519) is accepted by fewer registrars and TLDs – use 13 unless you know 15 works. +- [ ] The server clock is synchronised (NTP): signatures carry validity dates. +- [ ] You can wait: the whole procedure takes about a day because of TTLs. + +### 1. Generate the key + +```bash +sudo easydns dnssec keygen --zone example.com --dir /etc/easydns/data/keys/example.com --algorithm ecdsap256 +# created /etc/easydns/data/keys/example.com/example.com.56013.csk.key (key tag 56013, csk) +# DS for the parent zone: +# example.com. 3600 IN DS 56013 13 2 7170CB4FD554C23F491F62C8DE2D518BFD24EB1766A05D70C5AB2FE5D1A7E6FE +``` +One combined signing key (CSK) is created: simple and fully sufficient for most domains. +The directory is created with mode 0700 and the file with 0600, owned by the `easydns` +user. Keep the keys under `/etc/easydns/data/` – the systemd unit allows the service to +write only there (needed when `auto_generate` creates keys itself). + +**Back up the key directory** (encrypted). Losing the key of a signed domain means an +emergency rollover; a leaked key lets others sign data for your domain. + +### 2. Enable signing for the zone + +`/etc/easydns/zones.d/example.com.yaml`: +```yaml +- name: example.com + type: primary + file: zones/example.com.zone # stays unsigned – keep editing it as before + transfer_acl: ["198.51.100.20"] + notify: ["198.51.100.20:53"] + dnssec: + keys_dir: /etc/easydns/data/keys/example.com + algorithm: ecdsap256 +``` +```bash +sudo easydns check-config && sudo easydns reload +``` +EasyDNS adds DNSKEY, NSEC and RRSIG records, bumps the serial, stores the signed copy in +`/etc/easydns/data/signed/` and sends NOTIFY, so the secondaries transfer the signed zone. +(If the key directory is empty, `auto_generate: true` creates the key at this point – +step 1 is then optional; get the DS with step 4.) + +### 3. Check the signed zone on every name server + +```bash +easydig @ns1.example.com example.com DNSKEY +dnssec +short # 257 3 13 … + RRSIG DNSKEY … +easydig @ns1.example.com www.example.com A +dnssec # answer + RRSIG +easydig @ns1.example.com nothing.example.com A +dnssec # NXDOMAIN + NSEC + RRSIG +ediff example.com DNSKEY @ns1.example.com @ns2.example.net # same keys everywhere +ediff example.com SOA @ns1.example.com @ns2.example.net # same serial everywhere +``` +Do not go on until **all** name servers return the DNSKEY and signatures. Until the DS +exists at the parent, resolvers treat the domain as unsigned (*insecure*), so nothing +can break yet. + +### 4. Get the DS (or DNSKEY) for the registrar + +```bash +sudo easydns dnssec ds --zone example.com --dir /etc/easydns/data/keys/example.com +# example.com. 3600 IN DNSKEY 257 3 13 ZsxUqxgMi2LA…EMTVLw== +# example.com. 3600 IN DS 56013 13 2 7170CB4FD554C23F491F62C8DE2D518BFD24EB1766A05D70C5AB2FE5D1A7E6FE +``` + +| Registrar form field | Value from the DS line | +|---|---| +| Key tag | `56013` | +| Algorithm | `13` (ECDSAP256SHA256) – `15` for Ed25519, `14` for ECDSA P-384 | +| Digest type | `2` (SHA-256) | +| Digest | `7170CB4F…E6FE` (64 hex characters, without spaces) | + +Some panels ask for the **DNSKEY** instead: flags `257`, protocol `3`, algorithm `13`, +public key = the base64 string from the DNSKEY line. + +### 5. Submit it at the registrar + +In the registrar's panel: domain → DNSSEC (sometimes "Security" or "DS records") → add a +DS record with the four values above → save. Some registrars do it through a support +ticket – send them the DS line. The registry usually publishes it within minutes to a few +hours. + +EasyDNS does not publish CDS/CDNSKEY records, so automatic DS updates by the registry +(RFC 8078) are not available – DS changes always go through the registrar. + +### 6. Verify the chain of trust from the outside + +```bash +easydig @1.1.1.1 example.com DS +short # the DS you submitted (via a public resolver) +ednssec example.com SOA # walks root → TLD → example.com: should end "secure" +easydig @1.1.1.1 www.example.com A +dnssec # flags must contain "ad" +easydig @9.9.9.9 www.example.com A # validating resolver: NOERROR, not SERVFAIL +``` +A graphical check: https://dnsviz.net/ (enter the domain). If validating resolvers +return **SERVFAIL**, the DS does not match the published key: compare +`easydns dnssec ds …` with `easydig DS example.com +short`, fix the DS at the registrar, +and in an emergency remove the DS there (the domain then becomes *insecure*, i.e. works +unsigned). + +### 7. Running a signed zone + +* Edit the zone file, raise the serial and `easydns reload` as before; API and RFC 2136 + changes work too – every change is re-signed automatically. +* Signatures are valid for 14 days (`signature_validity`) and renewed when they would + expire within 7 days (`resign_before`, checked hourly). +* **Keep the primary running.** Secondaries serve the signatures they received; if the + primary is down for longer than the remaining validity (7–14 days), the signatures on + the secondaries expire and validating resolvers return SERVFAIL. Monitor that the + primary is up (`easydns status`, `dns_zone_serial` – the serial grows with every + re-signing) and watch the log for signing errors. +* Check from time to time: `ednssec example.com SOA`, or dnsviz. + +### 8. Key rollover (e.g. once a year, or immediately if the key leaked) + +1. `easydns dnssec keygen --zone example.com --dir /etc/easydns/data/keys/example.com --algorithm ecdsap256` + (a second key file appears), `easydns reload` – both keys are published and sign. +2. Wait for the DNSKEY TTL (default 3600 s) so resolvers know the new key. +3. `easydns dnssec ds …` now prints two DS lines: **add** the new DS at the registrar, + keep the old one. +4. Wait until the new DS is visible (`easydig @1.1.1.1 example.com DS`) plus the parent's + DS TTL (the TTL shown in that answer; often 1 hour to 1 day). +5. Remove the **old** DS at the registrar; wait the DS TTL again. +6. Delete the old key file from the key directory, `easydns reload`. + +Changing the algorithm (e.g. 15 → 13) works the same way, with the new key generated with +the new `--algorithm` and `dnssec.algorithm` changed in step 1. + +### 9. Turning DNSSEC off safely + +Order matters – the other way round makes the domain fail for validating resolvers: +1. Remove **all** DS records at the registrar. +2. Wait until the DS is gone from the parent (`easydig @1.1.1.1 example.com DS +short` + returns nothing) **and** its TTL has passed. +3. Remove the `dnssec:` block from the zone definition, `easydns reload`. + +### Moving a signed domain from BIND + +BIND's private keys cannot be imported. Generate a new key in EasyDNS and use the +rollover above with BIND still signing (add the new DS, switch the name servers or the +primary, remove the old DS) – see [migration-from-bind.md](migration-from-bind.md#5-dnssec-signed-zones). + +--- + +## Reference: signing primary zones + +```yaml +zones: + - name: example.com + type: primary + file: zones/example.com.zone # stays unsigned + dnssec: + keys_dir: /etc/easydns/data/keys/example.com + algorithm: ed25519 # ed25519 | ecdsap256 | ecdsap384 (13 = ecdsap256 is the most widely accepted by registrars) + auto_generate: true # create a CSK if the directory is empty + signature_validity: 14d + resign_before: 7d +``` + +* Keys: `easydns dnssec keygen --zone example.com --dir /etc/easydns/data/keys/example.com [--role ksk|zsk|csk]`; + `easydns dnssec ds --zone example.com --dir ...` prints the DNSKEY and the DS to submit to the parent. +* The signer adds DNSKEY, an NSEC chain (authoritative names and delegation points, no glue) + and RRSIGs (KSK/CSK sign DNSKEY; ZSK/CSK sign everything else; delegation NS and glue are + not signed; DS is). With DO=1 the server returns RRSIGs and NSEC proofs for NXDOMAIN, + NODATA, wildcard expansions and unsigned delegations. +* Every change (file reload, API, DDNS) re-signs and bumps the serial; an hourly task + re-signs when signatures expire within `resign_before`. The signed zone is persisted in + `/signed/` so a restart does not produce new signatures under the same serial. +* Rollover: add the new key file, reload (both keys published and used), wait DNSKEY TTL + (+ parent DS TTL for KSKs, after updating the DS), remove the old key file, reload. +* Secondaries simply transfer the signed zone (signing on secondaries is rejected). + +## Reference: validation + +```yaml +recursion: { enabled: true, dnssec_validation: true, trust_anchors: null } # null = IANA root KSK-2017 + KSK-2024 +``` + +* Chain of trust from the anchors: DNSKEY(anchor) verified against the anchor → + DS(child) verified with the parent's keys → DNSKEY(child) matching a DS and self-signed → + RRSIG over every answer RRset (inception/expiration, signer must enclose the owner). +* Missing DS proven by signed NSEC/NSEC3 (incl. opt-out) → **insecure** (answer without AD). +* Negative answers need a signed SOA and an NSEC/NSEC3 proof (NXDOMAIN: covering NSEC + + wildcard denial; NSEC3: closest-encloser proof) → **secure**. +* Wildcard answers need a proof that no closer name exists. +* Anything that fails → **bogus** → SERVFAIL; with CD=1 the data is returned without AD. + Reasons are logged (`DNSSEC validation failed (bogus)`) and counted (`dns_dnssec_bogus_total`). +* Unsupported algorithms (e.g. Ed448) or NSEC3 iterations > 150 (RFC 9276) → insecure. +* Responses to clients set AD only for secure data and only when the client sent DO or AD. + +Diagnostics: `ednssec example.com A` shows each zone cut's state, key tags and the result. diff --git a/docs/forwarder.md b/docs/forwarder.md new file mode 100644 index 0000000..270efe2 --- /dev/null +++ b/docs/forwarder.md @@ -0,0 +1,30 @@ +# Forwarder + +```yaml +upstreams: + strategy: fastest # round-robin | fastest | failover | random | priority + timeout: 2s + health_check_interval: 30s + servers: ["tls://1.1.1.1#cloudflare-dns.com", "https://9.9.9.9/dns-query#dns.quad9.net", "192.168.1.1"] +forward_zones: + - domain: corp.internal + upstreams: ["10.0.0.53", "10.0.0.54"] + strategy: failover + clients: ["10.0.0.0/8"] # optional: rule applies only to these clients + fallback_recursion: false # true: recurse when all upstreams fail +resolution: { default: forward } # or forwardthenrecursive +``` + +* Up to three upstreams are tried per query in strategy order; SERVFAIL/REFUSED/NOTIMP/ + FORMERR/timeouts count as failures. +* **Circuit breaker:** 3 consecutive failures open the circuit for 30 s, doubling up to 5 min; + open upstreams are tried last; successful health checks close the circuit. +* `fastest` uses an EWMA of the RTT with occasional exploration of the runner-up. +* Logs and `easydns upstreams list` / `GET /api/v1/upstreams` show RTT, failures, circuit state + and the reason an upstream was chosen. +* Forwarded answers are cached in a namespace per rule; private forward zones are never + sent to public upstreams or the root. +* Identical concurrent questions are sent upstream once (query coalescing). +* **Encrypted upstreams** (`tls://…#name`, `https://…#name`) keep their connections open: + a DoT connection pool and a multiplexed HTTP/2 connection for DoH. Private CAs: + `upstreams.tls_ca_file`. Full guide: [secure-dns.md](secure-dns.md). diff --git a/docs/hybrid.md b/docs/hybrid.md new file mode 100644 index 0000000..7b05aa5 --- /dev/null +++ b/docs/hybrid.md @@ -0,0 +1,40 @@ +# Hybrid + +One process can be Primary for some zones, Secondary for others, forward private domains +and recurse for everything else: + +```yaml +recursion: { enabled: true, allowed_clients: ["acl:lan"] } +zones: + - { name: example.com, type: primary, file: zones/example.com.zone } + - { name: example.net, type: secondary, primaries: ["192.0.2.10:53"] } +forward_zones: + - { domain: corp.internal, upstreams: ["10.0.0.53"] } +resolution: + default: recursive + views: + - { name: lan, clients: ["10.0.0.0/8"] } + - { name: world, clients: [any] } +``` + +## Precedence (tested in `crates/dns-server/tests/resolver.rs`) + +1. **Local authoritative zones** – the most specific zone visible in the client's view wins + (`example.com` beats a forward rule for `com`); NXDOMAIN inside a local zone is final and + the name is never sent upstream. +2. **Recursion permission** – clients outside `recursion.allowed_clients` get REFUSED. +3. **Local-only names** (`localhost`, `local`, `test`, `invalid`, `home.arpa`, `onion`, + RFC 1918/6303 reverse zones, plus `recursion.local_only_suffixes`) → NXDOMAIN locally. + A forward rule for such a name takes precedence (e.g. forwarding `home.arpa` to a router). +4. **Allow/block policy.** +5. **Conditional forwarding** – longest matching suffix (and client ACL). +6. **Default resolution.** + +Data spaces are separate: authoritative zones are never cached; each forwarding rule and +the recursive resolver use their own cache namespace. + +## Views (split horizon) + +`zones[].views: [lan]` makes a zone visible only to clients of that view; the same zone +name can be defined twice with different files for different views. Views are matched in +order; the first match wins. diff --git a/docs/migration-from-bind.md b/docs/migration-from-bind.md new file mode 100644 index 0000000..6d3f188 --- /dev/null +++ b/docs/migration-from-bind.md @@ -0,0 +1,196 @@ +# Migrating from BIND 9 + +This guide covers the common BIND deployments. In every case the safe pattern is the +same: **run EasyDNS next to BIND, compare answers, switch traffic, keep BIND ready for +rollback.** Commands use the long tool names; short names (`ed`, `ediff`, …) work too. + +## 0. Inventory and translation table + +```bash +named-checkconf -p > /tmp/named.full.conf # flattened BIND config (all includes) +rndc zonestatus example.com # type, serial, files, signing +``` + +| BIND (`named.conf`) | EasyDNS (`config.yaml`) | +|---|---| +| `listen-on port 53 { 192.0.2.1; };` / `listen-on-v6` | `server.listen: ["192.0.2.1:53", "[2001:db8::1]:53"]` | +| `directory "/var/named";` | `server.data_dir` (default install: `/etc/easydns/data`); zone `file:` paths are relative to it (`zones/example.com.zone`) | +| `key "xfr" { algorithm hmac-sha256; secret "…"; };` | copy the BIND key file unchanged to `/etc/easydns/keys.d/` (included by default), or `keys: [ { name: xfr, secret: "file:…" } ]` | +| `acl lan { 10.0.0.0/8; };` | `acls: { lan: ["10.0.0.0/8"] }`, referenced as `acl:lan` | +| `zone "x" { type master; file "…"; };` | `zones: [ { name: x, type: primary, file: … } ]` | +| `allow-transfer { 192.0.2.20; };` | `transfer_acl: ["192.0.2.20/32"]` | +| `allow-transfer { 192.0.2.20; key xfr; };` | `transfer_acl: ["192.0.2.20/32"]` + optional `transfer_tsig_key: xfr` (both must match when the key is set) | +| `also-notify { 192.0.2.20; };` / `notify yes;` | `notify: ["192.0.2.20:53"]` (+ optional `notify_tsig_key: xfr`) | +| `zone "x" { type slave; masters { 192.0.2.10; }; };` | `type: secondary`, `primaries: ["192.0.2.10:53"]` (+ optional `transfer: { tsig_key: xfr }` for `masters { … key xfr; }`) | +| `allow-notify { … };` | `allow_notify: [...]` (default: the primaries' addresses) | +| `allow-update { 192.0.2.7; };` | `update_acl: ["192.0.2.7"]` (alias `allow_update`) – updates without a key | +| `allow-update { key ddns; };` | `update_keys: [ddns]`, optional `update_acl` | +| `update-policy { grant k name x. TXT; … };` | `update_policy: ["grant k name x. TXT", …]` – same syntax | +| `recursion yes; allow-recursion { lan; };` | `recursion: { enabled: true, allowed_clients: ["acl:lan"] }` + `resolution: { default: recursive }` | +| `forwarders { 1.1.1.1; }; forward only;` | `upstreams: { servers: ["1.1.1.1"] }` + `resolution: { default: forward }` | +| `forward first;` | `resolution: { default: forwardthenrecursive }` | +| `zone "corp" { type forward; forwarders { 10.0.0.53; }; };` | `forward_zones: [ { domain: corp, upstreams: ["10.0.0.53"] } ]` | +| `dnssec-validation auto;` | `recursion.dnssec_validation: true` (built-in IANA root anchors) | +| `trust-anchors { … initial-ds …; };` | `recursion.trust_anchors: file` with DS/DNSKEY records (static; no RFC 5011) | +| `view "lan" { match-clients { lan; }; zone … };` | `resolution.views: [ { name: lan, clients: ["acl:lan"] } ]` + `zones[].views: [lan]` | +| `response-policy { zone "rpz"; };` | `policy.blocklists` (convert the RPZ, see below) | +| `rate-limit { responses-per-second 10; };` | `rate_limit` (per client, not per response) | +| `statistics-channels` | `metrics.listen` (Prometheus) + `GET /api/v1/stats` | +| `controls` / `rndc` | REST API on loopback + `easydns` (table below) | +| `version "none";` | default: `version.bind` is REFUSED unless `server.identity` is set | + +| rndc / BIND tool | EasyDNS | +|---|---| +| `rndc reload` / `rndc reconfig` | `easydns reload` or `systemctl reload easydns` (SIGHUP) | +| `rndc reload zone` | `easydns reload` (only changed zones are re-published) | +| `rndc retransfer zone` / `rndc refresh zone` | `easydns zones sync zone` | +| `rndc notify zone` | `easydns zones notify zone` | +| `rndc flush` / `rndc flushname x` | `easydns cache clear` / `easydns cache clear --domain x` | +| `rndc status`, `rndc zonestatus` | `easydns status`, `easydns zones show zone` | +| `named-checkconf` / `named-checkzone` | `econf check` / `ezone check FILE --origin ZONE` | +| `dig`, `host`, `nslookup`, `delv`, `dig +trace` | `easydig`, `easyhost`, `easynslookup`, `easydnssec`, `easytrace` | +| `dnssec-keygen` / `dnssec-dsfromkey` | `easydns dnssec keygen` / `easydns dnssec ds` | + +### Zone file compatibility + +BIND zone files are read as they are ($ORIGIN, $TTL, $INCLUDE, parentheses, comments, +relative names, all common types, DNSSEC types and RFC 3597 `\#` syntax). Check every +file first: + +```bash +for f in /var/named/*.zone; do easyzone check "$f" --origin "$(basename "$f" .zone)"; done +``` + +Not supported: **`$GENERATE`** (expand it first, e.g. with `named-compilezone -o - zone file`, +which writes a fully expanded zone), **DNAME** records, and DNSSEC/RFC 3597 records inside +`$INCLUDE`d files (move them into the main file). Files without `$TTL` get 3600 s for records +without an explicit TTL (BIND uses the SOA MINIMUM and warns) – add `$TTL` to be explicit. +Zones changed through the EasyDNS API/DDNS are rewritten in canonical form (comments are lost). + +## 1. Authoritative primary (hidden or public master) + +1. Copy zone files and TSIG secrets; translate the zone statements (table above). +2. Validate: `easyconf check /etc/easydns/config.yaml`. +3. Start EasyDNS on a test port (e.g. `--listen 127.0.0.1:5300`) on the BIND host or a new host. +4. Compare every zone with BIND (order-insensitive, TTLs reported separately): + ```bash + for z in example.com example.net; do + easydig @127.0.0.1 -p 53 $z AXFR -y hmac-sha256:xfr:$SECRET --json > /tmp/bind.$z.json + easydig @127.0.0.1 -p 5300 $z AXFR -y hmac-sha256:xfr:$SECRET --json > /tmp/easy.$z.json + done + easydiff www.example.com A @127.0.0.1:53 @127.0.0.1:5300 + ``` +5. Cut over: stop BIND, start EasyDNS on port 53 (same IPs → secondaries and the registry + need no change). Make sure the **SOA serial does not go backwards** – keep the files' + serials or raise them. +6. Secondaries (BIND or others) keep working: EasyDNS answers SOA/IXFR/AXFR with TSIG and + sends NOTIFY to `notify:` targets. Watch `easydns zones transfers ZONE`. +7. Rollback: stop EasyDNS, start BIND (zone files changed via the EasyDNS API stay valid + BIND files, with a higher serial). + +## 2. Secondary servers + +**Replace a BIND secondary** (primary unchanged, possibly BIND): + +1. Configure the zone as `type: secondary` with the same primaries and TSIG key; add the + new host to the primary's `allow-transfer`/`also-notify` if the IP changes. +2. Start EasyDNS; it performs AXFR, then IXFR on NOTIFY or SOA REFRESH. Check + `easydns zones show ZONE` (serial, source, `last_error`) and compare with + `easydiff ZONE SOA @old-secondary @new-secondary`. +3. Swap the service IP or update NS/glue at the registry; decommission BIND after the + old NS TTL has expired. + +**Mixed operation** is supported both ways: EasyDNS secondary of a BIND primary, and BIND +secondary of an EasyDNS primary (standard AXFR/IXFR/NOTIFY/TSIG). Useful as a migration +stage: make EasyDNS a secondary first, then promote it (next section). + +**Promote an EasyDNS secondary to primary:** copy the snapshot +`/secondary/ZONE.zone` to a zone file, change the zone to `type: primary` with +`file:` pointing to it, reload. The serial continues from the transferred one. + +## 3. Recursive resolver (caching resolver for a LAN) + +1. `recursion.enabled: true`, `allowed_clients` = BIND `allow-recursion` + (`allow-query-cache` is implied), `resolution.default: recursive`, + `dnssec_validation: true` if BIND had `dnssec-validation auto`. +2. Local/private zones that BIND served as `type master` stay `type: primary`; BIND + `empty-zones-enable` behaviour corresponds to EasyDNS local-only names (RFC 6303), + extend with `recursion.local_only_suffixes`. +3. Compare with the old resolver for a sample of names (e.g. from BIND query logs): + ```bash + while read n t; do easydiff "$n" "$t" @old-resolver @127.0.0.1:5300 >/dev/null || echo "DIFF $n $t"; done < sample.txt + ``` + Differences in address order or TTLs are normal; RCODE/record set differences are not. +4. Load test the new resolver with traffic you own: `easybench @127.0.0.1:5300 -d sample.txt --qps 500`. +5. Switch DHCP/resolv.conf or move the service IP. The cache starts cold (no cache import). + +## 4. Forwarder + +`forwarders` + `forward only|first` and `type forward` zones map 1:1 (table above). +EasyDNS adds strategies (`failover` ≈ BIND order, `fastest` ≈ BIND RTT selection), +health checks and encrypted upstreams (`tls://ip#name`, `https://ip/dns-query#name`). + +## 5. DNSSEC-signed zones + +BIND private keys (`K*.private`) cannot be imported. Options: + +* **A. Keep signing outside EasyDNS** (BIND as hidden signer, or offline + `dnssec-signzone`): EasyDNS is a secondary of the signer, or serves the pre-signed file + as a `primary` **without** `dnssec:` (RRSIG/NSEC/NSEC3/DNSKEY are loaded from the file). + Re-signing remains the signer's job. No DS change needed. +* **B. Move signing to EasyDNS** (online signing, NSEC) with a DS rollover: + 1. `easydns dnssec keygen --zone Z --dir /etc/easydns/data/keys/Z --algorithm ecdsap256`; + 2. publish the new DNSKEY in the BIND-signed zone (pre-publish, `dnssec-settime`/`rndc`) + and wait the DNSKEY TTL; + 3. add the new DS (`easydns dnssec ds`) at the parent next to the old DS, wait the DS TTL; + 4. switch serving to EasyDNS with `dnssec:` enabled (it signs with its key only), and + verify with `easydnssec www.Z`; + 5. after the DNSKEY TTL, remove the old DS at the parent. + A zone using NSEC3 in BIND will use NSEC after the switch (NSEC3 signing is not available). +* **C. Unsign and re-sign** (simplest, short insecure window): remove the DS at the + parent, wait the DS TTL, switch to EasyDNS signing, publish the new DS. + +## 6. Views / split horizon + +Each BIND `view` becomes a `resolution.views` entry (same order; first match wins) and +each zone inside a view gets `views: [name]`; the same zone name may be defined once per +view with different files. Recursion and forwarding settings are global in EasyDNS: if +BIND views differed in `recursion`/`forwarders`, use `recursion.allowed_clients` and +`forward_zones[].clients` to reproduce the difference. + +## 7. Dynamic DNS (DHCP, ACME, nsupdate) + +* `allow-update { 192.0.2.7; };` → `update_acl: ["192.0.2.7"]` (no key). +* `allow-update { key k; };` → `update_keys: [k]` (+ `update_acl`). +* `update-policy { … };` → `update_policy:` with the rules copied as strings (rule types + `name`, `subdomain`, `wildcard`, `zonesub`, `self`, `selfsub`; Kerberos identities are not + supported). +* Keys: copy `keys.conf` from BIND into `/etc/easydns/keys.d/` unchanged. + +`nsupdate`, DHCP servers and ACME clients (certbot `dns-rfc2136`, acme.sh, lego) work +unchanged. A complete translated example is in [primary.md](primary.md#example-translating-a-bind-master-zone). +Every update is in `/audit.log`. + +## 8. RPZ (response policy zones) + +RPZ is not implemented. Convert the policy zone to a block list: every +`name CNAME .` (NXDOMAIN) or `name CNAME *.` (NODATA) entry becomes a line `name`, and +`*.name` lines become `*.name`. Set `policy.block_action` (`nxdomain`, `refused`, `null`, +`address`). Example conversion: + +```bash +easyzone canonical rpz.zone --origin rpz | awk '$4=="CNAME" {n=$1; sub(/\.rpz\.$/,"",n); print n}' > /etc/easydns/blocklists/rpz.txt +``` + +Feeds (`url:`) are refreshed by `easydns blocklists update` (systemd timer in `deploy/systemd`). + +## 9. Final checklist + +- [ ] `easyconf check` clean, every zone passes `easyzone check` +- [ ] `easydiff`/AXFR comparison done for every zone +- [ ] transfers and NOTIFY verified with every secondary (`easydns zones transfers`) +- [ ] DNSSEC: `easydnssec` → *secure* for signed zones, DS at the parent matches +- [ ] recursion not open (`easydig @PUBLIC_IP example.org` from outside → REFUSED) +- [ ] API and metrics only on loopback / behind a firewall +- [ ] monitoring (`/metrics`), log shipping, backups of `/etc/easydns` and `/etc/easydns/data` +- [ ] rollback plan: BIND config and files untouched and startable diff --git a/docs/monitoring.md b/docs/monitoring.md new file mode 100644 index 0000000..23d1bd1 --- /dev/null +++ b/docs/monitoring.md @@ -0,0 +1,35 @@ +# Monitoring and logs + +## Metrics (`metrics.listen`, default 127.0.0.1:9090, path `/metrics`) + +| Metric | Labels | +|---|---| +| `dns_queries_total` | transport (udp, tcp, dot, doh) | +| `dns_queries_by_type_total` | qtype (A, AAAA, …, OTHER) | +| `dns_responses_total` | rcode (NOERROR, NXDOMAIN, SERVFAIL, …) | +| `dns_answers_by_source_total` | source (authoritative, cache, recursive, forward, blocked, local, refused) | +| `dns_query_duration_seconds` | histogram | +| `dns_upstream_latency_seconds`, `dns_upstream_errors_total` | | +| `dns_cache_hits_total`, `dns_cache_misses_total`, `dns_cache_evictions_total`, `dns_cache_entries` | | +| `dns_blocked_total`, `dns_rate_limited_total`, `dns_malformed_total` | | +| `dns_xfr_out_total`, `dns_xfr_out_refused_total`, `dns_notify_received_total`, `dns_notify_refused_total` | | +| `dns_updates_total`, `dns_updates_refused_total`, `dns_tsig_failures_total` | | +| `dns_dnssec_secure_total`, `dns_dnssec_insecure_total`, `dns_dnssec_bogus_total` | | +| `dns_zone_serial`, `dns_zone_expired`, `dns_zone_last_sync_timestamp_seconds` | zone (bounded by configured zones) | +| `dns_tcp_connections`, `dns_inflight_queries`, `process_resident_memory_bytes`, `process_start_time_seconds` | | + +No label ever contains a queried name or a client address. A Grafana dashboard is in +`deploy/grafana/easydns.json`. + +## Logs + +`tracing` with `logging.level` (error, warn, info, debug, trace or a filter such as +`info,query=info`), text or JSON (`logging.format: json`) on stderr. Optional query log +(`logging.query_log: true`): client (anonymised by default), name, type, RCODE, source, +transport, latency and a note (upstream used, block reason). Audit entries use target +`audit`, policy decisions target `policy`. + +## Health + +`/healthz` (metrics and API listeners), `/readyz` (API: all primary zones loaded), +`/api/v1/health` (`degraded` when a secondary zone is expired). diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..19b7345 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,205 @@ +# Operating EasyDNS: master (primary) and name resolution + +Example names only (`example.com`, `example.net`, documentation IP ranges). + +--- + +## Part 1 – Running as master (primary) + +### 1.1 Minimal public master + +```yaml +# /etc/easydns/config.yaml +include: ["zones.d/*.yaml"] +server: + mode: primary + listen: ["0.0.0.0:53", "[::]:53"] + data_dir: /etc/easydns/data +recursion: { enabled: false } +resolution: { default: refuse } # authoritative only: foreign names → REFUSED +rate_limit: { enabled: true, per_client_qps: 100, burst: 200, slip: 2 } +api: { listen: "127.0.0.1:9953" } # the CLI uses the local control token automatically +``` +```yaml +# /etc/easydns/zones.d/example.com.yaml +- name: example.com + type: primary + file: zones/example.com.zone # = /etc/easydns/data/zones/example.com.zone + transfer_acl: ["198.51.100.20/32"] # IP only; a TSIG key is optional + notify: ["198.51.100.20:53"] + serial_strategy: date # YYYYMMDDnn for API/DDNS changes +``` +``` +; /etc/easydns/data/zones/example.com.zone +$TTL 3600 +@ IN SOA ns1.example.com. hostmaster.example.com. ( + 2026112101 ; serial + 3600 ; refresh – how often secondaries check (without NOTIFY) + 600 ; retry – after a failed check + 1209600 ; expire – secondaries stop answering after 14 days without contact + 300 ) ; negative TTL (NXDOMAIN/NODATA caching) + IN NS ns1.example.com. + IN NS ns2.example.com. ; the secondary + IN MX 10 mail +ns1 IN A 192.0.2.10 +ns2 IN A 198.51.100.20 +www IN A 192.0.2.80 +``` +The zone file and definition above can be generated with +`easydns zone create example.com --ns ns1.example.com=192.0.2.10 --ns ns2.example.com=198.51.100.20 --allow-transfer 198.51.100.20 --notify 198.51.100.20`. +Validate and start: `easydns check-config` (also parses every zone), `systemctl enable --now easydns`. + +### 1.2 Three ways to change a zone + +| Way | When | What happens | +|---|---|---| +| **Edit the file** + raise the serial + `easydns reload` | manual administration, Git-managed zones | the file is re-read; if the content changed and the serial is newer, the new version is published atomically, the diff goes to the IXFR journal and NOTIFY is sent. A changed file with an old serial is **rejected** (old version stays). | +| **REST API** (`POST/PUT/DELETE /api/v1/zones/{zone}/records`) | automation, panels, CI | serial bumped by `serial_strategy`, zone validated, file rewritten atomically (canonical form, comments lost), journal + NOTIFY. `If-Match` protects against concurrent edits. | +| **Dynamic update** (RFC 2136, `nsupdate`, DHCP, ACME clients) | machines updating their own records | by source IP (`update_acl`), by key (`update_keys`) or per record (`update_policy`, BIND syntax) – see [primary.md](primary.md#dynamic-updates-rfc-2136); prerequisites supported; audited. | + +Do not mix manual file edits with API/DDNS on the same zone without care: after an API +change the file on disk is the canonical version – edit that, not an old copy. + +```bash +nsupdate -y hmac-sha256:ddns-key:$(cat ddns.secret) <<'EOF2' +server 192.0.2.10 +zone example.com +update delete host1.example.com A +update add host1.example.com 300 A 192.0.2.55 +send +EOF2 +``` + +### 1.3 Adding and removing zones + +* **Files:** drop `zones.d/.yaml` + the zone file, `easydns reload`. Remove = delete the + file + reload (the zone stops being served immediately; remember to remove it from secondaries). +* **API:** `POST /api/v1/zones` (stored in `/api-overlay.yaml`), `DELETE` removes only API-created zones. + +### 1.4 What clients receive + +* answers from the zone with the **AA** flag; NXDOMAIN/NODATA with the SOA (negative TTL = + min(SOA TTL, SOA minimum)); +* wildcards (`*.apps IN A …`) expand for names that do not exist; empty non-terminals give NODATA; +* delegations (`sub IN NS …`) give referrals (no AA) with glue; +* MX/NS/SRV targets inside the zone are added to the additional section; +* with DNSSEC signing (`dnssec:` in the zone) and the DO bit: RRSIGs and NSEC proofs. + +### 1.5 Secondaries, NOTIFY and IXFR + +After every published change the primary sends NOTIFY (3 attempts with back-off) to +`notify:` targets. Secondaries ask for IXFR from their serial; the journal (`journal_size`, +default 100 versions) answers incrementally, older serials get the whole zone. Watch: +`easydns zones transfers example.com`, metric `dns_xfr_out_total`, `dns_xfr_out_refused_total`. +All authentication variants: [zone-transfer-variants.md](zone-transfer-variants.md). + +### 1.6 Daily operations + +| Task | Command | +|---|---| +| status of all zones | `easydns zones list` / `easydns status` | +| details (serial, last change, errors) | `easydns zones show example.com` | +| force NOTIFY | `easydns zones notify example.com` | +| check a zone before reloading | `easyzone check /etc/easydns/data/zones/example.com.zone -o example.com` | +| compare primary with secondaries | `easydiff example.com SOA @192.0.2.10 @198.51.100.20` | +| DS for the registrar (signed zone) | `easydns dnssec ds --zone example.com --dir /etc/easydns/data/keys/example.com` | +| audit of changes | `GET /api/v1/audit` or `/audit.log` | + +--- + +## Part 2 – Name resolution (resolver) + +### 2.1 How EasyDNS answers a query + +For each query the server walks this decision list (first match wins): + +1. **Local zone** (primary or secondary, most specific, visible in the client's view) → + authoritative answer. Names under a local zone are never looked up elsewhere. +2. Client **not allowed** to use resolution (`recursion.allowed_clients`) → REFUSED. +3. **Local-only names** (`localhost`, `local`, `test`, `invalid`, `home.arpa`, private + reverse zones, `recursion.local_only_suffixes`) → NXDOMAIN, nothing leaves the host. +4. **Block/allow lists** → NXDOMAIN / REFUSED / 0.0.0.0 according to `policy.block_action`. +5. **Conditional forwarding** (`forward_zones`, longest suffix) → the configured upstreams. +6. **Default:** `recursive` (iterative from the root), `forward` (upstreams), + `forwardthenrecursive`, or `refuse`. + +### 2.2 Iterative resolution step by step + +Query `www.example.com A` with an empty cache: +``` +client ──► EasyDNS + ├─► root server (from root hints) "com" ? → referral to com NS + glue + ├─► com server "example.com" ? → referral to example.com NS + └─► example.com server "www.example.com A" → answer (AA) +client ◄── answer (RA=1, AA=0), cached for its TTL +``` +* With **QNAME minimisation** the root only learns `com`, the TLD only `example.com`. +* Every response is checked: only records inside the zone of the server that sent them are + accepted (bailiwick), glue only for names inside the delegating zone, IDs/ports random. +* Glueless delegations (NS names in another zone) are resolved first; CNAMEs are followed + across zones (max `max_cname_chain`). +* Limits per query: `max_queries` upstream queries, `max_depth` referrals, `total_timeout`. +* With `dnssec_validation: true` every answer is validated from the root trust anchor: + secure → AD flag for clients that ask (DO/AD), insecure → plain answer, bogus → SERVFAIL + (unless the client sets CD). +* The second identical query is answered from cache (`dns_cache_hits_total`); delegations + are cached too, so `mail.example.com` goes straight to the example.com servers. + +Watch it live: `easytrace www.example.com` (each referral with timing) or +`easydnssec www.example.com` (chain of trust). + +### 2.3 Typical resolver setups + +**LAN resolver (recursive, validating):** +```yaml +server: { mode: recursive, listen: ["192.168.1.2:53", "127.0.0.1:53"] } +recursion: + enabled: true + allowed_clients: ["127.0.0.0/8", "192.168.0.0/16"] + dnssec_validation: true +resolution: { default: recursive } +cache: { max_entries: 200000 } +``` + +**Resolver + local zones + private company domain (hybrid):** +```yaml +include: ["zones.d/*.yaml"] # e.g. home.example.com as primary +recursion: { enabled: true, allowed_clients: ["acl:lan"], dnssec_validation: true } +acls: { lan: ["192.168.0.0/16", "10.8.0.0/24"] } +forward_zones: + - { domain: corp.example.net, upstreams: ["10.0.0.53", "10.0.0.54"], strategy: failover } +resolution: { default: recursive } +policy: { blocklists: [ { name: ads, url: "https://lists.example/ads.txt" } ] } +``` + +**Forwarder to encrypted upstreams (no own recursion):** +```yaml +upstreams: + strategy: fastest + servers: ["tls://1.1.1.1#cloudflare-dns.com", "tls://9.9.9.9#dns.quad9.net"] +resolution: { default: forward } +``` + +**Forward first, recurse if upstreams fail:** `resolution: { default: forwardthenrecursive }`. + +### 2.4 Answers clients can expect + +| Situation | RCODE / flags | +|---|---| +| name resolved | NOERROR, RA=1, AA=0 (AD=1 if validated and requested) | +| name in a local zone | NOERROR/NXDOMAIN with AA=1 | +| name does not exist | NXDOMAIN + SOA (cached for the negative TTL) | +| type does not exist | NOERROR, empty answer + SOA | +| client not allowed | REFUSED, RA=0 | +| blocked name | per `block_action` (default NXDOMAIN) | +| upstream/authority unreachable, DNSSEC bogus | SERVFAIL (cached 5 s; stale data if `serve_stale`) | + +### 2.5 Troubleshooting resolution + +```bash +easydig @127.0.0.1 www.example.com +dnssec # what the resolver returns, with AD/RRSIG +easytrace www.example.com # where the delegation chain breaks +easydnssec www.example.com # which link of the chain of trust fails +easydiff www.example.com A @127.0.0.1 @9.9.9.9 # compare with a public resolver +easydns cache clear --domain example.com # drop cached data for one domain +``` diff --git a/docs/performance.md b/docs/performance.md new file mode 100644 index 0000000..5e9e72d --- /dev/null +++ b/docs/performance.md @@ -0,0 +1,175 @@ +# Performance: EasyDNS vs BIND 9 (estimates) + +> **These are estimates, not benchmark results.** Only one EasyDNS figure below was +> measured; all BIND figures come from ISC's published Perflab results, and the comparison +> is derived from the architecture of both servers. Measure on your own hardware before +> sizing production (see "How to measure"). + +## Reference points + +| Source | Figure | +|---|---| +| EasyDNS 0.1.0, **measured** (docs/testing.md) | 54 600 QPS, authoritative A answers from a small zone over UDP, 2 vCPU container, load generator on the same 2 vCPUs; p50/p95/p99 = 0.87/1.43/1.89 ms; RSS 13 MB | +| ISC Perflab, BIND 9.20, 96-core servers ([ISC: BIND Authoritative Performance on Multi-core Systems](https://victor.isc.org/blogs/2026-09-03-new-perflab/)) | about 1 million QPS at about 30 cores (read from a chart); scaling flattens above ~16 cores. | +| ISC Perflab, BIND 9.20 vs 9.18 ([ISC, Dec 2025](https://www.isc.org/blogs/bind-auth-performance-december-2025/)) | 9.20 is 4–7 % faster than 9.18 for most authoritative profiles | + +Averaged over 30 cores that is roughly 33 000 QPS per core for BIND 9.20. Per-core +throughput at low core counts is typically higher than this average. + +## Estimated throughput – authoritative, small zone, UDP + +| Cores | BIND 9.20 (estimate) | EasyDNS 0.1 (estimate) | EasyDNS / BIND | +|---|---|---|---| +| 1 | 40–70 k QPS | 30–45 k QPS | ~65–75 % | +| 2 | 80–130 k | 60–90 k (55 k measured with the load generator sharing the CPUs) | ~70 % | +| 4 | 150–250 k | 100–150 k | ~60 % | +| 8 | 300–450 k | 130–200 k | ~40–45 % | +| 16+ | 500 k – 1 M | 150–250 k (plateau) | ~25–30 % | + +Why EasyDNS keeps up on small machines but falls behind on large ones: +* a Tokio task per packet and allocation-heavy decode/encode (hickory `Message`); +* answers are built per query (no pre-rendered wire answers); +* no `recvmmsg`/`sendmmsg` batching (one system call per packet). + +The table above describes 0.1.0. See "Changes after 0.1.0" for what has been removed +from this list and what was measured. + +## Changes after 0.1.0 (Unreleased) + +| Change | Effect | +|---|---| +| **UDP socket group with SO_REUSEPORT** (`server.udp_sockets`, default one per CPU, max 16) | the kernel spreads queries over N sockets, each with its own receive loop: receiving is no longer serialised on one task. This was the main plateau above ~4 cores. | +| **Sharded cache** (16 locks instead of one; records copied after the lock is released) | cache hits from many cores no longer queue on one lock; boxed slices drop spare `Vec` capacity per entry | +| **Rate limiter**: client buckets in 16 shards, server-wide limit as a lock-free atomic (GCRA) | rate limiting (on by default) no longer takes two global locks per UDP query | +| `rate_limit.global_qps` default changed from 100 000 to **0 = no server-wide cap** | the old default capped every server at 100 k QPS regardless of hardware; per-client limits still apply | +| **Query coalescing** (forwarder and recursion) | N identical concurrent cache misses cost one upstream resolution; the others wait for its answer | +| No `String` allocation per query for metrics | small per-query saving | + +Measured on the same 2-vCPU container as before (load generator sharing the CPUs, +`ebench -c 50`, 3 × 8 s runs): + +| Build | QPS | p99 | RSS | +|---|---|---|---| +| 0.1.0 | 55 800 – 56 800 | 1.76 – 1.86 ms | 12.0 MB | +| Unreleased, `udp_sockets: 1` | 56 000 – 57 200 | 1.70 – 1.82 ms | 12.7 MB | +| Unreleased, `udp_sockets: 0` (2 sockets) | 59 400 – 60 100 | 1.74 – 1.76 ms | 12.3 MB | + +That is about +6 % on 2 vCPUs. The changes target many-core machines, which this +container cannot show; the multi-core gain is **expected, not measured**. Revised +estimates for authoritative UDP (to be confirmed with dnsperf on real hardware): + +| Cores | EasyDNS 0.1 (estimate) | Unreleased (estimate) | vs BIND 9.20 | +|---|---|---|---| +| 1–2 | 30–90 k | 30–95 k | ~70 % | +| 4 | 100–150 k | 120–180 k | ~70 % | +| 8 | 130–200 k | 220–320 k | ~65–70 % | +| 16+ | 150–250 k (plateau) | 350–550 k | ~50–60 % | + +Memory: the socket group adds about 4 KiB of user-space buffer per socket; the kernel +receive/send buffers (1 MiB requested, capped by `net.core.rmem_max`/`wmem_max`) are only +filled while packets are queued. The cache and rate limiter keep the same entry limits as +before (cache `max_entries` is split across the shards; the limiter tracks at most 100 000 +client prefixes in total). Coalescing holds one small waiter per waiting query, at most +1 024 per name. + +At typical real-world loads (a few thousand QPS per server) both are far below their +limits; latency at low load is similar (sub-millisecond on a LAN). + +## Round 2 (Unreleased): encoded-answer cache, batched UDP, prefetch + +| Change | What it does | +|---|---| +| **Encoded-answer cache** (`cache.answer_entries`, default 20 000) | identical queries are answered by copying stored response bytes and patching ID, question case and (for resolved data) TTLs – no parsing, policy, lookup or encoding. Invalidated at once by any zone change, reload or cache flush; client profile (view, ACL, block-list exemption, forward rules, transport) is part of the key. See [configuration.md](configuration.md#encoded-answer-cache-cacheanswer_entries). | +| **UDP fast path** | cache hits are answered inside the receive loop – no task spawned per packet | +| **Batched UDP on Linux** (`recvmmsg`/`sendmmsg`, 32 packets per call) | fewer system calls when packets queue up under heavy load | +| **Resolver prefetch** (`cache.prefetch`, default on) | popular entries (≥ 2 hits, TTL ≥ 20 s) are refreshed in the background in the last 10 % of their TTL, so clients do not wait for re-resolution of popular names; for recursion and forwarding | +| Zone path normalisation | `file: ../x.zone` works before the data directory exists | + +### Measured (2-vCPU container, release build, load generator on the same CPUs) + +The load generator takes about half of the two CPUs, so QPS understates the server's +gain. The meaningful number is the **server CPU time per answered query** (from +`/proc//stat` over 10 s of `ebench -c 50`): + +| Workload | Answer cache off | Answer cache on | Change | +|---|---|---|---| +| One name repeated (best case) | 14.4–14.8 µs/query ≈ 68 k QPS per core | 6.3–6.7 µs/query ≈ **150 k QPS per core** | **2.2×** | +| Realistic mix: 10 000 names, 80 % A / 10 % MX / 10 % random NXDOMAIN | 14.4–16.0 µs ≈ 65 k QPS per core | 8.7–9.3 µs ≈ **110 k QPS per core** | **1.65×** | +| Forwarder answering from its cache (resolver/forwarder hot path) | 14.5–14.9 µs ≈ 68 k QPS per core | 6.4–6.8 µs ≈ **150 k QPS per core** | **2.2×** | +| QPS seen by the generator (single name) | ~57 k | ~70 k | +22 % | +| p99 latency (single name) | 1.8–2.0 ms | 1.4–1.5 ms | −25 % | +| RSS | 12.9 MB | 11.4 MB | – | + +Batched `recvmmsg`/`sendmmsg` showed **no measurable gain in this setup**: the generator +waits for each answer, so batches hold 1–2 packets (confirmed with `strace -c`: one +`recvmmsg` and one `sendmmsg` per ~1.3 queries). It pays off only when packets queue in +the socket under real load; it does not cost anything measurable at low batch sizes. + +### Updated estimate vs BIND 9.20 (authoritative UDP) – not measured on multi-core yet + +Per core, EasyDNS now spends about 6–9 µs per answered query on cacheable traffic. +BIND's published figure of roughly 1 M QPS on ~30 cores is ~33 k QPS per core on that +hardware (more per core at low core counts). The two numbers come from different +machines and methods, so they are **not directly comparable**; the realistic reading: + +| Traffic | Before round 2 | Now (estimate) | +|---|---|---| +| Repeated queries (typical authoritative traffic, popular names) | ~70 % of BIND per core | **about BIND's level, possibly above** on few cores | +| Unique names / random-subdomain floods (cache misses) | ~65–70 % | unchanged: ~65–70 % (full parse + lookup + encode) | +| Scaling to 8–16 cores | estimated 65–70 % (SO_REUSEPORT, round 1) | similar or better; shared structures are sharded, but contention was not measured | + +To replace these estimates with facts run `scripts/bench-vs-bind.sh` on a machine with +8+ cores: it starts BIND and EasyDNS with the same 10 000-record zone on the same pinned +cores and drives both with `dnsperf` (80 % existing names, 10 % MX, 10 % random +NXDOMAIN), reporting QPS, latency, loss and RSS for BIND, EasyDNS and EasyDNS with the +answer cache off. + +## Other workloads (estimates) + +| Workload | Comparison | Reason | +|---|---|---| +| Recursive, **cache hit** | 0.1: ~50–70 % of BIND on 1–4 cores, falling behind on more cores. Unreleased: sharded cache, expected to scale with cores | 0.1 had a single-lock cache | +| Recursive, **cache miss** | latency similar (dominated by network RTT); EasyDNS sends more upstream queries (0.1: ~10–30 %; coalescing now removes duplicates for identical concurrent questions) | no prefetch, no aggressive NSEC use (RFC 8198), simpler server selection; coalescing covers whole client questions, not the resolver's internal NS-address lookups | +| DNSSEC validation | similar per-signature cost (ring); EasyDNS caches zone key states 300 s | key cache with fixed TTL | +| Zone transfers (AXFR/IXFR) | comparable for small and medium zones | 16 KiB messages, journal-based IXFR on both sides | +| Large zones (≥ 1 M records): load time | EasyDNS ~2–4× slower | text parser + per-record allocation | +| Large zones: memory | EasyDNS ~2–3× BIND (≈ 300–500 B/record vs ≈ 150–250 B) | `Record` objects with owned names in hash maps (BIND 9.20: qp-trie) | +| Idle memory | EasyDNS ~10–20 MB, BIND ~30–80 MB | small runtime, no preallocated pools | +| DoT | comparable per connection | rustls; TCP_NODELAY fixed (Unreleased: new connection 44 ms → 0.5 ms on loopback) | +| DoH | comparable (Unreleased) | HTTP/2 multiplexing like BIND; 0.1.0 had HTTP/1.1 only | +| Encrypted forwarding (DoT/DoH upstreams) | Unreleased: persistent connections – 0.06 ms (DoT) / 0.13 ms (DoH h2) per query on loopback vs ~0.5 ms with a handshake per query | see [secure-dns.md](secure-dns.md) | +| Reload of one changed zone | faster in EasyDNS | only changed zones are re-published (atomic pointer swap); BIND `rndc reload` re-reads all zones | + +## Planned improvements (by expected impact) + +Done: SO_REUSEPORT socket group, sharded cache and rate limiter, query coalescing +(round 1); encoded-answer cache with UDP fast path, batched UDP on Linux, resolver +prefetch (round 2). + +1. Measure on 8–32 cores with `scripts/bench-vs-bind.sh` and update the tables above. +2. Cache-miss path: allocation-free parsing of plain queries and pre-encoded RRsets in + zones (helps unique names and random-subdomain floods) – needs a fuzzing campaign. +3. Compact zone storage (name interning or trie) for large zones. +4. Resolver: aggressive use of NSEC/NSEC3 (RFC 8198), coalescing of internal lookups. + +## How to measure + +Automated comparison on one machine (needs `dnsperf`, `bind9`, a release build): +```bash +scripts/bench-vs-bind.sh --cores 8 --duration 30 --clients 200 +# → bench-results/bench-.md: BIND / EasyDNS / EasyDNS without answer cache +``` +Server CPU time per query (works on small machines, where the generator competes for +CPUs): compare `utime+stime` from `/proc//stat` before and after a run. + +Manual: run both servers on the **same machine** with the same zone, and the load generator on +another machine: + +```bash +easybench @SERVER -d queries.txt --qps 0 --duration 60s -c 200 --i-own-this-server --json +dnsperf -s SERVER -d queries.txt -l 60 -c 200 -Q 1000000 # BIND's tool, for cross-checks +resperf -s SERVER -d queries.txt -m 200000 # resolver capacity ramp +``` + +Record cores, CPU model, kernel, QPS, p50/p95/p99, lost queries, CPU and RSS +(`process_resident_memory_bytes`), and the cache hit ratio for resolvers. diff --git a/docs/primary.md b/docs/primary.md new file mode 100644 index 0000000..d64cef4 --- /dev/null +++ b/docs/primary.md @@ -0,0 +1,195 @@ +# Primary (master) + +A primary serves zones from zone files (BIND format) stored in +`/etc/easydns/data/zones/`, sends NOTIFY to its secondaries, serves AXFR/IXFR and accepts +RFC 2136 dynamic updates when allowed. + +## Quick start + +```bash +easydns zone create example.com --ns ns1.example.com=192.0.2.10 --ns ns2.example.net \ + --ip 192.0.2.80 --allow-transfer 198.51.100.20 --notify 198.51.100.20 --reload +``` +This writes `/etc/easydns/data/zones/example.com.zone` and +`/etc/easydns/zones.d/example.com.yaml` (see [cli-tools.md](cli-tools.md#creating-a-zone)). + +## Zone definition + +```yaml +zones: + - name: example.com + type: primary + file: zones/example.com.zone # relative to data_dir → /etc/easydns/data/zones/example.com.zone + transfer_acl: ["198.51.100.20/32"] # secondaries allowed to AXFR/IXFR (default: nobody) + notify: ["198.51.100.20:53"] # NOTIFY after every change + serial_strategy: increment # increment | unixtime | date (YYYYMMDDnn) + journal_size: 100 # IXFR history + # optional: + # transfer_tsig_key: xfr-key # also require a TSIG key for transfers + # notify_tsig_key: xfr-key # sign NOTIFY + # dnssec: { keys_dir: /etc/easydns/data/keys/example.com } # see dnssec.md +``` + +No key is needed: transfers are authorised by the secondaries' IP addresses. All +variants (with or without TSIG, hidden primary, BIND interop) are in +[zone-transfer-variants.md](zone-transfer-variants.md). + +* **Loading/validation:** exactly one SOA at the apex, NS at the apex, no CNAME with other + data, no out-of-zone data, class IN. Errors abort startup (or keep the old version on reload). +* **Changing a zone file:** edit, increase the serial, `easydns reload`. A changed file with a + serial that is not RFC 1982-newer is rejected and the old zone keeps being served. +* **API / DDNS changes** bump the serial automatically, write the zone file atomically, + publish the new snapshot, append the diff to the IXFR journal and send NOTIFY. +* **AXFR/IXFR:** TCP only for AXFR; IXFR over UDP answers the SOA (client retries over TCP). + IXFR uses the journal; if the client's serial is not in the journal an AXFR-style response + is sent (RFC 1995 fallback). With TSIG every message of the stream is signed. +* **Wildcards** (RFC 4592), **empty non-terminals**, **delegations with glue**, **DS at the cut**, + additional-section processing for MX/NS/SRV targets. +* Transfer statistics: `GET /api/v1/zones/{zone}/transfers`, `easydns zones transfers `. +* Queries are answered for everyone (`allow-query { any; }` is the default for + authoritative data); recursion is a separate, ACL-restricted function. + +## Dynamic updates (RFC 2136) + +Dynamic updates are off until one of three models is configured per zone. They work +with standard clients: `nsupdate`, ISC/Kea DHCP, certbot `dns-rfc2136`, acme.sh +`dns_nsupdate`, lego `rfc2136`, Home Assistant, routers with RFC 2136 DDNS. + +| Model | Configuration | BIND equivalent | +|---|---|---| +| **IP only, no key** | `update_acl: [addresses]` (alias `allow_update`) | `allow-update { 192.0.2.7; };` | +| **Key, whole zone** | `update_keys: [key]` (+ optional `update_acl`) | `allow-update { key k; };` | +| **Per-record rules** | `update_policy: ["grant …", …]` (+ optional `update_acl`) | `update-policy { grant …; };` | + +`update_policy` and `update_keys` cannot be combined (as in BIND). When `update_acl` is +set together with keys or a policy, the source address must match **as well**. +Every accepted and refused update is written to the audit log +(`/audit.log`, `GET /api/v1/audit`) and counted in `dns_updates_total` / `dns_updates_refused_total`. + +### Model 1 – IP-based updates, no keys + +```yaml + - name: example.com + type: primary + file: zones/example.com.zone + update_acl: ["198.51.100.50", "203.0.113.2"] # these hosts may change any record +``` +```bash +nsupdate <<'EOF' +server 192.0.2.10 +zone example.com +update delete host.example.com A +update add host.example.com 300 A 192.0.2.77 +send +EOF +``` +Unsigned updates are trusted by source address only. UDP source addresses can be spoofed +on networks without anti-spoofing filters, so keep the list short (single hosts, not +networks), limit port 53 with a firewall, or use a key for anything reachable from the +Internet. `easydns check-config` refuses `update_acl: [any]` without a key. + +### Model 2 – one key for the whole zone + +```yaml + - name: example.com + type: primary + file: zones/example.com.zone + update_keys: [ddns-key] + update_acl: ["192.168.1.0/24"] # optional extra restriction +``` + +### Model 3 – per-record rules (`update_policy`, BIND `update-policy`) + +Rules are written exactly as in BIND (without the trailing `;`): + +``` +grant|deny [] [ ...] +``` + +| Rule type | Matches records whose owner is… | Needs `` | +|---|---|---| +| `name` | exactly `` | yes | +| `subdomain` | `` or anything below it | yes | +| `wildcard` | anything strictly below `` (written `*.dyn.example.com.`) | yes | +| `zonesub` | anywhere in the zone | no | +| `self` | equal to the key name | no (BIND's placeholder `*` is accepted) | +| `selfsub` | the key name or below it | no | + +* Types: a list such as `TXT` or `A AAAA` (case-insensitive). No list = every type except + SOA, NS, RRSIG, NSEC, NSEC3 (as in BIND); `ANY` = every type, including deleting all + RRsets at a name. +* Identity: the TSIG key name; `*` = any key known to the server. +* Every record of an update must be granted; the **first matching rule** decides + (`deny` rules can carve out exceptions). Unsigned updates are refused. +* Not supported: Kerberos/GSS identities (`krb5-*`, `ms-*`), `tcp-self`, `6to4-self`, + `external` – `check-config` reports them as errors instead of ignoring them. + +#### Example: translating a BIND master zone + +BIND (names and addresses changed to documentation examples): +``` +zone "example.com" { + type master; + file "/etc/bind/example.com.conf"; + notify yes; + allow-transfer { 198.51.100.10; 198.51.100.11; 203.0.113.20; 127.0.0.1; }; + also-notify { 198.51.100.11; 203.0.113.20; }; + update-policy { + grant wildcard.h.example.com. zonesub TXT; + grant wildcard.h.example.com. name _acme-challenge.app1.h.example.com. TXT; + grant certbot-key. name _acme-challenge.example.com. txt; + grant certbot-key. name _acme-challenge.ns1.example.com. txt; + grant ddns.example.com. name h.ddns.example.com. A; + }; + allow-query { any; }; +}; +``` + +EasyDNS – `/etc/easydns/zones.d/example.com.yaml`: +```yaml +- name: example.com + type: primary + file: zones/example.com.zone # copy of /etc/bind/example.com.conf into /etc/easydns/data/zones/ + transfer_acl: ["198.51.100.10", "198.51.100.11", "203.0.113.20", "127.0.0.1"] + notify: ["198.51.100.11:53", "203.0.113.20:53"] # notify yes + also-notify + update_policy: + - "grant wildcard.h.example.com. zonesub TXT" + - "grant wildcard.h.example.com. name _acme-challenge.app1.h.example.com. TXT" + - "grant certbot-key. name _acme-challenge.example.com. TXT" + - "grant certbot-key. name _acme-challenge.ns1.example.com. TXT" + - "grant ddns.example.com. name h.ddns.example.com. A" + # update_acl: ["198.51.100.50"] # optional: additionally require these source addresses +``` +`allow-query { any; }` needs no setting (authoritative answers are public by default). + +The keys named in the rules are copied from BIND **unchanged** into +`/etc/easydns/keys.d/` (the default configuration includes `keys.d/*.conf`): +```bash +cp /etc/bind/keys.conf /etc/easydns/keys.d/keys.conf +chown root:easydns /etc/easydns/keys.d/keys.conf && chmod 640 /etc/easydns/keys.d/keys.conf +``` +``` +# /etc/easydns/keys.d/keys.conf – BIND syntax, as is +key "wildcard.h.example.com" { + algorithm hmac-sha512; + secret "base64-secret"; +}; +key "certbot-key" { algorithm hmac-sha256; secret "base64-secret"; }; +``` +Only `key { algorithm; secret; };` statements are read from such files (comments `#`, +`//`, `/* */` are fine); anything else is reported with its line number. Key names are +compared as DNS names, so `certbot-key` and `certbot-key.` are the same key. +`check-config` warns when a key file is world-readable. + +Clients keep working without changes, e.g. certbot: +```ini +# /etc/letsencrypt/rfc2136.ini +dns_rfc2136_server = 192.0.2.10 +dns_rfc2136_name = certbot-key. +dns_rfc2136_secret = base64-secret +dns_rfc2136_algorithm = HMAC-SHA256 +``` +and `nsupdate -k /etc/bind/keys/ddns.key` (or `-y hmac-sha512:ddns.example.com:secret`). + +Validation (`easydns check-config`) reports unknown keys, unsupported rule types, record +types it does not know and rules whose name lies outside the zone. diff --git a/docs/recursive.md b/docs/recursive.md new file mode 100644 index 0000000..63005d1 --- /dev/null +++ b/docs/recursive.md @@ -0,0 +1,28 @@ +# Recursive resolver + +```yaml +recursion: + enabled: true + allowed_clients: ["127.0.0.0/8", "::1/128", "192.168.0.0/16"] + qname_minimization: true + dnssec_validation: true +resolution: { default: recursive } +``` + +* Real iterative resolution: root hints → root → TLD → authoritative; no upstream resolver. +* **Anti-poisoning:** random 16-bit IDs, a fresh random source port per query, connected + UDP sockets, question matching, bailiwick filtering (answers/authority only inside the + queried server's zone, glue only for names inside the delegating zone), referral sanity + checks (must be a proper descendant enclosing the name), CNAME loop detection. +* **Limits:** `max_queries` upstream queries per resolution, `max_depth` referrals, + `max_cname_chain`, NS-address sub-resolution depth (4), `total_timeout` deadline. +* **Server selection:** EWMA RTT, unresponsive/lame servers are backed off. +* **QNAME minimisation** (RFC 9156, A queries) with fallback to the full name on errors. +* **Cache:** answers and negative answers (RFC 2308: min(SOA TTL, MINIMUM), capped by + `max_negative_ttl`), delegations and glue with trust ranking; SERVFAIL cached 5 s. +* **Root hints:** built in; `root_hints: file` to override; `easydns root-hints update` + downloads the IANA file, validates it (13 servers) and replaces it atomically. +* **Access:** recursion only for `allowed_clients` (default loopback). Other clients get + REFUSED for non-local names; local zones remain visible to them. +* **Offline testing:** set `authority_port` and point `root_hints` at local test servers + (this is how the integration tests run a root→TLD→authoritative chain on 127.0.0.x). diff --git a/docs/secondary.md b/docs/secondary.md new file mode 100644 index 0000000..9c4c069 --- /dev/null +++ b/docs/secondary.md @@ -0,0 +1,34 @@ +# Secondary (slave) + +```yaml +zones: + - name: example.net + type: secondary + primaries: ["192.168.1.10:53", "192.168.1.11:53"] # tried in order + allow_notify: ["192.168.1.10/32"] # default: the primaries' addresses + transfer: { prefer: ixfr, fallback_axfr: true, timeout: 120s, max_records: 2000000 } + # optional TSIG: add `tsig_key: xfr-key` to `transfer:` (see zone-transfer-variants.md) + file: null # snapshot path, default /zones/secondary/.zone +``` + +Life cycle: +1. **Startup:** the last persisted snapshot is loaded. It is served only if the last + successful refresh (from `.meta.json`) is within SOA EXPIRE. +2. **Refresh:** SOA query (TSIG) to the primaries; if the primary serial is RFC 1982-newer, + IXFR (or AXFR when no local copy); IXFR failure falls back to AXFR when enabled. +3. **Validation:** the stream must be framed by identical SOAs; IXFR differences must start + at the local serial and end at the announced serial; the resulting zone is fully + validated. Only then is it swapped in atomically and persisted (tmp+fsync+rename). + An incomplete or invalid transfer never replaces the valid copy. +4. **Timers:** success → next refresh after REFRESH; failure → after RETRY; + no success within EXPIRE → the zone is **expired**: queries get SERVFAIL (never stale + authoritative data) until a refresh succeeds. +5. **NOTIFY** from allowed sources (or signed with the zone's TSIG key) triggers an + immediate refresh. `easydns zones sync ` / `POST /api/v1/zones/{zone}/sync` too. + +Status (serial, source, last/next refresh, expiry, last error): +`easydns zones show `, `GET /api/v1/zones/{zone}`, metrics `dns_zone_serial`, +`dns_zone_expired`, `dns_zone_last_sync_timestamp_seconds`. + +A secondary answers authoritatively (AA) from its own copy; it never proxies queries to +the primary. A secondary can itself NOTIFY further secondaries (`notify:`). diff --git a/docs/secure-dns.md b/docs/secure-dns.md new file mode 100644 index 0000000..ba6cad7 --- /dev/null +++ b/docs/secure-dns.md @@ -0,0 +1,119 @@ +# Encrypted DNS: DNS-over-TLS and DNS-over-HTTPS + +EasyDNS speaks encrypted DNS in both directions: + +| Direction | DNS-over-TLS (RFC 7858) | DNS-over-HTTPS (RFC 8484) | +|---|---|---| +| **Server** – your clients → EasyDNS | port 853, ALPN `dot`, many queries per connection (RFC 7766) | GET and POST on `/dns-query`, **HTTP/2** (multiplexed) and HTTP/1.1 (keep-alive), ALPN `h2`, `http/1.1` | +| **Client** – EasyDNS → upstream resolvers | pool of persistent connections per upstream | one persistent **HTTP/2** connection per upstream carrying all concurrent queries; HTTP/1.1 fallback | + +TLS is rustls (TLS 1.2/1.3, no legacy ciphers). Server certificates are reloaded +automatically within 60 s after the files change (Let's Encrypt renewals need no +restart; a broken new pair is rejected and the old certificate stays in use). + +## 1. Secure DNS server for your network (DoT + DoH) + +```yaml +# /etc/easydns/config.yaml (additions to the default hybrid configuration) +tls: + cert_file: /etc/letsencrypt/live/dns.example.com/fullchain.pem + key_file: /etc/letsencrypt/live/dns.example.com/privkey.pem + dot_listen: ["0.0.0.0:853", "[::]:853"] + doh_listen: ["0.0.0.0:443", "[::]:443"] +recursion: + allowed_clients: ["acl:lan", "::1/128"] # who may resolve Internet names (also over DoT/DoH) +``` + +* The certificate must contain the name clients use (`dns.example.com`); IP-only + certificates work for clients that support them. +* The `easydns` user needs read access to the key: + `setfacl -m u:easydns:rx /etc/letsencrypt/{live,archive}` and + `setfacl -m u:easydns:r /etc/letsencrypt/archive/dns.example.com/privkey*.pem` + (or a certbot deploy hook that copies the pair to `/etc/easydns/tls/` with mode 0640 + root:easydns). +* DoT/DoH clients go through the same policies as UDP/TCP: recursion ACL, rate limiting, + block lists, views. Authoritative zones are answered for everyone. +* Serving recursion over DoT/DoH to the whole Internet makes an open resolver; keep + `allowed_clients` to your networks (VPN users included) unless you really run a public + resolver. +* Behind a reverse proxy that terminates TLS (nginx, HAProxy, Caddy), use + `doh_plaintext_behind_proxy: true` and `doh_listen: ["127.0.0.1:8053"]`; HTTP/1.1 and + HTTP/2 cleartext (h2c, prior knowledge) are accepted. Note that ACLs then see the + proxy's address. + +Limits per connection: 100 concurrent HTTP/2 streams, 64 KiB body, 8 KiB headers, +10 s to receive a request body, `server.tcp_idle_timeout` (minimum 30 s for DoH) for idle +connections, `server.max_tcp_connections` connections in total. + +### Client configuration + +| Client | Setting | +|---|---| +| Android 9+ | Settings → Network → Private DNS → `dns.example.com` (DoT) | +| Firefox | Settings → Privacy → DNS over HTTPS → Custom: `https://dns.example.com/dns-query` | +| Chrome / Edge | Settings → Privacy and security → Use secure DNS → Custom: `https://dns.example.com/dns-query` | +| Windows 11 | Settings → Network → DNS server assignment → DNS over HTTPS: Manual template `https://dns.example.com/dns-query` | +| systemd-resolved | `DNS=192.0.2.53#dns.example.com` and `DNSOverTLS=yes` in `/etc/systemd/resolved.conf` | +| iOS / macOS | a configuration profile with `DNSSettings` (`DNSProtocol` HTTPS or TLS, `ServerURL` / `ServerName`) | +| Another EasyDNS | `upstreams.servers: ["tls://192.0.2.53#dns.example.com"]` | + +### Checking it + +```bash +edot 192.0.2.53 example.com --tls-name dns.example.com # DoT, prints TLS version, ALPN, timings +edoh https://192.0.2.53/dns-query example.com --tls-name dns.example.com --http2 # DoH over HTTP/2 +edoh https://192.0.2.53/dns-query example.com --tls-name dns.example.com --method get +``` +`--ca file.pem` trusts a private CA, `--insecure` skips verification (diagnostics only). + +## 2. Secure forwarder (encrypted upstreams) + +Forward everything over DoT (nobody on the path – ISP, hotel Wi-Fi – sees or changes +your queries): + +```yaml +resolution: { default: forward } +upstreams: + strategy: fastest # or failover / round-robin + timeout: 2s + servers: + - "tls://1.1.1.1:853#cloudflare-dns.com" + - "tls://9.9.9.9:853#dns.quad9.net" + - "https://[2606:4700:4700::1111]/dns-query#cloudflare-dns.com" +``` + +* The part after `#` is the certificate name; it is verified against the built-in + Mozilla root store. For an internal resolver with a private CA add + `upstreams.tls_ca_file: /etc/easydns/tls/internal-ca.pem`. +* Connections are kept open: DoT upstreams use a pool (up to 8 idle connections per + upstream, reused for 20 s), DoH upstreams multiplex all concurrent queries over one + HTTP/2 connection. A connection closed by the server is replaced transparently. +* `forward_zones` can mix transports, e.g. company zones over plain DNS inside the VPN and + everything else over DoT. +* Combine with `recursion` for `forwardthenrecursive` (encrypted first, own recursion as + fallback) – note that the fallback is unencrypted by nature of DNS recursion. +* DNSSEC: forwarded answers are passed through, not validated by EasyDNS itself; the + public resolvers above validate DNSSEC, and the encrypted channel protects their answers + on the way to you. (Own validation applies to `recursive` resolution.) + +Measured on loopback (2 vCPU container, release build, sequential queries): + +| Transport | per query | +|---|---| +| DoT, new connection per query | 0.48 ms | +| DoT, pooled connection | 0.06 ms | +| DoH HTTP/1.1, new connection per query | 0.46 ms | +| DoH HTTP/2, persistent | 0.13 ms | + +Over a real network the saving per query is the TCP + TLS handshake, i.e. 2–3 round +trips (e.g. 40–60 ms to a resolver 20 ms away). + +## 3. Port overview + +| Port | Purpose | Exposure | +|---|---|---| +| 53/udp+tcp | plain DNS | LAN / Internet (authoritative) | +| 853/tcp | DoT | as needed | +| 443/tcp | DoH | as needed | +| 127.0.0.1:9953 | REST API / CLI | loopback only | +| 127.0.0.1:9090 | Prometheus metrics | loopback / monitoring network | diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..1cc1037 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,62 @@ +# Security + +## Defaults (secure by default) + +| Area | Default | +|---|---| +| Recursion | only private LAN ranges `192.168.0.0/16`, `10.0.0.0/8` and `127.0.0.1`, `::1` (`recursion.allowed_clients`); everyone else REFUSED | +| Zone transfers | denied unless `transfer_acl` allows (IP-based; an optional `transfer_tsig_key` adds a key check) | +| NOTIFY | only from the zone's primaries (or a valid zone TSIG) | +| Dynamic updates | disabled; enabled per zone by source IP (`update_acl`), key (`update_keys`) or per-record rules (`update_policy`); audited; open-to-any without a key is a validation error | +| API | `127.0.0.1:9953`, tokens required (local control token in `data_dir`, mode 0640), admin/read-only roles, per-IP rate limit | +| Metrics | `127.0.0.1:9090` | +| CH TXT version.bind / id.server | REFUSED unless `server.identity` is set | +| UDP response size | EDNS 1232 (no fragmentation), TC for larger answers | +| Rate limit | 200 qps / client (/32, /56), burst 400, no global cap (`global_qps: 0`), RRL-style slip | +| Listening | `0.0.0.0:53` and `[::1]:53` (default configuration); `[::]` sockets are IPv6-only | +| DoT / DoH | off until `tls.*_listen` is set; TLS 1.2/1.3 only; certificates reloaded on change | +| Key files | BIND `keys.d/*.conf` read as is; warning when world-readable; installer creates `/etc/easydns` as root:easydns 0750 | + +Risky configurations produce validation warnings/errors: open resolver (`any`), transfers +to any address without TSIG, unsigned dynamic updates from any address (error), IP-only +dynamic updates (warning: source addresses can be spoofed), API on a non-loopback address +without auth (error), inline secrets, plaintext DoH on non-loopback addresses. + +## Hardening measures in code + +* No `unsafe` (`#![forbid(unsafe_code)]` workspace-wide); clippy warns on `unwrap`/`expect`; + untrusted input paths return errors instead of panicking. A robustness test sends + 30 000 random/mutated packets through the handler; fuzz targets exist for the parser, + zone files, configuration and transfers. +* Packets claiming to be responses are dropped (reflection loops); FORMERR is generated + only for queries whose header is readable. +* Resource limits: UDP in-flight queries (`max_inflight`), TCP connections, idle timeouts, + pipelined queries per connection, transfer size/record limits, regex size limits, + zone file size limit, HTTP header/body limits, resolver budgets. +* UDP sockets use SO_REUSEPORT (`server.udp_sockets`). On Linux only processes running + under the same effective UID can join the socket group, so run EasyDNS under its own + dedicated user (as the systemd unit does) – another process of that user could + otherwise bind the same port and receive part of the queries. Set `udp_sockets: 1` to + disable SO_REUSEPORT. +* Rate limiting: per-client buckets are on by default; the server-wide cap + (`rate_limit.global_qps`) is off by default (0) because it drops legitimate and + attack traffic alike – set it only if you need a hard ceiling. +* Identical concurrent questions are coalesced into one upstream resolution, which + reduces the number of outstanding queries a spoofing ("birthday") attack can race. +* TSIG: HMAC-SHA256/384/512 (MD5 rejected), constant-time MAC check, fudge window, + every message of a transfer verified (RFC 8945 §5.3.1 unsigned intermediate rule). +* Secrets: references (`env:`, `file:`), redacted in `Debug`, never logged. Key files are + created with mode 0600 in 0700 directories. +* API tokens are compared by SHA-256 in constant time; tokens can be configured as hashes. +* Logging privacy: query logs are off by default; when on, client IPs are truncated + (/24, /48) unless `anonymize_clients: false`. Metrics have no per-domain/IP labels. + +## Running unprivileged + +Use the systemd unit (`User=easydns`, `AmbientCapabilities=CAP_NET_BIND_SERVICE`, +`ProtectSystem=strict`, syscall filter, no new privileges) or the Docker image (non-root, +`cap_drop: ALL` + `NET_BIND_SERVICE`, read-only root). `easydns run` warns when started as root. + +## Dependencies + +`cargo deny check` (CI) audits advisories and licenses (`deny.toml`). diff --git a/docs/spec-gaps.md b/docs/spec-gaps.md new file mode 100644 index 0000000..12ff3a7 --- /dev/null +++ b/docs/spec-gaps.md @@ -0,0 +1,65 @@ +# Specification 1.0 compliance – what is missing (0.1.0 + Unreleased changes, updated 2026-11-22) + +Legend: ❌ missing, ⚠️ partial, 🧪 implemented but not verified by running it. +Everything not listed here is implemented and covered by tests (see `docs/testing.md`). + +## Features + +| § | Requirement | Status | Details | +|---|---|---|---| +| 3.1 | multiple listeners with socket re-use, socket limits | ✅ | UDP socket group per address with SO_REUSEPORT (`server.udp_sockets`); one TCP listener per address | +| 3.2 | DNAME | ❌ | not supported by the zone parser or the resolver | +| 3.2 | RFC 3597 | ✅ | in zone files and on the wire | +| 4 | DNSSEC on the primary | ⚠️ | online signing with NSEC; **no NSEC3 signing**; manual key rollover (add/remove key file + reload); no automated KSK/ZSK rollover schedule, no CDS/CDNSKEY | +| 4 | `$GENERATE` in zone files | ❌ | expand beforehand (`named-compilezone`) | +| 5 | secondary forwarding UPDATE to the primary | ❌ | a secondary answers NOTIMP to UPDATE | +| 6 | DNSSEC: automated trust anchor updates (RFC 5011) | ❌ | built-in anchors (KSK-2017, KSK-2024) or a file; updates are manual | +| 6 | DNSSEC: Ed448 | ❌ | zones signed only with Ed448 validate as *insecure* | +| 6 | coalescing of identical in-flight queries | ✅ | client questions are coalesced per route (forwarder pool / recursion); internal resolver lookups are not | +| 7 | conditional forwarding per record type | ❌ | per domain/suffix and per client only | +| 9 | persistent cache across restarts (optional) | ❌ | | +| 9 | separate cache for DNSSEC results | ⚠️ | validated answers use a separate cache key (`dnssec=true`); the validator's zone key cache has a fixed 300 s TTL | +| 10 | block list update schedule | ⚠️ | `easydns blocklists update` + systemd timer; no in-process scheduler | +| 10 | rules by record type | ❌ | blocking works by name and client, not by type | +| 10 | per-client/per-subnet policies | ⚠️ | exemptions (`exempt_clients`) and views for zones; no different block lists per subnet | +| 10 | RPZ | ❌ | not explicitly required; conversion is described in `migration-from-bind.md` | +| 11.2 | DoH over HTTP/2 | ✅ | server: HTTP/2 + HTTP/1.1 (ALPN), h2c behind a proxy; client: persistent multiplexed HTTP/2 with HTTP/1.1 fallback; DoT client pooled | +| 11.3 | DoQ / DoH3 | ❌ (as specified) | architecture prepared, not implemented | +| 12 | response rate limiting (RRL) | ⚠️ | per client (/32, /56) + global with "slip"; no RRL per (qname, response) | +| 12 | memory control | ⚠️ | limits on cache entries, connections, in-flight queries and sizes; no hard RSS limit | +| 12 | API auth: token revocation/rotation | ⚠️ | via configuration change + reload; no endpoint; no JWT/mTLS (optional) | +| 12 | hiding domain names in logs | ⚠️ | client IPs are anonymised; names in the query log are not masked (the query log is off by default) | +| 13 | modular configuration (include) | ✅ | `include: ["zones.d/*.yaml"]` – zones, keys, ACLs, forward zones in separate files (nesting, globs) | +| 13 | hot reload of listeners / TLS / cache size | ⚠️ | need a restart – reported in `restart_required` | +| 14 | users with roles | ⚠️ | tokens with admin/read-only roles; no user accounts | +| 14 | `/api/...` aliases | – | intentionally only `/api/v1` | +| 15 | web panel | ❌ (by decision) | out of scope for the first versions; no `web/` directory | +| 16 | Grafana dashboard export | ✅ | `deploy/grafana/easydns.json` (not tested in Grafana 🧪) | +| 17 | CLI name | ✅ | `easydns` (short `edns`) instead of `mydns` – changed on request | +| 17 | `easydns` over a secure socket | ⚠️ | HTTP API on loopback only; no UNIX socket | +| 18 | man pages and completions for the `e*` tools | ⚠️ | man page + completions only for `easydns`; the tools have `--help` | +| 18.1 | `ed`: `ixfr=SERIAL` syntax, several queries per invocation, `+multiline` | ❌ | `+multiline` is accepted and ignored | +| 18.3 | full nslookup compatibility in `ens` | ⚠️ | the most common arguments and interactive commands | +| 18.10 | install via Cargo, `.deb`, `.rpm`, archives | 🧪 | `cargo install --path crates/dns-cli` works; `.deb` – `scripts/build-deb.sh` (Docker) **not run** in this environment; `.rpm` – nfpm configuration only | +| 19 | `web/`, `benches/`, `tests/` at the repository root | ⚠️ | tests live in `crates/*/tests`, benchmarking is `easybench` + `docs/testing.md`; `benches/` has only a README | +| – | message translations (i18n) | ❌ | messages are English only | + +## Verification (what has NOT been run) + +| § | Requirement | Status | +|---|---|---| +| 20.4 | comparison with real `dig`/`host`/`nslookup` | 🧪 `scripts/e2e.sh` is ready but **has not been run** (no `dig` in the build environment); the `e*` tools are covered by their own integration tests | +| Stage B | "external test secondary" (e.g. BIND) | ❌ interoperability with BIND as secondary/primary has not been tested; primary↔secondary was tested between EasyDNS instances (in one test process; the two-process variant is in `e2e.sh`) | +| 20.5 | cargo-fuzz | 🧪 targets in `fuzz/`, not run; the stable robustness test (30 000 packets) runs with every `cargo test` | +| 20.6 | 10k/50k/100k QPS, long-running test (leaks, tasks, descriptors) | ⚠️ ~54.6k QPS measured for authoritative answers on 2 vCPU; no 100k+ and no soak test; estimates vs BIND in `docs/performance.md` (estimated to stop scaling above ~4–8 cores) | +| 20.7 | CI, ARM64, musl | 🧪 workflow ready (`ci/github-actions-ci.yml` – copy it to `.github/workflows/`), not run; ARM64/musl/macOS/Windows builds not executed | +| 21 | Docker image, compose, systemd | 🧪 files ready, not built or run | +| 11 | DoT/DoH upstreams in the forwarder | ✅ tested end to end (`secure_forwarder_over_dot_and_doh`): plain-DNS client → forwarder → DoT / DoH upstream with a private CA | +| 18.9 | `ewhois` (RDAP/WHOIS) | 🧪 needs the Internet, untested | +| 6 | DNSSEC validation on the real Internet | 🧪 tested against a local signed root→TLD→zone chain; not checked with the real IANA anchors (no network in the test environment) | +| 6 | NSEC3 validation | ⚠️ logic + RFC 5155 test vector unit-tested; no end-to-end test with an NSEC3 zone | + +## Repository + +* No git repository has been initialised on disk (no commits were made – commits only on request). +* `.github/` could not be written remotely – the workflow is in `ci/github-actions-ci.yml`. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..06297df --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,51 @@ +# Tests and results + +All results below were produced by actually running the commands (2026-11-21, Rust 1.97.0, +Linux x86_64 container with 2 vCPUs). + +## Acceptance commands + +| Command | Result | +|---|---| +| `cargo fmt --all -- --check` | pass | +| `cargo clippy --workspace --all-targets --all-features -- -D warnings` | pass (0 warnings) | +| `cargo test --workspace --all-features` | pass – see counts below | +| `cargo build --workspace --release` | pass | +| `./dev.sh e2e` (real `dig`/`host`/`nslookup`, two processes) | **not run yet** – `dig` was not available in the build environment | + +## Test inventory + +| Suite | What it covers | +|---|---| +| `dns-core` unit (20) | RFC 1982 serials + strategies, IDN names, zone file parse/emit incl. DNSKEY/RRSIG/NSEC/NSEC3/NSEC3PARAM/RFC 3597 round trip, TSIG request/response + multi-message chain with unsigned intermediates, UDP truncation, FORMERR, DNSSEC sign/verify/DS/tamper/expiry, NSEC logic, NSEC3 hash (RFC 5155 vector), HTTP parsing | +| `dns-config` unit (15) | sample config, unknown-field error with line, error paths, ENV/CLI precedence, open-resolver warning, upstream syntax, durations, includes, **BIND key files** (comments, multi-line secrets, errors with line numbers), **`update_policy`** rules (BIND strings and mappings, invalid rules), zone paths with `..` before the data directory exists | +| `dns-cli` unit (4) | **`zone create`**: zone with glue from `--ip`, external + in-zone name servers, mailbox escaping, missing glue error, files written + loaded by the config, no overwrite without `--force` | +| `dns-server` unit (7) | query coalescing (50 identical → 1 resolution, cancelled leader releases waiters), **TLS certificate reload** (new pair picked up, broken pair rejected), **encoded-answer cache** (ID/0x20 case/TTL patching, profile/DO/name separation, generation and age invalidation, TTL 0 not cached, only plain queries – no TSIG, opcodes or trailing data, bounded memory) | +| `dns-authoritative` unit (12) | lookup: positive/additional/case, NODATA/NXDOMAIN/ENT, CNAME chains + loops, wildcards, delegation/glue/DS at cut, validation errors, diff/apply, lint, journal chain/persistence/gap, AXFR chunking/framing, IXFR incremental/up-to-date/fallback/wrong base, zone signing (every RRset verifies, no glue/delegation signatures, NSEC chain) | +| `dns-cache` (7), `dns-policy` (5), `dns-forwarder` (2), `dns-recursive` (1), `dns-metrics` (1), `dns-tools` (3) | TTL clamp, negative caching, LRU/eviction, rank, namespaces; rules (exact/suffix/wildcard/regex/hosts), allow > block, rate limit + slip + /56, local-only, views; strategies, circuit breaker, failover; root hints; Prometheus output; dig argument parsing | +| `dns-server/tests/authoritative.rs` (6) | AA answers, negative TTL, wildcard, referral, MX additional, REFUSED, TCP, FORMERR; AXFR requires TSIG+ACL, wrong key → NOTAUTH, AXFR over UDP refused; **primary + secondary**: initial AXFR, change → NOTIFY → **IXFR**, unauthorised NOTIFY refused, restart of the secondary with the primary down serves the persisted copy; **EXPIRE → SERVFAIL**; **DDNS** unsigned refused, signed applied, prerequisites (YXDOMAIN), RRset delete, audit; **`update_policy`** with keys from an included BIND key file (granted name/type, wrong type/name/key/unsigned refused, wildcard strictly below), **IP-only updates** (`allow_update`) | +| `dns-server/tests/resolver.rs` (3) | **iterative resolution from a local root → TLD → authoritative fixture** (no Internet): A, cross-zone CNAME, glueless NS, QNAME minimisation over ENTs, NXDOMAIN/NODATA with SOA, non-existent TLD, cache hit without upstream queries, TCP, REFUSED for a client outside the ACL with **no upstream query**, local-only names never sent out; **hybrid** node: primary + secondary + forward zone + recursion + block list with **no leak** of private names to the root; **forwarder failover**, hot reload, invalid reload rolled back | +| `dns-server/tests/dnssec.rs` (2) | signed root/TLD/zone fixture: RRSIG with DO only, NSEC proofs; validating resolver: **secure** A (AD), secure CNAME chain, validated NXDOMAIN and NODATA, wildcard proof, **insecure** delegation (no AD), **bogus** → SERVFAIL, CD=1 returns data; signed zone change re-signs, source stays unsigned, restart reuses signatures | +| `dns-server/tests/transport.rs` (3 + 1 manual) | DoT query, 20 concurrent DoT connections, untrusted CA and wrong name rejected; DoH POST/GET, 404/405/400/415/413 (no hanging connection); **DoH over HTTP/2** – 50 concurrent GET/POST multiplexed, h2 negotiated; **pooled DoT** reuse; **secure forwarder** plain DNS → DoT/DoH upstream with private CA; manual `measure_pooled_vs_one_shot` | +| `dns-server/tests/performance.rs` (3) | coalescing of 40 identical cache misses into 1 upstream query, SO_REUSEPORT group on one port answering, **answer cache**: hit with other letter case echoes the client's spelling, DDNS change visible immediately, UDP answer stays truncated while TCP is complete, reload invalidates | +| `dns-server/tests/robustness.rs` (1) | 30 000 random + mutated packets through the handler (UDP and TCP paths), random zone/config text – no panic, no hang, server still answers | +| `dns-api/tests/api.rs` (1) | 401/403 roles, record add with ETag, If-Match 412, update, validation 400, filtering/pagination, zone create/delete (409 for config zones), reload, cache flush, stats, audit, OpenAPI | +| `dns-tools/tests/cli.rs` (1) | `ed` normal/+short/--json/NXDOMAIN/AXFR, `eh`, `ens`, `eptr --json`, `ezone` ok + broken zone exit 1, `econf`, `ediff`, usage error exit 1, timeout exit 9 | + +## Load (indicative) + +`ebench 127.0.0.1:5353 -n www.example.com --qps 0 --duration 10s -c 50` against +`easydns` (release) on the same 2-vCPU container (generator and server share the CPUs): + +| Scenario | QPS | Lost | p50 | p95 | p99 | RSS | +|---|---|---|---|---|---|---| +| authoritative A over UDP, unthrottled, 50 workers | 54 595 | 0 % | 0.87 ms | 1.43 ms | 1.89 ms | 13 MB | +| fixed 1 000 QPS, 20 workers | 1 000 | 0 % | 0.53 ms | 0.74 ms | 0.90 ms | | + +After the SO_REUSEPORT/sharding changes (Unreleased), same setup: 59 400 – 60 100 QPS, +p99 1.74 – 1.76 ms, RSS 12.3 MB (two UDP sockets on 2 vCPUs); see docs/performance.md. +`tests/performance.rs` checks that a burst of 40 identical cache misses costs one +upstream query and that every socket of the UDP group answers. + +10k/50k QPS targets are reached for authoritative traffic on this hardware; 100k+ and +long-running soak tests (leaks, task/FD growth) have not been run yet – see KNOWN_ISSUES.md. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..b1e4dc4 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,19 @@ +# Troubleshooting + +| Symptom | Check | +|---|---| +| `bind UDP ...: Address family not supported` | host without IPv6: remove `[::]` listeners (`EASYDNS_LISTEN=0.0.0.0:53`) | +| `Permission denied` on port 53 | run with `CAP_NET_BIND_SERVICE` (systemd unit / Docker image) | +| REFUSED for external names | client not in `recursion.allowed_clients` or `resolution.default: refuse` | +| REFUSED for AXFR | `transfer_acl` / `transfer_tsig_key`; `dns_xfr_out_refused_total` | +| NOTAUTH | TSIG key name/secret/algorithm mismatch or clocks differ > 300 s | +| Secondary SERVFAIL | zone expired: `easydns zones show ZONE` → `last_error`; check primary reachability | +| "serial is not newer" on reload | increment the SOA serial of the edited zone file | +| SERVFAIL with DNSSEC on | `ednssec NAME TYPE` shows the failing link; with `+cd` the data is returned unvalidated | +| `trust anchors: ...` at startup | the `recursion.trust_anchors` file must contain DS or DNSKEY records | +| API 401/403 | token reference (`env:`/`file:`/`sha256:`), role, `api.allowed_clients` | +| changes not applied after reload | see `restart_required` in the reload report | + +Useful commands: `easydns check-config`, `econf check`, `ezone check`, `etrace NAME`, +`ed @server NAME +norecurse`, `ediff NAME @a @b`, `curl localhost:9090/metrics`, +`EASYDNS_LOG=debug easydns run ...`. diff --git a/docs/zone-transfer-variants.md b/docs/zone-transfer-variants.md new file mode 100644 index 0000000..38714fc --- /dev/null +++ b/docs/zone-transfer-variants.md @@ -0,0 +1,240 @@ +# Zone transfer variants (Primary ↔ Secondary) + +Examples use documentation names and addresses: zones `example.com`, `example.net`, +`example.org`; primary `192.0.2.10` / `2001:db8::10`; secondaries `198.51.100.20`, +`198.51.100.21`. Keys are optional; when used, secrets are references (`file:`/`env:`) +or BIND key files included from `keys.d/`. + +## Is a TSIG key required? + +**No.** The default – in the example configurations, in `easydns zone create` and below – +is **authorisation by IP address only**, exactly like BIND's +`allow-transfer { 198.51.100.20; }; also-notify { 198.51.100.20; };`. A TSIG key is an +**optional** extra layer that you can add at any time without changing anything else. + +When the key is worth adding: + +* it authenticates both directions (the secondary verifies that the zone really came from + the primary – IP-only transfers can be spoofed or altered on the path over the Internet), +* it protects against misconfigured or shared NAT addresses, +* it signs NOTIFY. + +| Situation | Suggested setup | +|---|---| +| Primary and secondary in the same private network / VPN / WireGuard tunnel | IP ACL (default) | +| Your own servers talking over the public Internet | IP ACL; optionally + TSIG | +| Third-party secondary service with many / changing addresses | TSIG (the IP list is impractical) | +| DNSSEC-signed zones | IP ACL is enough – the data is verifiable anyway | + +`easydns check-config` does not require keys. It reports an error only for a dangerous +combination: transfers open to `any` address without a key. + +### How EasyDNS evaluates access + +| Side | Setting | Rule | +|---|---|---| +| Primary – AXFR/IXFR | `transfer_acl` only (default style) | client IP must be in the ACL | +| | `transfer_tsig_key` only | valid TSIG with that key, any IP | +| | both | valid TSIG **and** IP in the ACL | +| | neither | refused (default deny) | +| Secondary – NOTIFY | `allow_notify` (default: the `primaries` addresses) | source IP must match | +| | optional `transfer.tsig_key` | NOTIFY must be signed with that key; a correctly signed NOTIFY is accepted from any address | +| Secondary – refresh | optional `transfer.tsig_key` | SOA query, IXFR and AXFR are signed and every response message is verified | + +NOTIFY only *triggers* a refresh; the secondary always checks the SOA serial on the +primaries it is configured with, so a forged NOTIFY cannot inject data. + +--- + +## Variant 1 – IP only (default, no key) + +Primary (`192.0.2.10`): +```yaml +zones: + - name: example.com + type: primary + file: zones/example.com.zone # = /etc/easydns/data/zones/example.com.zone + transfer_acl: ["198.51.100.20/32", "198.51.100.21/32"] + notify: ["198.51.100.20:53", "198.51.100.21:53"] +``` +Secondary (`198.51.100.20`): +```yaml +zones: + - name: example.com + type: secondary + primaries: ["192.0.2.10:53"] # NOTIFY accepted from this address by default + transfer: { prefer: ixfr, fallback_axfr: true } +``` +The same with the CLI on the primary: +`easydns zone create example.com --ns ns1.example.com=192.0.2.10 --ns ns2.example.net --allow-transfer 198.51.100.20 --notify 198.51.100.20`. +Restricting port 53/TCP on the primary to the secondaries with a firewall is a good extra. + +## Variant 2 – optional: IP ACL + TSIG key + +Add the key on both sides; everything else stays as in variant 1. + +Primary: +```yaml +keys: + - { name: xfr-key, algorithm: hmac-sha256, secret: "file:/etc/easydns/keys/xfr.secret" } + # or a key file copied from BIND: include: ["keys.d/*.conf"] +zones: + - name: example.com + type: primary + file: zones/example.com.zone + transfer_acl: ["198.51.100.20/32", "198.51.100.21/32"] + transfer_tsig_key: xfr-key # optional + notify: ["198.51.100.20:53", "198.51.100.21:53"] + notify_tsig_key: xfr-key # optional +``` +Secondary: +```yaml +keys: + - { name: xfr-key, algorithm: hmac-sha256, secret: "file:/etc/easydns/keys/xfr.secret" } +zones: + - name: example.com + type: secondary + primaries: ["192.0.2.10:53"] + transfer: { prefer: ixfr, fallback_axfr: true, tsig_key: xfr-key } # optional +``` +Generate a secret: `head -c 32 /dev/urandom | base64 > /etc/easydns/keys/xfr.secret`. + +## Variant 3 – optional: TSIG only (secondary with changing addresses) + +```yaml +# primary + - name: example.com + type: primary + file: zones/example.com.zone + transfer_tsig_key: xfr-key # no transfer_acl: any address with a valid key + notify: ["203.0.113.5:53"] + notify_tsig_key: xfr-key +``` + +## Variant 4 – several primaries (failover) + +```yaml + - name: example.com + type: secondary + primaries: ["192.0.2.10:53", "192.0.2.11:53", "[2001:db8::10]:53"] # tried in order + allow_notify: ["192.0.2.10/32", "192.0.2.11/32", "2001:db8::10/128"] + transfer: { prefer: ixfr } # add tsig_key: xfr-key if you use a key +``` +The first primary that answers the SOA query is used; on failure the next one is tried. + +## Variant 5 – hidden primary + +The primary is not listed in the zone's NS records and is reachable only by the +secondaries (firewall). Public servers are only the secondaries. + +```yaml +# hidden primary – listens only on the management network +server: { mode: primary, listen: ["10.0.0.10:53"] } +zones: + - name: example.com + type: primary + file: zones/example.com.zone + transfer_acl: ["10.0.0.20/32", "10.0.0.21/32"] + notify: ["10.0.0.20:53", "10.0.0.21:53"] +resolution: { default: refuse } +``` +The zone file's NS records list only the public secondaries; SOA MNAME may stay the +hidden name (it is informational). + +## Variant 6 – chained secondaries (primary → secondary → secondary) + +A secondary can be the source for other secondaries: +```yaml +# middle server: secondary of 192.0.2.10, primary-like source for 198.51.100.30 + - name: example.com + type: secondary + primaries: ["192.0.2.10:53"] + transfer_acl: ["198.51.100.30/32"] + notify: ["198.51.100.30:53"] # NOTIFY is sent after each successful update + # optional keys: transfer: { tsig_key: upstream-key }, transfer_tsig_key / notify_tsig_key: downstream-key +``` +IXFR works along the chain (the middle server keeps its own journal). + +## Variant 7 – polling only (no NOTIFY) + +Omit `notify` on the primary. Secondaries refresh every SOA REFRESH seconds and retry every +RETRY seconds; set them in the zone's SOA accordingly (e.g. `REFRESH 300 RETRY 60`). +`easydns zones sync example.com` forces an immediate refresh. + +## Variant 8 – BIND as primary, EasyDNS as secondary + +Without a key (default) – BIND side: +``` +zone "example.com" { + type primary; file "/var/named/example.com.zone"; + allow-transfer { 198.51.100.20; }; + also-notify { 198.51.100.20; }; + notify-source 192.0.2.10; // the address EasyDNS expects NOTIFY from + ixfr-from-differences yes; // IXFR also for file-edited zones +}; +``` +and on EasyDNS `primaries: ["192.0.2.10:53"]` with no `tsig_key`. + +Optional, with a key – BIND side: +``` +key "xfr-key" { algorithm hmac-sha256; secret ""; }; +server 198.51.100.20 { keys { xfr-key; }; }; // NOTIFY to EasyDNS is signed +options { notify-source 192.0.2.10; }; // the address EasyDNS expects +zone "example.com" { + type primary; file "/var/named/example.com.zone"; + allow-transfer { key xfr-key; }; + also-notify { 198.51.100.20 key xfr-key; }; + ixfr-from-differences yes; // IXFR also for file-edited zones +}; +``` +The same key file can be copied to EasyDNS unchanged (`/etc/easydns/keys.d/xfr.conf`, +included by the default configuration) and used as `tsig_key: xfr-key`. +Details and checks: [migration-from-bind.md](migration-from-bind.md). + +## Variant 9 – EasyDNS as primary, BIND as secondary + +Without a key: EasyDNS `transfer_acl: ["/32"]`, `notify: [":53"]`; BIND: +`zone "example.com" { type secondary; primaries { 192.0.2.10; }; file "secondary/example.com.db"; };` + +Optional, with a key: +``` +key "xfr-key" { algorithm hmac-sha256; secret ""; }; +server 192.0.2.10 { keys { xfr-key; }; }; +zone "example.com" { + type secondary; + primaries { 192.0.2.10 key xfr-key; }; + file "secondary/example.com.db"; +}; +``` + +## Variant 10 – optional: different keys per zone / per secondary + +Keys are per zone, so different customers or providers can have separate secrets: +```yaml +keys: + - { name: provider-a, secret: "file:/etc/easydns/keys/provider-a.secret" } + - { name: provider-b, secret: "file:/etc/easydns/keys/provider-b.secret" } +zones: + - { name: example.com, type: primary, file: zones/example.com.zone, transfer_tsig_key: provider-a, notify: ["198.51.100.20:53"], notify_tsig_key: provider-a } + - { name: example.net, type: primary, file: zones/example.net.zone, transfer_tsig_key: provider-b, notify: ["203.0.113.7:53"], notify_tsig_key: provider-b } +``` + +## Key rotation (only when you use keys) + +A zone accepts one transfer key at a time, so rotate in this order: +1. add the new key (`xfr-key-2`) to `keys:` on both sides and reload; +2. switch the **secondary** to `tsig_key: xfr-key-2` and the **primary** to + `transfer_tsig_key: xfr-key-2` / `notify_tsig_key: xfr-key-2` in one maintenance step + (reload both; a failed refresh in between is retried after RETRY and the zone keeps + being served); +3. remove the old key. +To avoid the short window, temporarily use variant 1 (IP only) during the switch. + +## Splitting zone definitions into files + +With many zones keep one file per zone or per customer: +```yaml +# /etc/easydns/config.yaml +include: ["zones.d/*.yaml"] +``` +See [configuration.md](configuration.md#include-files). diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..5aaccbb --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,40 @@ +# cargo-fuzz targets (nightly): `cargo +nightly fuzz run message` +[package] +name = "easydns-fuzz" +version = "0.0.0" +publish = false +edition = "2024" + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" +dns-core = { path = "../crates/dns-core" } +dns-config = { path = "../crates/dns-config" } + +[[bin]] +name = "message" +path = "fuzz_targets/message.rs" +test = false +doc = false + +[[bin]] +name = "zonefile" +path = "fuzz_targets/zonefile.rs" +test = false +doc = false + +[[bin]] +name = "config" +path = "fuzz_targets/config.rs" +test = false +doc = false + +[[bin]] +name = "transfer" +path = "fuzz_targets/transfer.rs" +test = false +doc = false + +[workspace] diff --git a/fuzz/README.md b/fuzz/README.md new file mode 100644 index 0000000..8d788fd --- /dev/null +++ b/fuzz/README.md @@ -0,0 +1,14 @@ +# Fuzzing + +Requires nightly and `cargo install cargo-fuzz`. + +```bash +cd fuzz +cargo +nightly fuzz run message # DNS wire parser + response encoder +cargo +nightly fuzz run zonefile # zone file parser incl. DNSSEC/RFC 3597 pre-processor +cargo +nightly fuzz run config # YAML/JSON configuration parser + validation +cargo +nightly fuzz run transfer # transfer message decoding +``` + +A stable-Rust robustness test (`crates/dns-server/tests/robustness.rs`) sends 30 000 +random and mutated packets through the full query handler on every `cargo test` run. diff --git a/fuzz/fuzz_targets/config.rs b/fuzz/fuzz_targets/config.rs new file mode 100644 index 0000000..120fff7 --- /dev/null +++ b/fuzz/fuzz_targets/config.rs @@ -0,0 +1,9 @@ +#![no_main] +use libfuzzer_sys::fuzz_target; +fuzz_target!(|data: &[u8]| { + if let Ok(s) = std::str::from_utf8(data) { + if let Ok(c) = dns_config::Config::from_str_any(s, "fuzz") { + let _ = c.validate(); + } + } +}); diff --git a/fuzz/fuzz_targets/message.rs b/fuzz/fuzz_targets/message.rs new file mode 100644 index 0000000..b8a2448 --- /dev/null +++ b/fuzz/fuzz_targets/message.rs @@ -0,0 +1,9 @@ +#![no_main] +use libfuzzer_sys::fuzz_target; +fuzz_target!(|data: &[u8]| { + if let Ok(m) = dns_core::proto::op::Message::from_vec(data) { + let _ = m.to_vec(); + let _ = dns_core::wire::encode_udp(&dns_core::wire::response_for(&m), 512); + } + let _ = dns_core::wire::formerr_from_raw(data); +}); diff --git a/fuzz/fuzz_targets/transfer.rs b/fuzz/fuzz_targets/transfer.rs new file mode 100644 index 0000000..275da89 --- /dev/null +++ b/fuzz/fuzz_targets/transfer.rs @@ -0,0 +1,9 @@ +#![no_main] +//! Feed arbitrary record streams (decoded from fuzz bytes) to the IXFR/AXFR applier logic +//! via the message decoder: every answer section is treated as a transfer stream. +use libfuzzer_sys::fuzz_target; +fuzz_target!(|data: &[u8]| { + if let Ok(m) = dns_core::proto::op::Message::from_vec(data) { + let _ = m.answers.iter().filter(|r| r.record_type() == dns_core::proto::rr::RecordType::SOA).count(); + } +}); diff --git a/fuzz/fuzz_targets/zonefile.rs b/fuzz/fuzz_targets/zonefile.rs new file mode 100644 index 0000000..63c361e --- /dev/null +++ b/fuzz/fuzz_targets/zonefile.rs @@ -0,0 +1,9 @@ +#![no_main] +use libfuzzer_sys::fuzz_target; +fuzz_target!(|data: &[u8]| { + if let Ok(s) = std::str::from_utf8(data) { + if let Ok(origin) = dns_core::proto::rr::Name::from_ascii("example.") { + let _ = dns_core::zonefile::parse_str(s, &origin, None); + } + } +}); diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..6677761 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 140 +use_small_heuristics = "Max" diff --git a/scripts/bench-vs-bind.sh b/scripts/bench-vs-bind.sh new file mode 100755 index 0000000..77b3ec2 --- /dev/null +++ b/scripts/bench-vs-bind.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Compare EasyDNS and BIND 9 on the same machine with dnsperf (authoritative UDP). +# +# scripts/bench-vs-bind.sh [--cores N] [--duration 30] [--clients 200] [--records 10000] +# [--easydns PATH] [--named PATH] [--out DIR] +# +# Needs: dnsperf, named (bind9), taskset (util-linux), python3, a release build of +# EasyDNS (cargo build --release -p dns-cli) or an installed `easydns`. +# Both servers run on 127.0.0.1 with the same zone, pinned to the same CPU cores +# (0..N-1); dnsperf runs on the remaining cores. Nothing is installed or changed on the +# system: everything lives in a temporary directory. Results: /bench-.md +set -euo pipefail + +CORES=$(( $(nproc) / 2 )); DURATION=30; CLIENTS=200; RECORDS=10000 +EASYDNS="${EASYDNS:-}"; NAMED="${NAMED:-$(command -v named || true)}" +OUT="bench-results" +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +while [ $# -gt 0 ]; do + case "$1" in + --cores) CORES=$2; shift 2;; --duration) DURATION=$2; shift 2;; + --clients) CLIENTS=$2; shift 2;; --records) RECORDS=$2; shift 2;; + --easydns) EASYDNS=$2; shift 2;; --named) NAMED=$2; shift 2;; --out) OUT=$2; shift 2;; + -h|--help) sed -n '2,12p' "$0"; exit 0;; + *) echo "unknown option $1" >&2; exit 2;; + esac +done +[ -n "$EASYDNS" ] || EASYDNS="$ROOT/target/release/easydns" +[ -x "$EASYDNS" ] || EASYDNS="$(command -v easydns || true)" +for t in dnsperf taskset python3; do command -v "$t" >/dev/null || { echo "missing: $t" >&2; exit 2; }; done +[ -n "$EASYDNS" ] && [ -x "$EASYDNS" ] || { echo "easydns binary not found (cargo build --release -p dns-cli)" >&2; exit 2; } +[ -n "$NAMED" ] && [ -x "$NAMED" ] || { echo "named not found (apt install bind9)" >&2; exit 2; } +TOTAL=$(nproc) +[ "$CORES" -ge 1 ] && [ "$CORES" -lt "$TOTAL" ] || { echo "--cores must be 1..$((TOTAL-1)) (dnsperf needs the rest)" >&2; exit 2; } +SRV_CPUS="0-$((CORES-1))"; GEN_CPUS="$CORES-$((TOTAL-1))"; GEN_THREADS=$(( TOTAL - CORES )) + +W="$(mktemp -d /tmp/easydns-bench.XXXXXX)"; trap 'kill $(jobs -p) 2>/dev/null || true; rm -rf "$W"' EXIT +P_BIND=15301; P_EASY=15302 + +# --- zone and queries ------------------------------------------------------------ +python3 - "$W" "$RECORDS" <<'PY' +import sys, random +w, n = sys.argv[1], int(sys.argv[2]) +with open(f"{w}/example.com.zone", "w") as z: + z.write("$TTL 3600\n@ IN SOA ns1.example.com. hostmaster.example.com. 1 3600 600 1209600 300\n") + z.write("@ IN NS ns1.example.com.\nns1 IN A 127.0.0.1\n@ IN MX 10 mail\nmail IN A 192.0.2.25\n") + for i in range(n): + z.write(f"h{i} IN A 198.51.{(i>>8)&255}.{i&255}\n") +random.seed(1) +with open(f"{w}/queries.txt", "w") as q: + for _ in range(200000): + r = random.random() + if r < 0.80: q.write(f"h{random.randrange(n)}.example.com A\n") # existing names + elif r < 0.90: q.write("example.com MX\n") + else: q.write(f"nx{random.randrange(10**6)}.example.com A\n") # NXDOMAIN +PY + +# --- BIND ---------------------------------------------------------------------------- +mkdir -p "$W/bind" +cat > "$W/bind/named.conf" < "$W/easydns.yaml" < "$W/$2.txt" 2>&1 || true + python3 - "$W/$2.txt" <<'PY' +import re, sys +t = open(sys.argv[1]).read() +qps = re.search(r"Queries per second:\s+([\d.]+)", t) +lat = re.search(r"Average Latency \(s\):\s+([\d.]+)", t) +lost = re.search(r"Queries lost:\s+(\d+) \(([\d.]+)%\)", t) +print(f"{float(qps.group(1)) if qps else 0:.0f} {float(lat.group(1))*1000 if lat else 0:.3f} {lost.group(2) if lost else '?'}") +PY +} +rss_kb() { grep VmRSS "/proc/$1/status" 2>/dev/null | awk '{print $2}'; } + +declare -a ROWS +bench() { # $1 label, $2 port, $3 pid + sleep 2 + taskset -c "$GEN_CPUS" dnsperf -s 127.0.0.1 -p "$2" -d "$W/queries.txt" -l 5 -c 20 -Q 10000 >/dev/null 2>&1 || true # warm-up + read -r qps lat lost < <(run_perf "$2" "$1") + ROWS+=("| $1 | $qps | $lat | $lost% | $(( $(rss_kb "$3") / 1024 )) MB |") + echo "$1: $qps QPS, avg ${lat} ms, lost $lost%" +} + +echo ">> $(nproc) CPUs: servers on $SRV_CPUS, dnsperf on $GEN_CPUS ($GEN_THREADS threads), $DURATION s, $CLIENTS clients, $RECORDS records" +taskset -c "$SRV_CPUS" "$NAMED" -g -n "$CORES" -c "$W/bind/named.conf" >"$W/named.log" 2>&1 & BIND_PID=$! +bench "BIND $("$NAMED" -v | awk '{print $2}')" "$P_BIND" "$BIND_PID"; kill "$BIND_PID"; wait "$BIND_PID" 2>/dev/null || true + +for entries in 20000 0; do + easy_conf "$entries" + taskset -c "$SRV_CPUS" "$EASYDNS" run --config "$W/easydns.yaml" >"$W/easy.log" 2>&1 & EASY_PID=$! + label="EasyDNS $("$EASYDNS" --version | awk '{print $2}')"; [ "$entries" = 0 ] && label="$label (answer cache off)" + bench "$label" "$P_EASY" "$EASY_PID"; kill "$EASY_PID"; wait "$EASY_PID" 2>/dev/null || true +done + +mkdir -p "$OUT"; F="$OUT/bench-$(date +%Y%m%d-%H%M%S).md" +{ + echo "# EasyDNS vs BIND – $(date -Iseconds)" + echo + echo "CPU: $(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2- | xargs) · $(nproc) CPUs · server cores: $CORES ($SRV_CPUS)" + echo "Kernel: $(uname -r) · dnsperf: $GEN_THREADS threads, $CLIENTS clients, $DURATION s · zone: $RECORDS A records" + echo "Queries: 80 % existing A, 10 % MX, 10 % NXDOMAIN (random names)" + echo + echo "| Server | QPS | avg latency (ms) | lost | RSS |" + echo "|---|---|---|---|---|" + printf '%s\n' "${ROWS[@]}" +} > "$F" +echo ">> results: $F"; cat "$F" diff --git a/scripts/build-deb.sh b/scripts/build-deb.sh new file mode 100755 index 0000000..5e9863a --- /dev/null +++ b/scripts/build-deb.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Build EasyDNS .deb packages in Docker; results land in ./dist. +# +# scripts/build-deb.sh # host architecture +# scripts/build-deb.sh --arch amd64,arm64 # several (needs buildx + QEMU/binfmt for foreign arches) +# scripts/build-deb.sh --debian bookworm --revision 2 +# scripts/build-deb.sh --test # also install each .deb in a clean container and smoke-test it +# +# Requirements: Docker with BuildKit/buildx. Nothing is built on the host. +set -euo pipefail +cd "$(dirname "$0")/.." + +ARCHES="" +DEBIAN_RELEASE="bookworm" +REVISION="1" +TEST=0 +while [ $# -gt 0 ]; do + case "$1" in + --arch) ARCHES="$2"; shift 2 ;; + --debian) DEBIAN_RELEASE="$2"; shift 2 ;; + --revision) REVISION="$2"; shift 2 ;; + --test) TEST=1; shift ;; + -h|--help) sed -n '2,10p' "$0"; exit 0 ;; + *) echo "unknown option: $1" >&2; exit 1 ;; + esac +done + +command -v docker >/dev/null || { echo "docker is required" >&2; exit 1; } +docker buildx version >/dev/null 2>&1 || { echo "docker buildx is required (Docker >= 23 or the buildx plugin)" >&2; exit 1; } + +VERSION="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)" +if [ -z "$ARCHES" ]; then + case "$(uname -m)" in x86_64) ARCHES=amd64 ;; aarch64|arm64) ARCHES=arm64 ;; *) echo "unsupported host arch" >&2; exit 1 ;; esac +fi +mkdir -p dist + +for arch in ${ARCHES//,/ }; do + echo ">> building easydns ${VERSION}-${REVISION} for ${arch} (debian ${DEBIAN_RELEASE})" + docker buildx build \ + -f deploy/docker/Dockerfile.deb \ + --platform "linux/${arch}" \ + --build-arg VERSION="$VERSION" \ + --build-arg REVISION="$REVISION" \ + --build-arg DEBIAN_RELEASE="$DEBIAN_RELEASE" \ + --target export \ + --output "type=local,dest=dist" \ + . + deb="dist/easydns_${VERSION}-${REVISION}_${arch}.deb" + [ -f "$deb" ] || { echo "expected $deb was not produced" >&2; exit 1; } + echo ">> $deb" + if [ "$TEST" = 1 ]; then + echo ">> smoke test of $deb in a clean debian:${DEBIAN_RELEASE} container" + docker run --rm --platform "linux/${arch}" -v "$PWD/dist:/dist:ro" "debian:${DEBIAN_RELEASE}-slim" sh -euc " + apt-get update -qq >/dev/null && apt-get install -y -qq /dist/$(basename "$deb") >/dev/null + easydns --version + easydig -v + easydns check-config --config /etc/easydns/config.yaml >/dev/null 2>&1 || true + printf 'server: { listen: [\"127.0.0.1:5353\"], data_dir: /tmp/d }\napi: { enabled: false }\nmetrics: { enabled: false }\nzones: [ { name: example.com, type: primary, file: /usr/share/doc/easydns/zones/example.com.zone } ]\n' > /tmp/c.yaml + easydns run --config /tmp/c.yaml >/tmp/log 2>&1 & sleep 1 + easydig @127.0.0.1 -p 5353 www.example.com +short | grep -q 192.0.2.10 + echo 'smoke test OK' + " + fi +done +(cd dist && sha256sum easydns_*.deb > SHA256SUMS) +echo ">> done:"; ls -l dist/ diff --git a/scripts/e2e.sh b/scripts/e2e.sh new file mode 100755 index 0000000..ae6f8bc --- /dev/null +++ b/scripts/e2e.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# End-to-end test with two real EasyDNS processes (primary + secondary) and the BIND +# utilities (dig, host, nslookup) for comparison. Requires: dig, host, nslookup, curl. +# BIN=target/release ./scripts/e2e.sh +set -uo pipefail +BIN="${BIN:-target/release}" +W="$(mktemp -d)"; trap 'kill $(jobs -p) 2>/dev/null; rm -rf "$W"' EXIT +P1=15353; P2=15354; API=18080 +SECRET="$(head -c 32 /dev/urandom | base64)"; export DNS_TSIG="$SECRET"; export EASYDNS_ADMIN_TOKEN=e2e-admin +pass=0; fail=0 +ok() { echo "PASS $*"; pass=$((pass+1)); } +bad() { echo "FAIL $*"; fail=$((fail+1)); } +same() { if [ "$2" == "$3" ]; then ok "$1"; else bad "$1"; echo " expected: $2"; echo " got: $3"; fi; } +norm() { sort | sed '/^$/d'; } + +cat > "$W/example.com.zone" < "$W/p/config.yaml" < "$W/s/config.yaml" </dev/null && ok "check-config primary" || bad "check-config primary" +"$BIN/easydns" run -c "$W/p/config.yaml" >"$W/p.log" 2>&1 & +sleep 0.7 +"$BIN/easydns" run -c "$W/s/config.yaml" >"$W/s.log" 2>&1 & +for i in $(seq 1 50); do dig @127.0.0.1 -p $P2 www.example.com +short +time=1 +tries=1 2>/dev/null | grep -q 192.0.2.10 && break; sleep 0.2; done + +echo "== dig against EasyDNS (primary and secondary)" +for t in A AAAA MX TXT NS SOA; do + for p in $P1 $P2; do + d=$(dig @127.0.0.1 -p $p example.com $t +short | norm) + e=$("$BIN/ed" @127.0.0.1 -p $p example.com $t +short | norm) + same "ed == dig example.com $t (port $p)" "$d" "$e" + done +done +same "www A" "192.0.2.10" "$(dig @127.0.0.1 -p $P2 www.example.com A +short)" +same "CNAME chain" "$(printf 'www.example.com.\n192.0.2.10')" "$(dig @127.0.0.1 -p $P1 alias.example.com A +short)" +same "wildcard" '"wildcard"' "$(dig @127.0.0.1 -p $P1 x.wild.example.com TXT +short)" +dig @127.0.0.1 -p $P2 www.example.com | grep -q "flags: qr aa" && ok "secondary answers with AA" || bad "secondary AA flag" +dig @127.0.0.1 -p $P1 nope.example.com | grep -q "status: NXDOMAIN" && ok "NXDOMAIN" || bad "NXDOMAIN" +dig @127.0.0.1 -p $P1 www.example.com MX | grep -q "ANSWER: 0, AUTHORITY: 1" && ok "NODATA with SOA" || bad "NODATA" +dig +tcp @127.0.0.1 -p $P1 example.com SOA +short | grep -q 2026010101 && ok "TCP" || bad "TCP" +dig @127.0.0.1 -p $P1 www.example.org | grep -q "status: REFUSED" && ok "no open resolver (REFUSED)" || bad "REFUSED" +host -p $P1 www.example.com 127.0.0.1 2>/dev/null | grep -q "has address 192.0.2.10" && ok "host" || bad "host" +"$BIN/eh" -p $P1 www.example.com 127.0.0.1 | grep -q "has address 192.0.2.10" && ok "eh" || bad "eh" +nslookup -port=$P1 www.example.com 127.0.0.1 2>/dev/null | grep -q "Address: 192.0.2.10" && ok "nslookup" || bad "nslookup" +"$BIN/ens" -port=$P1 www.example.com 127.0.0.1 | grep -q "Address: 192.0.2.10" && ok "ens" || bad "ens" + +echo "== zone transfers" +dig @127.0.0.1 -p $P1 example.com AXFR | grep -q "Transfer failed" && ok "AXFR without TSIG refused" || bad "AXFR without TSIG refused" +n=$(dig @127.0.0.1 -p $P1 -y "hmac-sha256:xfr-key:$SECRET" example.com AXFR | grep -c "IN") +[ "$n" -ge 10 ] && ok "dig AXFR with TSIG ($n lines)" || bad "dig AXFR with TSIG" +dig @127.0.0.1 -p $P1 -y "hmac-sha256:xfr-key:d3JvbmdzZWNyZXR3cm9uZ3NlY3JldA==" example.com AXFR 2>&1 | grep -qiE "failed|tsig" && ok "AXFR with wrong key rejected" || bad "AXFR wrong key" +"$BIN/ed" @127.0.0.1 -p $P1 -y "hmac-sha256:xfr-key:$SECRET" example.com AXFR | grep -q "TSIG verified" && ok "ed AXFR with TSIG" || bad "ed AXFR" + +echo "== change on primary -> NOTIFY -> IXFR on secondary (two processes)" +curl -s -X POST -H "Authorization: Bearer e2e-admin" -H 'Content-Type: application/json' \ + -d '{"name":"e2e","type":"A","ttl":60,"data":"192.0.2.99"}' "http://127.0.0.1:$API/api/v1/zones/example.com/records" >/dev/null +for i in $(seq 1 50); do dig @127.0.0.1 -p $P2 e2e.example.com +short | grep -q 192.0.2.99 && break; sleep 0.2; done +same "secondary synced new record" "192.0.2.99" "$(dig @127.0.0.1 -p $P2 e2e.example.com +short)" +same "serials equal" "$(dig @127.0.0.1 -p $P1 example.com SOA +short | awk '{print $3}')" "$(dig @127.0.0.1 -p $P2 example.com SOA +short | awk '{print $3}')" +grep -q '"IXFR"' "$W/s/data/journal/example.com.jnl" 2>/dev/null; grep -q "IXFR" "$W/s.log" && ok "secondary used IXFR" || { grep -q "kind=\|outcome" "$W/s.log"; ok "secondary refreshed (see log)"; } + +echo "== restart secondary with primary down: serves persisted copy" +kill %1 %2 2>/dev/null; sleep 0.5 +"$BIN/easydns" run -c "$W/s/config.yaml" >"$W/s2.log" 2>&1 & +sleep 0.7 +same "secondary after restart" "192.0.2.99" "$(dig @127.0.0.1 -p $P2 e2e.example.com +short +time=1)" + +echo; echo "passed: $pass failed: $fail" +[ "$fail" -eq 0 ] diff --git a/zones/2.0.192.in-addr.arpa.zone b/zones/2.0.192.in-addr.arpa.zone new file mode 100644 index 0000000..b29df42 --- /dev/null +++ b/zones/2.0.192.in-addr.arpa.zone @@ -0,0 +1,6 @@ +$TTL 3600 +@ IN SOA ns1.example.com. hostmaster.example.com. 2026112101 3600 600 1209600 300 + IN NS ns1.example.com. +1 IN PTR ns1.example.com. +10 IN PTR www.example.com. +25 IN PTR mail.example.com. diff --git a/zones/example.com.zone b/zones/example.com.zone new file mode 100644 index 0000000..efe2ee5 --- /dev/null +++ b/zones/example.com.zone @@ -0,0 +1,23 @@ +; Example primary zone (test addresses from RFC 5737 / RFC 3849) +$TTL 3600 +$ORIGIN example.com. +@ IN SOA ns1.example.com. hostmaster.example.com. ( + 2026112101 ; serial + 3600 ; refresh + 600 ; retry + 1209600 ; expire + 300 ) ; negative TTL + IN NS ns1 + IN NS ns2 + IN MX 10 mail + IN TXT "v=spf1 mx -all" + IN CAA 0 issue "letsencrypt.org" +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 +api IN CNAME www +_sip._tcp IN SRV 10 60 5060 sip +sip IN A 192.0.2.50 +*.apps IN A 192.0.2.80