From e1764bd0b35b21f47121c5a043a4f7a1c5e8951b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 15:24:10 +0000 Subject: [PATCH 1/3] Add minimal DNS proxy with DoT/DoH in- and outbound Plain DNS (UDP/TCP), DNS over TLS and DNS over HTTPS (HTTP/1.1 + HTTP/2) inbound; DoT and DoH upstreams outbound with ordered failover. - Mandatory per-listener CIDR allowlist (no open resolver by default) - Upstreams addressed via configured bootstrap IPs only; hostnames are used for SNI/certificate verification, never resolved - rustls (ring), webpki-roots or custom CA file - Small bounds-checked DNS wire parser; responses validated against the query (question + ID), random IDs for DoT, ID 0 for DoH - UDP responses capped at EDNS size (max 1232), TC fallback - Connection, in-flight, handshake, idle and body limits - Hardened systemd unit (DynamicUser, CAP_NET_BIND_SERVICE only, LoadCredential for certificates, syscall filter) - Unit tests and end-to-end tests with fake upstreams and a test CA Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011hHaUEqQpj7pg7F9XAM8Ce --- .github/workflows/ci.yml | 22 + .gitignore | 1 + Cargo.lock | 1106 ++++++++++++++++++++++++++++++++++++++ Cargo.toml | 30 ++ README.md | 100 ++++ config.example.toml | 68 +++ dist/dns-proxy.service | 61 +++ rustfmt.toml | 1 + src/acl.rs | 35 ++ src/config.rs | 287 ++++++++++ src/dns.rs | 399 ++++++++++++++ src/frame.rs | 34 ++ src/lib.rs | 169 ++++++ src/main.rs | 96 ++++ src/server/doh.rs | 172 ++++++ src/server/mod.rs | 41 ++ src/server/stream.rs | 62 +++ src/server/udp.rs | 50 ++ src/tls.rs | 65 +++ src/upstream/doh.rs | 151 ++++++ src/upstream/dot.rs | 101 ++++ src/upstream/mod.rs | 157 ++++++ tests/e2e.rs | 699 ++++++++++++++++++++++++ 23 files changed, 3907 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 config.example.toml create mode 100644 dist/dns-proxy.service create mode 100644 rustfmt.toml create mode 100644 src/acl.rs create mode 100644 src/config.rs create mode 100644 src/dns.rs create mode 100644 src/frame.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/server/doh.rs create mode 100644 src/server/mod.rs create mode 100644 src/server/stream.rs create mode 100644 src/server/udp.rs create mode 100644 src/tls.rs create mode 100644 src/upstream/doh.rs create mode 100644 src/upstream/dot.rs create mode 100644 src/upstream/mod.rs create mode 100644 tests/e2e.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4dcadcb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - run: cargo fmt --check + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + - run: cargo build --locked --release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..026d5f2 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1106 @@ +# 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 = "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", +] + +[[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 = "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 = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +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 = "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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[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.6", +] + +[[package]] +name = "dns-proxy" +version = "0.1.0" +dependencies = [ + "base64", + "http-body-util", + "hyper", + "hyper-util", + "ipnet", + "rcgen", + "rustls", + "serde", + "tokio", + "tokio-rustls", + "toml", + "tracing", + "tracing-subscriber", + "webpki-roots", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[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 = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[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.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +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", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +dependencies = [ + "serde", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[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.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[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" + +[[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 = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[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 = "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 = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[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.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[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.6", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[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 = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[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 = "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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[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 = "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.6", +] + +[[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 = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "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.6", +] + +[[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.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "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-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", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[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.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +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 = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[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 = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + +[[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 = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..198a402 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "dns-proxy" +version = "0.1.0" +description = "Minimal DNS proxy: plain DNS, DoT and DoH in, DoT and DoH out" +license = "MIT" +rust-version = "1.85" +edition = "2024" + +[dependencies] +base64 = "0.23.1" +http-body-util = "0.1.5" +hyper = { version = "1.11.1", features = ["http1", "http2", "server", "client"] } +hyper-util = { version = "0.1.21", features = ["tokio", "server-auto", "http1", "http2"] } +ipnet = { version = "2.12.2", features = ["serde"] } +rustls = { version = "0.23.45", default-features = false, features = ["ring", "std", "tls12", "logging"] } +serde = { version = "1.0.229", features = ["derive"] } +tokio = { version = "1.53.2", features = ["rt-multi-thread", "net", "io-util", "time", "macros", "signal", "sync"] } +tokio-rustls = { version = "0.26.6", default-features = false, features = ["ring", "tls12", "logging"] } +toml = "1.1.6" +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter", "fmt"] } +webpki-roots = "1.0.9" + +[dev-dependencies] +rcgen = "0.14.10" + +[profile.release] +lto = true +codegen-units = 1 +strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8e90be --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# dns-proxy + +A small, no-frills DNS forwarder written in Rust. + +``` +clients ── plain DNS (UDP/TCP) ─┐ + ── DoT (RFC 7858) ──────┼──► dns-proxy ──► DoT / DoH upstreams (failover) + ── DoH (RFC 8484) ──────┘ +``` + +- **Inbound:** plain DNS over UDP and TCP, DNS over TLS, DNS over HTTPS (HTTP/1.1 and HTTP/2, GET and POST). +- **Outbound:** encrypted only (DoT or DoH). Upstreams are tried in order. One that fails is deprioritised for 30 s. +- **Not included:** no cache, no filtering, no ACME, no HTTP/3, no DNSSEC validation, no statistics endpoint. + +## Security properties + +- **Closed by default.** Every listener requires an explicit `allow` CIDR list. An open resolver needs a deliberate `"0.0.0.0/0"` / `"::/0"`. +- **No plain-DNS bootstrap.** Upstream hostnames are never resolved. You configure their IPs (`addrs`). The hostname is used only for SNI and certificate verification, so nothing goes in circles and nothing leaks. +- **Verified TLS.** Uses rustls (ring provider, TLS 1.2/1.3, AEAD suites only). Upstream certificates are verified against the built-in Mozilla roots (`webpki-roots`) or a `ca_file` you supply. +- **Validated responses.** Upstream responses must match the query's question and ID. + - DoT queries get a fresh random ID, so the client's ID never leaves the host. + - DoH uses ID 0, as RFC 8484 recommends. +- **UDP limits.** UDP responses are capped at the client's EDNS0 size, with an upper bound of 1232 bytes. Larger answers come back truncated (TC), and the client retries over TCP. This also limits amplification. +- **Malformed input is dropped.** Invalid queries are dropped without a reply over UDP and close the connection over TCP/DoT. Over DoH they get HTTP 400. +- **Bounded resources.** + - Concurrent UDP queries, connections, and queries per connection are all capped. + - Handshake, idle, header, and body timeouts apply, so slow clients can't hold slots. + - Message size is capped at 65535 bytes. +- **Private logs.** Query names are never logged. +- `#![forbid(unsafe_code)]`. The DNS wire handling is a small, bounds-checked parser with tests, including a random-input test that checks it never panics. + +## Build + +```sh +cargo build --release --locked +install -m 0755 target/release/dns-proxy /usr/local/bin/ +``` + +## Configure + +```sh +install -d /etc/dns-proxy +install -m 0644 config.example.toml /etc/dns-proxy/config.toml +dns-proxy --config /etc/dns-proxy/config.toml --check +``` + +See [`config.example.toml`](config.example.toml) for all options. Summary: + +| Section | Keys | +|---|---| +| `[[listen]]` | `proto` (`udp` \| `tcp` \| `dot` \| `doh`), `addr`, `allow`. For `dot`/`doh` also `cert`, `key`; for `doh` optionally `path` (default `/dns-query`). | +| `[[upstream]]` | `type = "dot"`: `name`, `addrs`. `type = "doh"`: `url`, `addrs`. Optional `ca_file`. | +| `[limits]` | Concurrency limits and timeouts (all optional). | + +Notes: + +- **Listening on IPv6.** Whether `[::]:53` also accepts IPv4 depends on `net.ipv6.bindv6only`. Configure separate IPv4 and IPv6 listeners to be explicit. +- **Certificate paths.** In certificate paths, `${CREDENTIALS_DIRECTORY}` is expanded (systemd `LoadCredential=`). No other variables are. +- **Logging.** Set the log level with `RUST_LOG` (default `info`), e.g. `RUST_LOG=debug`. + +## Run with systemd + +[`dist/dns-proxy.service`](dist/dns-proxy.service) runs the proxy as a transient unprivileged user (`DynamicUser=`). Its only capability is `CAP_NET_BIND_SERVICE`. It also enables a strict sandbox: read-only filesystem, a syscall filter, no new privileges, and more. + +```sh +install -m 0644 dist/dns-proxy.service /etc/systemd/system/ +systemctl daemon-reload +systemctl enable --now dns-proxy +systemd-analyze security dns-proxy +``` + +For DoT/DoH listeners: + +1. Uncomment the `LoadCredential=` lines in the unit. +2. Point `cert`/`key` at `${CREDENTIALS_DIRECTORY}/cert.pem` and `${CREDENTIALS_DIRECTORY}/key.pem`. + +The private key can stay readable by root only, because systemd hands the service a private copy. Since that copy is made at start, restart the service after a certificate renewal. With certbot, for example: + +```sh +certbot renew --deploy-hook "systemctl restart dns-proxy" +``` + +## Test + +```sh +cargo test +``` + +The end-to-end tests start fake DoT and DoH upstreams with a throwaway CA and query the proxy over all four inbound protocols. They cover: + +- failover, and SERVFAIL when every upstream fails +- certificate verification +- the allowlist +- UDP truncation +- TCP pipelining +- DoH error handling + +## License + +MIT diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..e0e6691 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,68 @@ +# dns-proxy example configuration. +# Every listener needs an explicit 'allow' list; nothing is open by default. + +# All values optional; shown with their defaults. +[limits] +udp_max_inflight = 1024 # concurrent UDP queries per listener (excess dropped) +tcp_max_connections = 256 # concurrent TCP/DoT/DoH connections per listener +tcp_max_inflight_per_conn = 16 # concurrent queries per connection / HTTP/2 streams +tcp_idle_timeout_ms = 10000 +tls_handshake_timeout_ms = 5000 +upstream_timeout_ms = 2000 # one attempt against one upstream +query_timeout_ms = 5000 # overall, across failover attempts +dot_pool_size = 8 # idle connections kept per DoT upstream + +# --- Inbound ----------------------------------------------------------------- + +[[listen]] +proto = "udp" +addr = "127.0.0.1:53" +allow = ["127.0.0.0/8"] + +[[listen]] +proto = "tcp" +addr = "127.0.0.1:53" +allow = ["127.0.0.0/8"] + +[[listen]] +proto = "udp" +addr = "[::1]:53" +allow = ["::1/128"] + +[[listen]] +proto = "tcp" +addr = "[::1]:53" +allow = ["::1/128"] + +# DoT and DoH need a certificate. With the shipped systemd unit, use +# LoadCredential= and reference the files via ${CREDENTIALS_DIRECTORY}. +# +# [[listen]] +# proto = "dot" +# addr = "0.0.0.0:853" +# allow = ["192.168.0.0/16", "10.0.0.0/8"] +# cert = "${CREDENTIALS_DIRECTORY}/cert.pem" +# key = "${CREDENTIALS_DIRECTORY}/key.pem" +# +# [[listen]] +# proto = "doh" +# addr = "0.0.0.0:443" +# allow = ["192.168.0.0/16", "10.0.0.0/8"] +# cert = "${CREDENTIALS_DIRECTORY}/cert.pem" +# key = "${CREDENTIALS_DIRECTORY}/key.pem" +# path = "/dns-query" + +# --- Upstreams (tried in order, failed ones are deprioritised for 30 s) ------- +# 'addrs' are bootstrap addresses: upstream hostnames are never resolved. +# The name / URL host is used for SNI and certificate verification only. + +[[upstream]] +type = "dot" +name = "dns.quad9.net" +addrs = ["9.9.9.9:853", "149.112.112.112:853", "[2620:fe::fe]:853"] + +[[upstream]] +type = "doh" +url = "https://cloudflare-dns.com/dns-query" +addrs = ["1.1.1.1:443", "1.0.0.1:443", "[2606:4700:4700::1111]:443"] +# ca_file = "/etc/dns-proxy/upstream-ca.pem" # replaces the built-in Mozilla roots diff --git a/dist/dns-proxy.service b/dist/dns-proxy.service new file mode 100644 index 0000000..3a85c1f --- /dev/null +++ b/dist/dns-proxy.service @@ -0,0 +1,61 @@ +[Unit] +Description=dns-proxy (plain DNS, DoT, DoH) +Documentation=https://github.com/nullthrone/dns-proxy +After=network-online.target +Wants=network-online.target +Before=nss-lookup.target +Wants=nss-lookup.target + +[Service] +Type=exec +ExecStart=/usr/local/bin/dns-proxy --config /etc/dns-proxy/config.toml +Restart=on-failure +RestartSec=2 + +# For DoT/DoH listeners: systemd copies the files into a private directory +# readable only by the service; reference them in the config as +# ${CREDENTIALS_DIRECTORY}/cert.pem and ${CREDENTIALS_DIRECTORY}/key.pem. +# The originals can stay root-only. Restart the service after renewal. +#LoadCredential=cert.pem:/etc/dns-proxy/cert.pem +#LoadCredential=key.pem:/etc/dns-proxy/key.pem + +# Unprivileged, transient user; only allowed to bind ports < 1024. +DynamicUser=yes +AmbientCapabilities=CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +NoNewPrivileges=yes + +# Filesystem +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectProc=invisible +ProcSubset=pid +UMask=0077 + +# Kernel +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +LockPersonality=yes +MemoryDenyWriteExecute=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +RestrictNamespaces=yes +RemoveIPC=yes + +# Network and syscalls +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged @resources +SystemCallErrorNumber=EPERM + +LimitNOFILE=4096 + +[Install] +WantedBy=multi-user.target diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..284d219 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 110 diff --git a/src/acl.rs b/src/acl.rs new file mode 100644 index 0000000..a6aef7d --- /dev/null +++ b/src/acl.rs @@ -0,0 +1,35 @@ +//! Client allowlist. + +use ipnet::IpNet; +use std::net::IpAddr; + +#[derive(Debug, Clone)] +pub struct Acl(Vec); + +impl Acl { + pub fn new(nets: Vec) -> Self { + Self(nets) + } + + pub fn allows(&self, ip: IpAddr) -> bool { + // IPv4-mapped IPv6 (dual-stack sockets) is matched as IPv4. + let ip = ip.to_canonical(); + self.0.iter().any(|n| n.contains(&ip)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matching() { + let acl = Acl::new(vec!["127.0.0.0/8".parse().unwrap(), "fd00::/8".parse().unwrap()]); + assert!(acl.allows("127.0.0.1".parse().unwrap())); + assert!(acl.allows("::ffff:127.0.0.1".parse().unwrap())); + assert!(acl.allows("fd12::1".parse().unwrap())); + assert!(!acl.allows("10.0.0.1".parse().unwrap())); + assert!(!acl.allows("::1".parse().unwrap())); + assert!(!Acl::new(vec![]).allows("127.0.0.1".parse().unwrap())); + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..21713e6 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,287 @@ +//! Configuration file (TOML). Everything is validated up front; anything +//! ambiguous or missing is an error rather than a silent default. + +use ipnet::IpNet; +use serde::Deserialize; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + #[serde(default)] + pub limits: Limits, + #[serde(rename = "listen", default)] + pub listeners: Vec, + #[serde(rename = "upstream", default)] + pub upstreams: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct Limits { + /// Concurrent UDP queries per listener; excess queries are dropped. + pub udp_max_inflight: usize, + /// Concurrent TCP/DoT/DoH connections per listener. + pub tcp_max_connections: usize, + /// Concurrent queries per TCP/DoT connection or DoH (HTTP/2) connection. + pub tcp_max_inflight_per_conn: usize, + pub tcp_idle_timeout_ms: u64, + pub tls_handshake_timeout_ms: u64, + /// Timeout of a single attempt against one upstream. + pub upstream_timeout_ms: u64, + /// Overall deadline for answering a query (all failover attempts). + pub query_timeout_ms: u64, + /// Idle connections kept per DoT upstream. + pub dot_pool_size: usize, +} + +impl Default for Limits { + fn default() -> Self { + Self { + udp_max_inflight: 1024, + tcp_max_connections: 256, + tcp_max_inflight_per_conn: 16, + tcp_idle_timeout_ms: 10_000, + tls_handshake_timeout_ms: 5_000, + upstream_timeout_ms: 2_000, + query_timeout_ms: 5_000, + dot_pool_size: 8, + } + } +} + +impl Limits { + pub fn tcp_idle_timeout(&self) -> Duration { + Duration::from_millis(self.tcp_idle_timeout_ms) + } + pub fn tls_handshake_timeout(&self) -> Duration { + Duration::from_millis(self.tls_handshake_timeout_ms) + } + pub fn upstream_timeout(&self) -> Duration { + Duration::from_millis(self.upstream_timeout_ms) + } + pub fn query_timeout(&self) -> Duration { + Duration::from_millis(self.query_timeout_ms) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Proto { + Udp, + Tcp, + Dot, + Doh, +} + +impl std::fmt::Display for Proto { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Proto::Udp => "udp", + Proto::Tcp => "tcp", + Proto::Dot => "dot", + Proto::Doh => "doh", + }) + } +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Listener { + pub proto: Proto, + pub addr: SocketAddr, + /// Client networks allowed to use this listener. Mandatory. + pub allow: Vec, + pub cert: Option, + pub key: Option, + /// DoH only: request path (default `/dns-query`). + pub path: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum UpstreamKind { + Dot, + Doh, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Upstream { + #[serde(rename = "type")] + pub kind: UpstreamKind, + /// DoT only: TLS server name (SNI and certificate verification). + pub name: Option, + /// DoH only: `https://host/path`. + pub url: Option, + /// Bootstrap socket addresses. Upstream hostnames are never resolved. + pub addrs: Vec, + /// PEM file with trust anchors replacing the built-in Mozilla roots. + pub ca_file: Option, +} + +impl Config { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("reading {}: {e}", path.display()))?; + Self::parse(&text) + } + + pub fn parse(text: &str) -> Result { + let cfg: Config = toml::from_str(text).map_err(|e| format!("config: {e}"))?; + cfg.validate()?; + Ok(cfg) + } + + fn validate(&self) -> Result<(), String> { + let l = &self.limits; + for (name, v) in [ + ("udp_max_inflight", l.udp_max_inflight as u64), + ("tcp_max_connections", l.tcp_max_connections as u64), + ("tcp_max_inflight_per_conn", l.tcp_max_inflight_per_conn as u64), + ("tcp_idle_timeout_ms", l.tcp_idle_timeout_ms), + ("tls_handshake_timeout_ms", l.tls_handshake_timeout_ms), + ("upstream_timeout_ms", l.upstream_timeout_ms), + ("query_timeout_ms", l.query_timeout_ms), + ] { + if v == 0 { + return Err(format!("limits.{name} must be > 0")); + } + } + if l.tcp_max_inflight_per_conn > u32::MAX as usize { + return Err("limits.tcp_max_inflight_per_conn too large".into()); + } + + if self.listeners.is_empty() { + return Err("no [[listen]] configured".into()); + } + if self.upstreams.is_empty() { + return Err("no [[upstream]] configured".into()); + } + + for li in &self.listeners { + let ctx = format!("listen {} {}", li.proto, li.addr); + if li.allow.is_empty() { + return Err(format!( + "{ctx}: 'allow' must not be empty (use \"0.0.0.0/0\" and \"::/0\" to deliberately run an open resolver)" + )); + } + let tls = matches!(li.proto, Proto::Dot | Proto::Doh); + if tls != (li.cert.is_some() && li.key.is_some()) || li.cert.is_some() != li.key.is_some() { + return Err(if tls { + format!("{ctx}: 'cert' and 'key' are required") + } else { + format!("{ctx}: 'cert'/'key' are only valid for dot/doh") + }); + } + match (&li.path, li.proto) { + (Some(p), Proto::Doh) if !p.starts_with('/') || p.contains(['?', '#']) => { + return Err(format!("{ctx}: 'path' must start with '/' and contain no query")); + } + (Some(_), p) if p != Proto::Doh => { + return Err(format!("{ctx}: 'path' is only valid for doh")); + } + _ => {} + } + } + + for up in &self.upstreams { + if up.addrs.is_empty() { + return Err("upstream: 'addrs' must list at least one IP:port".into()); + } + match up.kind { + UpstreamKind::Dot => { + if up.name.is_none() || up.url.is_some() { + return Err("upstream dot: requires 'name' and no 'url'".into()); + } + } + UpstreamKind::Doh => { + if up.url.is_none() || up.name.is_some() { + return Err("upstream doh: requires 'url' and no 'name'".into()); + } + } + } + } + Ok(()) + } +} + +/// Expands `${CREDENTIALS_DIRECTORY}` (systemd `LoadCredential=`) in a path. +/// No other variables are supported. +pub fn expand_path(p: &Path) -> Result { + const VAR: &str = "${CREDENTIALS_DIRECTORY}"; + let s = p + .to_str() + .ok_or_else(|| format!("non-UTF-8 path {}", p.display()))?; + if !s.contains(VAR) { + return Ok(p.to_path_buf()); + } + let dir = std::env::var("CREDENTIALS_DIRECTORY") + .map_err(|_| format!("{s}: CREDENTIALS_DIRECTORY is not set"))?; + Ok(PathBuf::from(s.replace(VAR, &dir))) +} + +#[cfg(test)] +mod tests { + use super::*; + + const UPSTREAM: &str = r#" + [[upstream]] + type = "dot" + name = "dns.example" + addrs = ["192.0.2.1:853"] + "#; + + fn parse(listen: &str) -> Result { + Config::parse(&format!("{listen}\n{UPSTREAM}")) + } + + #[test] + fn minimal_ok() { + let c = parse( + r#"[[listen]] + proto = "udp" + addr = "127.0.0.1:53" + allow = ["127.0.0.0/8"]"#, + ) + .unwrap(); + assert_eq!(c.listeners.len(), 1); + assert_eq!(c.limits.udp_max_inflight, 1024); + } + + #[test] + fn rejects_missing_or_empty_allow() { + assert!(parse("[[listen]]\nproto = \"udp\"\naddr = \"127.0.0.1:53\"").is_err()); + assert!(parse("[[listen]]\nproto = \"udp\"\naddr = \"127.0.0.1:53\"\nallow = []").is_err()); + } + + #[test] + fn tls_listeners_need_cert_and_key() { + let base = "[[listen]]\nproto = \"dot\"\naddr = \"127.0.0.1:853\"\nallow = [\"::1/128\"]\n"; + assert!(parse(base).is_err()); + assert!(parse(&format!("{base}cert = \"c\"")).is_err()); + assert!(parse(&format!("{base}cert = \"c\"\nkey = \"k\"")).is_ok()); + let udp = "[[listen]]\nproto = \"udp\"\naddr = \"127.0.0.1:53\"\nallow = [\"::1/128\"]\ncert = \"c\"\nkey = \"k\""; + assert!(parse(udp).is_err()); + } + + #[test] + fn rejects_unknown_fields_and_bad_upstreams() { + let li = "[[listen]]\nproto = \"udp\"\naddr = \"127.0.0.1:53\"\nallow = [\"::1/128\"]\n"; + assert!(Config::parse(&format!("{li}{UPSTREAM}\nbogus = 1")).is_err()); + assert!(Config::parse(li).is_err()); + let doh_without_url = "[[upstream]]\ntype = \"doh\"\naddrs = [\"192.0.2.1:443\"]"; + assert!(Config::parse(&format!("{li}{doh_without_url}")).is_err()); + let no_addrs = "[[upstream]]\ntype = \"dot\"\nname = \"x\"\naddrs = []"; + assert!(Config::parse(&format!("{li}{no_addrs}")).is_err()); + let hostname_addr = "[[upstream]]\ntype = \"dot\"\nname = \"x\"\naddrs = [\"dns.example:853\"]"; + assert!(Config::parse(&format!("{li}{hostname_addr}")).is_err()); + } + + #[test] + fn credentials_expansion() { + let p = Path::new("/etc/x.pem"); + assert_eq!(expand_path(p).unwrap(), p); + } +} diff --git a/src/dns.rs b/src/dns.rs new file mode 100644 index 0000000..20b7fdf --- /dev/null +++ b/src/dns.rs @@ -0,0 +1,399 @@ +//! Minimal DNS wire-format handling. +//! +//! The proxy never interprets records. It only needs to: +//! - validate that an inbound message is a sane standard query, +//! - know the question (to match responses) and the client's UDP size, +//! - rewrite message IDs, +//! - synthesise SERVFAIL and truncated (TC) replies. +//! +//! All access goes through bounds-checked helpers; malformed input yields +//! an error, never a panic. + +pub const HEADER_LEN: usize = 12; +pub const MAX_MSG: usize = 65535; +/// Classic DNS UDP limit for clients without EDNS0. +const MIN_UDP_PAYLOAD: usize = 512; +/// Upper bound for UDP responses regardless of what the client advertises +/// (DNS Flag Day 2020: avoid IP fragmentation). +const MAX_UDP_PAYLOAD: usize = 1232; +const MAX_NAME_LEN: usize = 255; + +const FLAG_QR: u16 = 0x8000; +const FLAG_TC: u16 = 0x0200; +const FLAG_RD: u16 = 0x0100; +const FLAG_RA: u16 = 0x0080; +const OPCODE_MASK: u16 = 0x7800; +const RCODE_SERVFAIL: u16 = 2; +const TYPE_OPT: u16 = 41; + +#[derive(Debug, PartialEq, Eq)] +pub struct Malformed; + +impl std::fmt::Display for Malformed { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("malformed DNS message") + } +} + +impl std::error::Error for Malformed {} + +/// A validated standard query. +#[derive(Debug, Clone)] +pub struct Query { + msg: Vec, + /// End offset of the question section within `msg`. + qend: usize, + pub id: u16, + /// Largest UDP response the client accepts. + pub udp_size: usize, +} + +impl Query { + pub fn parse(msg: &[u8]) -> Result { + if msg.len() < HEADER_LEN || msg.len() > MAX_MSG { + return Err(Malformed); + } + let id = be16(msg, 0)?; + let flags = be16(msg, 2)?; + if flags & FLAG_QR != 0 || flags & OPCODE_MASK != 0 { + return Err(Malformed); + } + if be16(msg, 4)? != 1 { + return Err(Malformed); + } + let ancount = be16(msg, 6)?; + let nscount = be16(msg, 8)?; + let arcount = be16(msg, 10)?; + + let mut off = skip_name(msg, HEADER_LEN, false)?; + off = checked_end(msg, off, 4)?; // QTYPE + QCLASS + let qend = off; + + for _ in 0..(u32::from(ancount) + u32::from(nscount)) { + off = skip_rr(msg, off)?.next; + } + let mut udp_size = MIN_UDP_PAYLOAD; + let mut seen_opt = false; + for _ in 0..arcount { + let rr = skip_rr(msg, off)?; + if rr.rtype == TYPE_OPT { + if seen_opt { + return Err(Malformed); + } + seen_opt = true; + udp_size = usize::from(rr.class).clamp(MIN_UDP_PAYLOAD, MAX_UDP_PAYLOAD); + } + off = rr.next; + } + + Ok(Self { + msg: msg.to_vec(), + qend, + id, + udp_size, + }) + } + + /// The raw question section (QNAME, QTYPE, QCLASS). + pub fn question(&self) -> &[u8] { + self.msg.get(HEADER_LEN..self.qend).unwrap_or_default() + } + + /// The query with its ID replaced, ready to be sent upstream. + pub fn with_id(&self, id: u16) -> Vec { + let mut m = self.msg.clone(); + set_id(&mut m, id); + m + } + + fn rd(&self) -> u16 { + be16(&self.msg, 2).unwrap_or(0) & FLAG_RD + } + + fn reply(&self, flags: u16) -> Vec { + let q = self.question(); + let mut out = Vec::with_capacity(HEADER_LEN + q.len()); + out.extend_from_slice(&self.id.to_be_bytes()); + out.extend_from_slice(&(FLAG_QR | FLAG_RA | self.rd() | flags).to_be_bytes()); + out.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 0]); + out.extend_from_slice(q); + out + } + + pub fn servfail(&self) -> Vec { + self.reply(RCODE_SERVFAIL) + } + + pub fn truncated(&self) -> Vec { + self.reply(FLAG_TC) + } + + /// Whether `resp` is a plausible answer to this query: a response + /// header, standard opcode, and an identical question (name compared + /// case-insensitively). The ID is checked by the caller. + pub fn is_answered_by(&self, resp: &[u8]) -> bool { + let Ok(flags) = be16(resp, 2) else { + return false; + }; + if flags & FLAG_QR == 0 || flags & OPCODE_MASK != 0 || be16(resp, 4) != Ok(1) { + return false; + } + let q = self.question(); + let Some(rq) = resp.get(HEADER_LEN..HEADER_LEN + q.len()) else { + return false; + }; + // Name compared case-insensitively; label length bytes are < 64 and + // thus unaffected. QTYPE/QCLASS (last 4 bytes) compared exactly. + let split = q.len().saturating_sub(4); + q[..split].eq_ignore_ascii_case(&rq[..split]) && q[split..] == rq[split..] + } +} + +pub fn id(msg: &[u8]) -> Option { + be16(msg, 0).ok() +} + +pub fn set_id(msg: &mut [u8], id: u16) { + if let Some(h) = msg.get_mut(0..2) { + h.copy_from_slice(&id.to_be_bytes()); + } +} + +fn be16(b: &[u8], off: usize) -> Result { + let end = off.checked_add(2).ok_or(Malformed)?; + let s: [u8; 2] = b + .get(off..end) + .ok_or(Malformed)? + .try_into() + .map_err(|_| Malformed)?; + Ok(u16::from_be_bytes(s)) +} + +/// Returns `off + n` if that many bytes are available. +fn checked_end(b: &[u8], off: usize, n: usize) -> Result { + let end = off.checked_add(n).ok_or(Malformed)?; + if end > b.len() { + return Err(Malformed); + } + Ok(end) +} + +/// Skips a domain name starting at `off`, returning the offset after it. +/// Compression pointers are not followed (only skipped) and are rejected +/// entirely when `allow_ptr` is false. +fn skip_name(b: &[u8], mut off: usize, allow_ptr: bool) -> Result { + let mut name_len = 0usize; + loop { + let len = *b.get(off).ok_or(Malformed)?; + match len & 0xC0 { + 0x00 => { + let len = usize::from(len); + name_len += len + 1; + if name_len > MAX_NAME_LEN { + return Err(Malformed); + } + off = checked_end(b, off, 1 + len)?; + if len == 0 { + return Ok(off); + } + } + 0xC0 if allow_ptr => return checked_end(b, off, 2), + _ => return Err(Malformed), + } + } +} + +struct Rr { + rtype: u16, + class: u16, + next: usize, +} + +fn skip_rr(b: &[u8], off: usize) -> Result { + let off = skip_name(b, off, true)?; + let rtype = be16(b, off)?; + let class = be16(b, off + 2)?; + let rdlen = be16(b, off + 8)?; + let next = checked_end(b, off + 10, usize::from(rdlen))?; + Ok(Rr { rtype, class, next }) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// Builds a query for `name` (dotted) with type A, optionally with an + /// EDNS0 OPT record advertising `edns`. + pub fn build_query(id: u16, name: &str, edns: Option) -> Vec { + let mut m = Vec::new(); + m.extend_from_slice(&id.to_be_bytes()); + m.extend_from_slice(&FLAG_RD.to_be_bytes()); + m.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, u8::from(edns.is_some())]); + for label in name.split('.').filter(|l| !l.is_empty()) { + m.push(label.len() as u8); + m.extend_from_slice(label.as_bytes()); + } + m.extend_from_slice(&[0, 0, 1, 0, 1]); + if let Some(size) = edns { + m.push(0); + m.extend_from_slice(&TYPE_OPT.to_be_bytes()); + m.extend_from_slice(&size.to_be_bytes()); + m.extend_from_slice(&[0, 0, 0, 0, 0, 0]); + } + m + } + + #[test] + fn parses_simple_query() { + let q = Query::parse(&build_query(0x1234, "example.com", None)).unwrap(); + assert_eq!(q.id, 0x1234); + assert_eq!(q.udp_size, 512); + assert_eq!(q.question().len(), 13 + 4); + } + + #[test] + fn edns_size_is_clamped() { + let q = Query::parse(&build_query(1, "a.b", Some(4096))).unwrap(); + assert_eq!(q.udp_size, MAX_UDP_PAYLOAD); + let q = Query::parse(&build_query(1, "a.b", Some(100))).unwrap(); + assert_eq!(q.udp_size, MIN_UDP_PAYLOAD); + let q = Query::parse(&build_query(1, "a.b", Some(1000))).unwrap(); + assert_eq!(q.udp_size, 1000); + } + + #[test] + fn root_query() { + let q = Query::parse(&build_query(1, "", None)).unwrap(); + assert_eq!(q.question(), &[0, 0, 1, 0, 1]); + } + + #[test] + fn rejects_bad_queries() { + let good = build_query(1, "example.com", None); + // Too short. + assert!(Query::parse(&good[..11]).is_err()); + // Truncated question. + assert!(Query::parse(&good[..good.len() - 1]).is_err()); + // QR set. + let mut m = good.clone(); + m[2] |= 0x80; + assert!(Query::parse(&m).is_err()); + // Non-zero opcode. + let mut m = good.clone(); + m[2] |= 0x08; + assert!(Query::parse(&m).is_err()); + // QDCOUNT = 2. + let mut m = good.clone(); + m[5] = 2; + assert!(Query::parse(&m).is_err()); + // Compression pointer in question. + let mut m = good[..HEADER_LEN].to_vec(); + m.extend_from_slice(&[0xC0, 0x0C, 0, 1, 0, 1]); + assert!(Query::parse(&m).is_err()); + // Reserved label type. + let mut m = good[..HEADER_LEN].to_vec(); + m.extend_from_slice(&[0x40, 0, 0, 1, 0, 1]); + assert!(Query::parse(&m).is_err()); + // ARCOUNT claims a record that is not there. + let mut m = good.clone(); + m[11] = 1; + assert!(Query::parse(&m).is_err()); + // Two OPT records. + let mut m = build_query(1, "a", Some(1232)); + let opt = m[m.len() - 11..].to_vec(); + m.extend_from_slice(&opt); + m[11] = 2; + assert!(Query::parse(&m).is_err()); + } + + #[test] + fn rejects_overlong_name() { + let label = "a".repeat(63); + let name = [label.as_str(); 4].join("."); + assert!(Query::parse(&build_query(1, &name, None)).is_err()); + let name = [label.as_str(); 3].join("."); + assert!(Query::parse(&build_query(1, &name, None)).is_ok()); + } + + #[test] + fn synthesised_replies() { + let q = Query::parse(&build_query(0xBEEF, "example.com", Some(1232))).unwrap(); + let sf = q.servfail(); + assert_eq!(id(&sf), Some(0xBEEF)); + assert_eq!(sf[3] & 0x0F, 2); + assert_ne!(sf[2] & 0x80, 0); + assert!(q.is_answered_by(&sf)); + let tc = q.truncated(); + assert_ne!(tc[2] & 0x02, 0); + assert!(q.is_answered_by(&tc)); + } + + #[test] + fn response_matching() { + let q = Query::parse(&build_query(7, "Example.COM", None)).unwrap(); + let other = Query::parse(&build_query(7, "example.com", None)).unwrap(); + assert!(q.is_answered_by(&other.servfail())); + let wrong = Query::parse(&build_query(7, "example.org", None)).unwrap(); + assert!(!q.is_answered_by(&wrong.servfail())); + // A query (QR=0) is not a response. + assert!(!q.is_answered_by(&build_query(7, "example.com", None))); + // Different QTYPE whose byte happens to be an ASCII letter case-pair. + let mut r = q.servfail(); + let n = r.len(); + r[n - 3] = 0x41; + let mut r2 = r.clone(); + r2[n - 3] = 0x61; + let q41 = Query::parse(&{ + let mut m = build_query(7, "example.com", None); + let n = m.len(); + m[n - 3] = 0x41; + m + }) + .unwrap(); + assert!(q41.is_answered_by(&r)); + assert!(!q41.is_answered_by(&r2)); + assert!(!q.is_answered_by(&[])); + } + + #[test] + fn id_rewrite() { + let q = Query::parse(&build_query(0x1111, "x", None)).unwrap(); + let m = q.with_id(0); + assert_eq!(id(&m), Some(0)); + let mut short = vec![1u8]; + set_id(&mut short, 5); + assert_eq!(short, vec![1u8]); + } + + #[test] + fn random_input_never_panics() { + // xorshift: deterministic, no extra dependency. + let mut s: u64 = 0x9E37_79B9_7F4A_7C15; + let mut next = || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + s + }; + let seed = build_query(1, "example.com", Some(1232)); + for _ in 0..200_000 { + let len = (next() % 64) as usize; + let mut m: Vec = if next() % 2 == 0 { + seed.clone() + } else { + (0..len).map(|_| next() as u8).collect() + }; + // Mutate a few bytes of the seed-based variant. + for _ in 0..(next() % 4) { + if !m.is_empty() { + let i = (next() as usize) % m.len(); + m[i] = next() as u8; + } + } + if let Ok(q) = Query::parse(&m) { + let _ = q.is_answered_by(&m); + let _ = q.servfail(); + } + } + } +} diff --git a/src/frame.rs b/src/frame.rs new file mode 100644 index 0000000..f7acea7 --- /dev/null +++ b/src/frame.rs @@ -0,0 +1,34 @@ +//! Length-prefixed DNS message framing for TCP and TLS (RFC 1035 4.2.2). + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +/// Writes one length-prefixed DNS message (RFC 1035 4.2.2). +pub async fn write_frame(w: &mut W, msg: &[u8]) -> std::io::Result<()> { + let len = u16::try_from(msg.len()) + .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "message too large"))?; + let mut buf = Vec::with_capacity(2 + msg.len()); + buf.extend_from_slice(&len.to_be_bytes()); + buf.extend_from_slice(msg); + w.write_all(&buf).await?; + w.flush().await +} + +/// Reads one length-prefixed DNS message; `None` on clean EOF. +pub async fn read_frame(r: &mut R) -> std::io::Result>> { + let mut len = [0u8; 2]; + match r.read_exact(&mut len).await { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None), + Err(e) => return Err(e), + } + let len = usize::from(u16::from_be_bytes(len)); + if len == 0 { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "empty message", + )); + } + let mut buf = vec![0u8; len]; + r.read_exact(&mut buf).await?; + Ok(Some(buf)) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..44d9897 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,169 @@ +//! Minimal DNS proxy: plain DNS (UDP/TCP), DoT and DoH in; DoT and DoH out. + +#![forbid(unsafe_code)] + +mod acl; +pub mod config; +mod dns; +mod frame; +mod server; +mod tls; +mod upstream; + +use acl::Acl; +use config::{Config, Proto}; +use std::net::SocketAddr; +use std::sync::Arc; +use tokio::net::{TcpListener, UdpSocket}; +use tokio::task::JoinSet; +use tokio::time::timeout; +use tokio_rustls::TlsAcceptor; +use tracing::{debug, info}; +use upstream::Resolver; + +/// Running proxy. Dropping it stops all listeners. +pub struct Proxy { + /// Bound address per listener, in configuration order. + pub bound: Vec<(Proto, SocketAddr)>, + tasks: JoinSet<()>, +} + +impl Proxy { + /// Waits until a listener task ends (which only happens on panic). + pub async fn join(mut self) { + self.tasks.join_next().await; + } +} + +struct Prepared { + proto: Proto, + addr: SocketAddr, + acl: Acl, + tls: Option, + path: String, +} + +/// Validates everything that can fail without binding sockets: upstream +/// URLs/names, CA files, listener certificates and keys. +fn prepare(cfg: &Config) -> Result<(Arc, Vec), String> { + let resolver = Arc::new(Resolver::new(&cfg.upstreams, &cfg.limits)?); + let mut out = Vec::with_capacity(cfg.listeners.len()); + for li in &cfg.listeners { + let tls = match (li.proto, &li.cert, &li.key) { + (Proto::Dot | Proto::Doh, Some(cert), Some(key)) => { + let alpn: &[&[u8]] = if li.proto == Proto::Dot { + &[b"dot"] + } else { + &[b"h2", b"http/1.1"] + }; + let sc = tls::server_config(&config::expand_path(cert)?, &config::expand_path(key)?, alpn)?; + Some(TlsAcceptor::from(sc)) + } + _ => None, + }; + out.push(Prepared { + proto: li.proto, + addr: li.addr, + acl: Acl::new(li.allow.clone()), + tls, + path: li.path.clone().unwrap_or_else(|| "/dns-query".into()), + }); + } + Ok((resolver, out)) +} + +/// Checks the configuration including certificates, without binding. +pub fn check(cfg: &Config) -> Result<(), String> { + prepare(cfg).map(|_| ()) +} + +/// Binds all listeners and starts serving. +pub async fn start(cfg: Config) -> Result { + let (resolver, listeners) = prepare(&cfg)?; + let limits = &cfg.limits; + let mut tasks = JoinSet::new(); + let mut bound = Vec::with_capacity(listeners.len()); + + for l in listeners { + let bind_err = |e: std::io::Error| format!("bind {} {}: {e}", l.proto, l.addr); + if l.proto == Proto::Udp { + let sock = UdpSocket::bind(l.addr).await.map_err(bind_err)?; + let local = sock.local_addr().map_err(bind_err)?; + info!(proto = %l.proto, addr = %local, "listening"); + bound.push((l.proto, local)); + tasks.spawn(server::udp::serve( + sock, + l.acl, + resolver.clone(), + limits.udp_max_inflight, + )); + continue; + } + + let listener = TcpListener::bind(l.addr).await.map_err(bind_err)?; + let local = listener.local_addr().map_err(bind_err)?; + info!(proto = %l.proto, addr = %local, "listening"); + bound.push((l.proto, local)); + let hs_timeout = limits.tls_handshake_timeout(); + let max_conns = limits.tcp_max_connections; + + match l.proto { + Proto::Tcp | Proto::Dot => { + let params = Arc::new(server::stream::Params { + resolver: resolver.clone(), + idle: limits.tcp_idle_timeout(), + max_inflight: limits.tcp_max_inflight_per_conn, + }); + let tls = l.tls; + tasks.spawn(server::accept_loop( + listener, + l.acl, + max_conns, + move |tcp, peer, permit| { + let params = params.clone(); + let tls = tls.clone(); + async move { + let _permit = permit; + match tls { + None => server::stream::handle(tcp, params).await, + Some(acc) => match timeout(hs_timeout, acc.accept(tcp)).await { + Ok(Ok(s)) => server::stream::handle(s, params).await, + _ => debug!(%peer, "dot handshake failed"), + }, + } + } + }, + )); + } + Proto::Doh => { + let params = Arc::new(server::doh::Params { + resolver: resolver.clone(), + path: l.path, + idle: limits.tcp_idle_timeout(), + max_inflight: limits.tcp_max_inflight_per_conn, + }); + let Some(acc) = l.tls else { + return Err("doh listener without TLS".into()); + }; + tasks.spawn(server::accept_loop( + listener, + l.acl, + max_conns, + move |tcp, peer, permit| { + let params = params.clone(); + let acc = acc.clone(); + async move { + let _permit = permit; + match timeout(hs_timeout, acc.accept(tcp)).await { + Ok(Ok(s)) => server::doh::handle(s, params).await, + _ => debug!(%peer, "doh handshake failed"), + } + } + }, + )); + } + Proto::Udp => unreachable!(), + } + } + Ok(Proxy { bound, tasks }) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..830539e --- /dev/null +++ b/src/main.rs @@ -0,0 +1,96 @@ +#![forbid(unsafe_code)] + +use dns_proxy::config::Config; +use std::path::PathBuf; +use std::process::ExitCode; +use tokio::signal::unix::{SignalKind, signal}; +use tracing::{error, info}; + +const USAGE: &str = "usage: dns-proxy [--config ] [--check] + + --config configuration file (default /etc/dns-proxy/config.toml) + --check validate configuration and certificates, then exit + --version print version"; + +fn main() -> ExitCode { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .with_target(false) + .init(); + + let mut config = PathBuf::from("/etc/dns-proxy/config.toml"); + let mut check = false; + let mut args = std::env::args().skip(1); + while let Some(a) = args.next() { + match a.as_str() { + "--config" | "-c" => match args.next() { + Some(p) => config = p.into(), + None => return usage(), + }, + "--check" => check = true, + "--version" | "-V" => { + println!("dns-proxy {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + "--help" | "-h" => { + println!("{USAGE}"); + return ExitCode::SUCCESS; + } + _ => return usage(), + } + } + + let cfg = match Config::load(&config) { + Ok(c) => c, + Err(e) => { + error!("{e}"); + return ExitCode::FAILURE; + } + }; + if check { + return match dns_proxy::check(&cfg) { + Ok(()) => { + println!("configuration OK"); + ExitCode::SUCCESS + } + Err(e) => { + error!("{e}"); + ExitCode::FAILURE + } + }; + } + + let rt = match tokio::runtime::Builder::new_multi_thread().enable_all().build() { + Ok(rt) => rt, + Err(e) => { + error!("runtime: {e}"); + return ExitCode::FAILURE; + } + }; + match rt.block_on(run(cfg)) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + error!("{e}"); + ExitCode::FAILURE + } + } +} + +fn usage() -> ExitCode { + eprintln!("{USAGE}"); + ExitCode::from(2) +} + +async fn run(cfg: Config) -> Result<(), String> { + let mut term = signal(SignalKind::terminate()).map_err(|e| e.to_string())?; + let mut int = signal(SignalKind::interrupt()).map_err(|e| e.to_string())?; + let proxy = dns_proxy::start(cfg).await?; + tokio::select! { + _ = term.recv() => info!("SIGTERM, shutting down"), + _ = int.recv() => info!("SIGINT, shutting down"), + _ = proxy.join() => return Err("listener task ended unexpectedly".into()), + } + Ok(()) +} diff --git a/src/server/doh.rs b/src/server/doh.rs new file mode 100644 index 0000000..6461e92 --- /dev/null +++ b/src/server/doh.rs @@ -0,0 +1,172 @@ +//! DNS over HTTPS server (RFC 8484): HTTP/1.1 and HTTP/2, GET and POST on a +//! single path. Nothing else is served. + +use crate::dns::{MAX_MSG, Query}; +use crate::upstream::Resolver; +use crate::upstream::doh::{DNS_MESSAGE, is_dns_message}; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD_INDIFFERENT; +use http_body_util::{BodyExt, Full, LengthLimitError, Limited}; +use hyper::body::{Bytes, Incoming}; +use hyper::header::{ALLOW, CONTENT_TYPE}; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; +use hyper_util::server::conn::auto; +use std::convert::Infallible; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncRead, AsyncWrite}; + +/// Grace period for in-flight requests after an idle shutdown starts. +const SHUTDOWN_GRACE: Duration = Duration::from_secs(5); + +pub struct Params { + pub resolver: Arc, + pub path: String, + pub idle: Duration, + pub max_inflight: usize, +} + +/// Tracks request activity on one connection for the idle timeout +/// (HTTP/2 connections are otherwise kept open indefinitely). +struct Activity { + start: Instant, + last_ms: AtomicU64, + inflight: AtomicUsize, +} + +impl Activity { + fn now_ms(&self) -> u64 { + u64::try_from(self.start.elapsed().as_millis()).unwrap_or(u64::MAX) + } + fn touch(&self) { + self.last_ms.store(self.now_ms(), Ordering::Relaxed); + } + fn idle_for(&self) -> Duration { + Duration::from_millis(self.now_ms().saturating_sub(self.last_ms.load(Ordering::Relaxed))) + } +} + +struct InflightGuard(Arc); + +impl Drop for InflightGuard { + fn drop(&mut self) { + self.0.inflight.fetch_sub(1, Ordering::Relaxed); + self.0.touch(); + } +} + +pub async fn handle(stream: S, p: Arc) +where + S: AsyncRead + AsyncWrite + Unpin + Send + 'static, +{ + let activity = Arc::new(Activity { + start: Instant::now(), + last_ms: AtomicU64::new(0), + inflight: AtomicUsize::new(0), + }); + + let svc = { + let p = p.clone(); + let activity = activity.clone(); + hyper::service::service_fn(move |req| { + let p = p.clone(); + activity.inflight.fetch_add(1, Ordering::Relaxed); + let guard = InflightGuard(activity.clone()); + async move { + let resp = respond(req, &p).await; + drop(guard); + Ok::<_, Infallible>(resp) + } + }) + }; + + let mut builder = auto::Builder::new(TokioExecutor::new()); + builder + .http1() + .timer(TokioTimer::new()) + .header_read_timeout(p.idle) + .max_buf_size(16 * 1024); + builder + .http2() + .timer(TokioTimer::new()) + .max_concurrent_streams(u32::try_from(p.max_inflight).unwrap_or(u32::MAX)) + .max_header_list_size(16 * 1024) + .keep_alive_interval(Some(Duration::from_secs(30))) + .keep_alive_timeout(Duration::from_secs(10)); + + let conn = builder.serve_connection(TokioIo::new(stream), svc); + tokio::pin!(conn); + let mut tick = tokio::time::interval(Duration::from_secs(1)); + loop { + tokio::select! { + _ = conn.as_mut() => return, + _ = tick.tick() => { + if activity.inflight.load(Ordering::Relaxed) == 0 && activity.idle_for() >= p.idle { + break; + } + } + } + } + conn.as_mut().graceful_shutdown(); + let _ = tokio::time::timeout(SHUTDOWN_GRACE, conn).await; +} + +fn status(code: StatusCode) -> Response> { + let mut r = Response::new(Full::default()); + *r.status_mut() = code; + r +} + +async fn respond(req: Request, p: &Params) -> Response> { + if req.uri().path() != p.path { + return status(StatusCode::NOT_FOUND); + } + let msg = match *req.method() { + Method::GET => { + let param = req + .uri() + .query() + .unwrap_or_default() + .split('&') + .find_map(|kv| kv.strip_prefix("dns=")); + // base64url of a 65535-byte message is at most 87380 chars. + match param + .filter(|s| s.len() <= 87_380) + .map(|s| URL_SAFE_NO_PAD_INDIFFERENT.decode(s)) + { + Some(Ok(m)) => m, + _ => return status(StatusCode::BAD_REQUEST), + } + } + Method::POST => { + let ct = req.headers().get(CONTENT_TYPE).and_then(|v| v.to_str().ok()); + if !ct.is_some_and(is_dns_message) { + return status(StatusCode::UNSUPPORTED_MEDIA_TYPE); + } + // Bounded in size and time: a slowly trickling body must not + // hold a connection slot indefinitely. + match tokio::time::timeout(p.idle, Limited::new(req.into_body(), MAX_MSG).collect()).await { + Ok(Ok(b)) => b.to_bytes().to_vec(), + Ok(Err(e)) if e.is::() => return status(StatusCode::PAYLOAD_TOO_LARGE), + Ok(Err(_)) => return status(StatusCode::BAD_REQUEST), + Err(_) => return status(StatusCode::REQUEST_TIMEOUT), + } + } + _ => { + let mut r = status(StatusCode::METHOD_NOT_ALLOWED); + r.headers_mut() + .insert(ALLOW, "GET, POST".parse().expect("static header")); + return r; + } + }; + let Ok(q) = Query::parse(&msg) else { + return status(StatusCode::BAD_REQUEST); + }; + let answer = p.resolver.resolve(&q).await; + let mut r = Response::new(Full::new(Bytes::from(answer))); + r.headers_mut() + .insert(CONTENT_TYPE, DNS_MESSAGE.parse().expect("static header")); + r +} diff --git a/src/server/mod.rs b/src/server/mod.rs new file mode 100644 index 0000000..afd4b3b --- /dev/null +++ b/src/server/mod.rs @@ -0,0 +1,41 @@ +pub mod doh; +pub mod stream; +pub mod udp; + +use crate::acl::Acl; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tracing::debug; + +/// Accepts TCP connections, enforcing the allowlist and the connection +/// limit before any byte is read, and hands them to `handle`. +pub async fn accept_loop(listener: TcpListener, acl: Acl, max_conns: usize, handle: F) +where + F: Fn(TcpStream, SocketAddr, OwnedSemaphorePermit) -> Fut, + Fut: Future + Send + 'static, +{ + let conns = Arc::new(Semaphore::new(max_conns)); + loop { + let (tcp, peer) = match listener.accept().await { + Ok(x) => x, + Err(e) => { + // E.g. EMFILE: back off instead of spinning. + debug!(error = %e, "accept"); + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + }; + if !acl.allows(peer.ip()) { + continue; + } + let Ok(permit) = conns.clone().try_acquire_owned() else { + debug!("connection limit reached, closing"); + continue; + }; + let _ = tcp.set_nodelay(true); + tokio::spawn(handle(tcp, peer, permit)); + } +} diff --git a/src/server/stream.rs b/src/server/stream.rs new file mode 100644 index 0000000..8bbe3e8 --- /dev/null +++ b/src/server/stream.rs @@ -0,0 +1,62 @@ +//! Plain DNS over TCP and DNS over TLS (RFC 7858). Queries on one +//! connection are processed concurrently (RFC 7766 pipelining), bounded +//! per connection. + +use crate::dns::Query; +use crate::frame::{read_frame, write_frame}; +use crate::upstream::Resolver; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; +use tokio::sync::{Semaphore, mpsc}; +use tokio::time::timeout; + +pub struct Params { + pub resolver: Arc, + pub idle: Duration, + pub max_inflight: usize, +} + +pub async fn handle(stream: S, p: Arc) +where + S: AsyncRead + AsyncWrite + Send + 'static, +{ + let (mut rd, mut wr) = tokio::io::split(stream); + let (tx, mut rx) = mpsc::channel::>(p.max_inflight); + let idle = p.idle; + let writer = tokio::spawn(async move { + while let Some(msg) = rx.recv().await { + // A client that stops reading must not pin the connection. + if !matches!(timeout(idle, write_frame(&mut wr, &msg)).await, Ok(Ok(()))) { + return; + } + } + let _ = wr.shutdown().await; + }); + + let inflight = Arc::new(Semaphore::new(p.max_inflight)); + loop { + // Stop reading while the per-connection limit is exhausted. + let Ok(permit) = inflight.clone().acquire_owned().await else { + break; + }; + // Each message must arrive completely within the idle timeout. + let msg = match timeout(p.idle, read_frame(&mut rd)).await { + Ok(Ok(Some(m))) => m, + _ => break, + }; + let Ok(q) = Query::parse(&msg) else { + break; + }; + let tx = tx.clone(); + let resolver = p.resolver.clone(); + tokio::spawn(async move { + let resp = resolver.resolve(&q).await; + let _ = tx.send(resp).await; + drop(permit); + }); + } + // Let in-flight answers drain; the writer ends once all senders are gone. + drop(tx); + let _ = writer.await; +} diff --git a/src/server/udp.rs b/src/server/udp.rs new file mode 100644 index 0000000..fd035c3 --- /dev/null +++ b/src/server/udp.rs @@ -0,0 +1,50 @@ +//! Plain DNS over UDP. + +use crate::acl::Acl; +use crate::dns::{MAX_MSG, Query}; +use crate::upstream::Resolver; +use std::sync::Arc; +use tokio::net::UdpSocket; +use tokio::sync::Semaphore; +use tracing::debug; + +pub async fn serve(sock: UdpSocket, acl: Acl, resolver: Arc, max_inflight: usize) { + let sock = Arc::new(sock); + let inflight = Arc::new(Semaphore::new(max_inflight)); + let mut buf = vec![0u8; MAX_MSG]; + loop { + let (n, peer) = match sock.recv_from(&mut buf).await { + Ok(x) => x, + Err(e) => { + debug!(error = %e, "udp recv"); + continue; + } + }; + if !acl.allows(peer.ip()) { + continue; + } + // Invalid queries are dropped silently: answering garbage only + // helps reflection attacks. + let Ok(q) = Query::parse(&buf[..n]) else { + continue; + }; + let Ok(permit) = inflight.clone().try_acquire_owned() else { + debug!("udp: too many queries in flight, dropping"); + continue; + }; + let sock = sock.clone(); + let resolver = resolver.clone(); + tokio::spawn(async move { + let _permit = permit; + let mut resp = resolver.resolve(&q).await; + // Never send more than the client can take (also caps + // amplification); TC makes it retry over TCP. + if resp.len() > q.udp_size { + resp = q.truncated(); + } + if let Err(e) = sock.send_to(&resp, peer).await { + debug!(error = %e, "udp send"); + } + }); + } +} diff --git a/src/tls.rs b/src/tls.rs new file mode 100644 index 0000000..8b42e29 --- /dev/null +++ b/src/tls.rs @@ -0,0 +1,65 @@ +//! rustls configuration (ring provider, rustls' safe defaults: TLS 1.2/1.3, +//! AEAD-only cipher suites). + +use rustls::crypto::CryptoProvider; +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use rustls::{ClientConfig, RootCertStore, ServerConfig}; +use std::path::Path; +use std::sync::{Arc, OnceLock}; + +pub fn provider() -> Arc { + static P: OnceLock> = OnceLock::new(); + P.get_or_init(|| Arc::new(rustls::crypto::ring::default_provider())) + .clone() +} + +/// Cryptographically secure random u16 (for upstream query IDs). +pub fn random_u16() -> u16 { + let mut b = [0u8; 2]; + // Failure of the system RNG is not recoverable in any meaningful way. + provider().secure_random.fill(&mut b).expect("system RNG failure"); + u16::from_ne_bytes(b) +} + +fn load_certs(path: &Path) -> Result>, String> { + let certs = CertificateDer::pem_file_iter(path) + .and_then(|it| it.collect::, _>>()) + .map_err(|e| format!("{}: {e}", path.display()))?; + if certs.is_empty() { + return Err(format!("{}: no certificates found", path.display())); + } + Ok(certs) +} + +pub fn server_config(cert: &Path, key: &Path, alpn: &[&[u8]]) -> Result, String> { + let certs = load_certs(cert)?; + let key = PrivateKeyDer::from_pem_file(key).map_err(|e| format!("{}: {e}", key.display()))?; + let mut cfg = ServerConfig::builder_with_provider(provider()) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .with_no_client_auth() + .with_single_cert(certs, key) + .map_err(|e| format!("{}: {e}", cert.display()))?; + cfg.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect(); + Ok(Arc::new(cfg)) +} + +pub fn client_config(ca_file: Option<&Path>, alpn: &[&[u8]]) -> Result, String> { + let mut roots = RootCertStore::empty(); + match ca_file { + Some(p) => { + for c in load_certs(p)? { + roots.add(c).map_err(|e| format!("{}: {e}", p.display()))?; + } + } + None => roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()), + } + let mut cfg = ClientConfig::builder_with_provider(provider()) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .with_root_certificates(roots) + .with_no_client_auth(); + cfg.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect(); + Ok(Arc::new(cfg)) +} diff --git a/src/upstream/doh.rs b/src/upstream/doh.rs new file mode 100644 index 0000000..3523b1d --- /dev/null +++ b/src/upstream/doh.rs @@ -0,0 +1,151 @@ +//! DNS over HTTPS client (RFC 8484), HTTP/2 only, one multiplexed +//! connection per upstream that is re-established on failure. + +use super::{BoxError, connect_any}; +use crate::dns::MAX_MSG; +use crate::tls; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::body::Bytes; +use hyper::client::conn::http2::{self, SendRequest}; +use hyper::header::{ACCEPT, CONTENT_TYPE}; +use hyper::{Method, Request, StatusCode, Uri}; +use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; +use rustls::pki_types::ServerName; +use std::net::SocketAddr; +use std::path::Path; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::Duration; +use tokio::net::TcpStream; +use tokio::sync::Mutex; +use tokio_rustls::TlsConnector; +use tracing::debug; + +pub const DNS_MESSAGE: &str = "application/dns-message"; + +type Sender = SendRequest>; + +pub struct Doh { + uri: Uri, + name: ServerName<'static>, + addrs: Vec, + connector: TlsConnector, + /// Current connection, tagged with a generation so a failing request + /// only tears down the connection it actually used. + conn: Mutex>, + generation: AtomicU64, + next_addr: AtomicUsize, +} + +impl Doh { + pub fn new(url: &str, addrs: Vec, ca: Option<&Path>) -> Result { + let err = |m: &str| format!("upstream doh '{url}': {m}"); + let uri: Uri = url.parse().map_err(|_| err("invalid URL"))?; + if uri.scheme_str() != Some("https") { + return Err(err("scheme must be https")); + } + let auth = uri.authority().ok_or_else(|| err("missing host"))?; + if auth.as_str().contains('@') { + return Err(err("userinfo not allowed")); + } + if uri.path().is_empty() || uri.path() == "/" { + return Err(err("missing path (e.g. /dns-query)")); + } + if uri.query().is_some() { + return Err(err("query string not allowed")); + } + let host = auth.host().trim_start_matches('[').trim_end_matches(']'); + let name = ServerName::try_from(host.to_owned()).map_err(|e| err(&e.to_string()))?; + let cfg = tls::client_config(ca, &[b"h2"])?; + Ok(Self { + uri, + name, + addrs, + connector: TlsConnector::from(cfg), + conn: Mutex::new(None), + generation: AtomicU64::new(0), + next_addr: AtomicUsize::new(0), + }) + } + + pub async fn exchange(&self, msg: &[u8]) -> Result, BoxError> { + let (generation, mut sender) = self.sender().await?; + match self.send(&mut sender, msg).await { + Ok(r) => Ok(r), + Err(e) => { + let mut slot = self.conn.lock().await; + if matches!(&*slot, Some((g, _)) if *g == generation) { + *slot = None; + } + Err(e) + } + } + } + + async fn send(&self, sender: &mut Sender, msg: &[u8]) -> Result, BoxError> { + let req = Request::builder() + .method(Method::POST) + .uri(self.uri.clone()) + .header(CONTENT_TYPE, DNS_MESSAGE) + .header(ACCEPT, DNS_MESSAGE) + .body(Full::new(Bytes::copy_from_slice(msg)))?; + sender.ready().await?; + let resp = sender.send_request(req).await?; + if resp.status() != StatusCode::OK { + return Err(format!("HTTP status {}", resp.status()).into()); + } + let ct = resp.headers().get(CONTENT_TYPE).and_then(|v| v.to_str().ok()); + if !ct.is_some_and(is_dns_message) { + return Err("unexpected content-type".into()); + } + let body = Limited::new(resp.into_body(), MAX_MSG).collect().await?; + Ok(body.to_bytes().to_vec()) + } + + /// Returns the live connection or establishes a new one. The lock is + /// held while connecting so concurrent queries share one handshake. + async fn sender(&self) -> Result<(u64, Sender), BoxError> { + let mut slot = self.conn.lock().await; + if let Some((g, s)) = &*slot { + if !s.is_closed() { + return Ok((*g, s.clone())); + } + } + let s = self.connect().await?; + let g = self.generation.fetch_add(1, Ordering::Relaxed); + *slot = Some((g, s.clone())); + Ok((g, s)) + } + + async fn connect(&self) -> Result { + connect_any(&self.addrs, &self.next_addr, |a| self.connect_one(a)).await + } + + async fn connect_one(&self, addr: SocketAddr) -> Result { + let tcp = TcpStream::connect(addr).await?; + tcp.set_nodelay(true)?; + let tls = self.connector.connect(self.name.clone(), tcp).await?; + if tls.get_ref().1.alpn_protocol() != Some(b"h2") { + return Err("server did not negotiate HTTP/2".into()); + } + let (sender, conn) = http2::Builder::new(TokioExecutor::new()) + .timer(TokioTimer::new()) + // Detect dead connections while requests are outstanding. + .keep_alive_interval(Duration::from_secs(10)) + .keep_alive_timeout(Duration::from_secs(5)) + .handshake(TokioIo::new(tls)) + .await?; + tokio::spawn(async move { + if let Err(e) = conn.await { + debug!(error = %e, "doh upstream connection closed"); + } + }); + Ok(sender) + } +} + +/// `application/dns-message`, ignoring parameters and case. +pub fn is_dns_message(ct: &str) -> bool { + ct.split(';') + .next() + .is_some_and(|t| t.trim().eq_ignore_ascii_case(DNS_MESSAGE)) +} diff --git a/src/upstream/dot.rs b/src/upstream/dot.rs new file mode 100644 index 0000000..90d409f --- /dev/null +++ b/src/upstream/dot.rs @@ -0,0 +1,101 @@ +//! DNS over TLS client (RFC 7858) with a small pool of persistent +//! connections. Each connection carries one query at a time, which avoids +//! ID multiplexing and out-of-order handling entirely. + +use super::{BoxError, connect_any}; +use crate::frame::{read_frame, write_frame}; +use crate::tls; +use rustls::pki_types::ServerName; +use std::net::SocketAddr; +use std::path::Path; +use std::sync::Mutex; +use std::sync::atomic::AtomicUsize; +use std::time::{Duration, Instant}; +use tokio::net::TcpStream; +use tokio_rustls::TlsConnector; +use tokio_rustls::client::TlsStream; + +/// Pooled connections idle longer than this are discarded; most resolvers +/// close idle connections after ~10-30 s anyway. +const MAX_IDLE: Duration = Duration::from_secs(10); + +type Conn = TlsStream; + +pub struct Dot { + name: ServerName<'static>, + addrs: Vec, + connector: TlsConnector, + pool: Mutex>, + pool_size: usize, + next_addr: AtomicUsize, +} + +impl Dot { + pub fn new( + name: &str, + addrs: Vec, + ca: Option<&Path>, + pool_size: usize, + ) -> Result { + let name = + ServerName::try_from(name.to_owned()).map_err(|e| format!("upstream dot '{name}': {e}"))?; + // No ALPN: RFC 7858 does not require it and some servers reject + // unknown protocols. + let cfg = tls::client_config(ca, &[])?; + Ok(Self { + name, + addrs, + connector: TlsConnector::from(cfg), + pool: Mutex::new(Vec::new()), + pool_size, + next_addr: AtomicUsize::new(0), + }) + } + + pub async fn exchange(&self, msg: &[u8]) -> Result, BoxError> { + // A pooled connection may have been closed by the server in the + // meantime; on failure fall through to a fresh connection. + if let Some(mut c) = self.checkout() { + if let Ok(r) = roundtrip(&mut c, msg).await { + self.checkin(c); + return Ok(r); + } + } + let mut c = self.connect().await?; + let r = roundtrip(&mut c, msg).await?; + self.checkin(c); + Ok(r) + } + + fn checkout(&self) -> Option { + let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner()); + while let Some((c, since)) = pool.pop() { + if since.elapsed() < MAX_IDLE { + return Some(c); + } + } + None + } + + fn checkin(&self, c: Conn) { + let mut pool = self.pool.lock().unwrap_or_else(|e| e.into_inner()); + if pool.len() < self.pool_size { + pool.push((c, Instant::now())); + } + } + + async fn connect(&self) -> Result { + connect_any(&self.addrs, &self.next_addr, |a| self.connect_one(a)).await + } + + async fn connect_one(&self, addr: SocketAddr) -> Result { + let tcp = TcpStream::connect(addr).await?; + tcp.set_nodelay(true)?; + Ok(self.connector.connect(self.name.clone(), tcp).await?) + } +} + +async fn roundtrip(c: &mut Conn, msg: &[u8]) -> Result, BoxError> { + write_frame(c, msg).await?; + read_frame(c).await?.ok_or_else(|| "connection closed".into()) +} diff --git a/src/upstream/mod.rs b/src/upstream/mod.rs new file mode 100644 index 0000000..98a396c --- /dev/null +++ b/src/upstream/mod.rs @@ -0,0 +1,157 @@ +//! Encrypted upstreams (DoT, DoH) and ordered failover between them. + +pub(crate) mod doh; +mod dot; + +use crate::config::{self, Limits, UpstreamKind}; +use crate::dns::{self, Query}; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; +use tokio::time::timeout; +use tracing::{debug, info, warn}; + +pub type BoxError = Box; + +/// How long a failed upstream is moved to the end of the try order. +const PENALTY: Duration = Duration::from_secs(30); + +enum Kind { + Dot(dot::Dot), + Doh(doh::Doh), +} + +struct Upstream { + label: String, + kind: Kind, + /// Milliseconds since `Resolver::epoch` until which this upstream is + /// deprioritised; 0 = healthy. + penalised_until: AtomicU64, +} + +impl Upstream { + async fn exchange(&self, q: &Query) -> Result, BoxError> { + // RFC 8484 recommends ID 0 for DoH (HTTP caching); DoT gets a fresh + // random ID so the client's ID never leaves this host. + let id = match self.kind { + Kind::Dot(_) => crate::tls::random_u16(), + Kind::Doh(_) => 0, + }; + let msg = q.with_id(id); + let mut resp = match &self.kind { + Kind::Dot(d) => d.exchange(&msg).await?, + Kind::Doh(d) => d.exchange(&msg).await?, + }; + if dns::id(&resp) != Some(id) || !q.is_answered_by(&resp) { + return Err("response does not match query".into()); + } + dns::set_id(&mut resp, q.id); + Ok(resp) + } +} + +pub struct Resolver { + upstreams: Vec, + attempt_timeout: Duration, + deadline: Duration, + epoch: Instant, +} + +impl Resolver { + pub fn new(cfgs: &[config::Upstream], limits: &Limits) -> Result { + let mut upstreams = Vec::with_capacity(cfgs.len()); + for c in cfgs { + let ca = c.ca_file.as_deref().map(config::expand_path).transpose()?; + let (label, kind) = match c.kind { + UpstreamKind::Dot => { + let name = c.name.clone().unwrap_or_default(); + let d = dot::Dot::new(&name, c.addrs.clone(), ca.as_deref(), limits.dot_pool_size)?; + (format!("dot://{name}"), Kind::Dot(d)) + } + UpstreamKind::Doh => { + let url = c.url.clone().unwrap_or_default(); + let d = doh::Doh::new(&url, c.addrs.clone(), ca.as_deref())?; + (url, Kind::Doh(d)) + } + }; + upstreams.push(Upstream { + label, + kind, + penalised_until: AtomicU64::new(0), + }); + } + Ok(Self { + upstreams, + attempt_timeout: limits.upstream_timeout(), + deadline: limits.query_timeout(), + epoch: Instant::now(), + }) + } + + fn now_ms(&self) -> u64 { + u64::try_from(self.epoch.elapsed().as_millis()).unwrap_or(u64::MAX) + } + + /// Resolves `q` via the first upstream that answers. Always returns a + /// response for the client: SERVFAIL if every upstream fails. + pub async fn resolve(&self, q: &Query) -> Vec { + let attempts = async { + let now = self.now_ms(); + let healthy = |u: &&Upstream| u.penalised_until.load(Ordering::Relaxed) <= now; + // Fixed up front: penalties set during this loop must not make + // an upstream reappear in the same resolution. + let order: Vec<&Upstream> = self + .upstreams + .iter() + .filter(healthy) + .chain(self.upstreams.iter().filter(|u| !healthy(u))) + .collect(); + for u in order { + let err = match timeout(self.attempt_timeout, u.exchange(q)).await { + Ok(Ok(resp)) => { + if u.penalised_until.swap(0, Ordering::Relaxed) != 0 { + info!(upstream = %u.label, "upstream recovered"); + } + return Some(resp); + } + Ok(Err(e)) => e.to_string(), + Err(_) => "timed out".to_string(), + }; + let until = self.now_ms().saturating_add(PENALTY.as_millis() as u64); + // Warn once per outage, not once per query. + if u.penalised_until.swap(until, Ordering::Relaxed) <= now { + warn!(upstream = %u.label, error = %err, "upstream failed, deprioritised for 30 s"); + } else { + debug!(upstream = %u.label, error = %err, "upstream still failing"); + } + } + None + }; + match timeout(self.deadline, attempts).await { + Ok(Some(resp)) => resp, + _ => { + debug!("all upstreams failed, answering SERVFAIL"); + q.servfail() + } + } + } +} + +/// Connects to the first reachable bootstrap address, starting at a +/// rotating offset to spread load. Reports every address's error. +async fn connect_any(addrs: &[SocketAddr], next: &AtomicUsize, connect: F) -> Result +where + F: Fn(SocketAddr) -> Fut, + Fut: Future>, +{ + let start = next.fetch_add(1, Ordering::Relaxed); + let mut errors = Vec::with_capacity(addrs.len()); + for i in 0..addrs.len() { + let addr = addrs[(start + i) % addrs.len()]; + match connect(addr).await { + Ok(t) => return Ok(t), + Err(e) => errors.push(format!("{addr}: {e}")), + } + } + Err(errors.join("; ").into()) +} diff --git a/tests/e2e.rs b/tests/e2e.rs new file mode 100644 index 0000000..e484b3d --- /dev/null +++ b/tests/e2e.rs @@ -0,0 +1,699 @@ +//! End-to-end tests: fake DoT/DoH upstreams with a test CA, the proxy in +//! between, and clients for every inbound protocol. + +use dns_proxy::config::{Config, Proto}; +use http_body_util::{BodyExt, Full}; +use hyper::body::{Bytes, Incoming}; +use hyper::{Request, Response, StatusCode}; +use hyper_util::rt::{TokioExecutor, TokioIo}; +use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair}; +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName}; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream, UdpSocket}; +use tokio::time::timeout; +use tokio_rustls::{TlsAcceptor, TlsConnector}; + +// ---------------------------------------------------------------- PKI + +struct Pki { + dir: PathBuf, + ca_params: CertificateParams, + ca_key: KeyPair, + ca_file: PathBuf, +} + +impl Pki { + fn new() -> Self { + static N: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir().join(format!( + "dns-proxy-test-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let ca_key = KeyPair::generate().unwrap(); + let ca = ca_params.self_signed(&ca_key).unwrap(); + let ca_file = dir.join("ca.pem"); + std::fs::write(&ca_file, ca.pem()).unwrap(); + Self { + dir, + ca_params, + ca_key, + ca_file, + } + } + + /// Leaf certificate for `name`, returns (cert path, key path). + fn leaf(&self, name: &str) -> (PathBuf, PathBuf) { + let key = KeyPair::generate().unwrap(); + let params = CertificateParams::new(vec![name.to_string()]).unwrap(); + let issuer = Issuer::from_params(&self.ca_params, &self.ca_key); + let cert = params.signed_by(&key, &issuer).unwrap(); + let c = self.dir.join(format!("{name}.crt")); + let k = self.dir.join(format!("{name}.key")); + std::fs::write(&c, cert.pem()).unwrap(); + std::fs::write(&k, key.serialize_pem()).unwrap(); + (c, k) + } + + fn acceptor(&self, name: &str, alpn: &[&[u8]]) -> TlsAcceptor { + let (c, k) = self.leaf(name); + let certs = CertificateDer::pem_file_iter(&c) + .unwrap() + .map(Result::unwrap) + .collect(); + let key = PrivateKeyDer::from_pem_file(&k).unwrap(); + let mut cfg = + rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(certs, key) + .unwrap(); + cfg.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect(); + TlsAcceptor::from(Arc::new(cfg)) + } + + fn connector(&self, alpn: &[&[u8]]) -> TlsConnector { + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_file_iter(&self.ca_file).unwrap() { + roots.add(c.unwrap()).unwrap(); + } + let mut cfg = + rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + cfg.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect(); + TlsConnector::from(Arc::new(cfg)) + } +} + +impl Drop for Pki { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +// ---------------------------------------------------------------- DNS helpers + +fn query(id: u16, name: &str, edns: Option) -> Vec { + let mut m = Vec::new(); + m.extend_from_slice(&id.to_be_bytes()); + m.extend_from_slice(&[0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, u8::from(edns.is_some())]); + for l in name.split('.') { + m.push(l.len() as u8); + m.extend_from_slice(l.as_bytes()); + } + m.extend_from_slice(&[0, 0, 1, 0, 1]); + if let Some(size) = edns { + m.extend_from_slice(&[0, 0, 41]); + m.extend_from_slice(&size.to_be_bytes()); + m.extend_from_slice(&[0, 0, 0, 0, 0, 0]); + } + m +} + +/// Fake authoritative answer: 1.2.3.4, or 60 A records for names +/// starting with "big" (≈ 1 KB, beyond the 512-byte UDP default). +fn answer(q: &[u8]) -> Vec { + let mut off = 12; + while q[off] != 0 { + off += 1 + q[off] as usize; + } + let qend = off + 5; + let big = q[13..16] == *b"big"; + let n: u16 = if big { 60 } else { 1 }; + let mut r = Vec::new(); + r.extend_from_slice(&q[0..2]); + r.extend_from_slice(&[0x81, 0x80, 0, 1]); + r.extend_from_slice(&n.to_be_bytes()); + r.extend_from_slice(&[0, 0, 0, 0]); + r.extend_from_slice(&q[12..qend]); + for i in 0..n { + r.extend_from_slice(&[0xC0, 0x0C, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 1, 2, 3]); + r.push(if big { i as u8 } else { 4 }); + } + r +} + +fn rcode(r: &[u8]) -> u8 { + r[3] & 0x0F +} + +fn ancount(r: &[u8]) -> u16 { + u16::from_be_bytes([r[6], r[7]]) +} + +fn assert_answer(r: &[u8], id: u16) { + assert_eq!(u16::from_be_bytes([r[0], r[1]]), id, "client ID restored"); + assert_eq!(rcode(r), 0); + assert_eq!(ancount(r), 1); + assert_eq!(&r[r.len() - 4..], &[1, 2, 3, 4]); +} + +// ---------------------------------------------------------------- fake upstreams + +async fn fake_dot(pki: &Pki, name: &str) -> SocketAddr { + let acc = pki.acceptor(name, &[]); + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let (tcp, _) = l.accept().await.unwrap(); + let acc = acc.clone(); + tokio::spawn(async move { + let Ok(mut s) = acc.accept(tcp).await else { return }; + loop { + let Ok(len) = s.read_u16().await else { return }; + let mut q = vec![0; len as usize]; + if s.read_exact(&mut q).await.is_err() { + return; + } + let a = answer(&q); + let mut out = (a.len() as u16).to_be_bytes().to_vec(); + out.extend_from_slice(&a); + if s.write_all(&out).await.is_err() { + return; + } + } + }); + } + }); + addr +} + +async fn fake_doh(pki: &Pki, name: &str) -> SocketAddr { + let acc = pki.acceptor(name, &[b"h2"]); + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let (tcp, _) = l.accept().await.unwrap(); + let acc = acc.clone(); + tokio::spawn(async move { + let Ok(s) = acc.accept(tcp).await else { return }; + let svc = hyper::service::service_fn(|req: Request| async move { + let ok = req.method() == hyper::Method::POST + && req.uri().path() == "/dns-query" + && req.headers()["content-type"] == "application/dns-message"; + let body = req.into_body().collect().await.unwrap().to_bytes(); + // RFC 8484: the proxy must send ID 0. + let mut resp = if ok && body[0..2] == [0, 0] { + let mut r = Response::new(Full::new(Bytes::from(answer(&body)))); + r.headers_mut() + .insert("content-type", "application/dns-message".parse().unwrap()); + r + } else { + Response::new(Full::default()) + }; + if !ok { + *resp.status_mut() = StatusCode::BAD_REQUEST; + } + Ok::<_, std::convert::Infallible>(resp) + }); + let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new()) + .serve_connection(TokioIo::new(s), svc) + .await; + }); + } + }); + addr +} + +/// Accepts TCP connections and closes them at once, counting attempts. +async fn closing_upstream(count: Arc) -> SocketAddr { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let (tcp, _) = l.accept().await.unwrap(); + count.fetch_add(1, Ordering::SeqCst); + drop(tcp); + } + }); + addr +} + +async fn dead_addr() -> SocketAddr { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + l.local_addr().unwrap() +} + +// ---------------------------------------------------------------- proxy + clients + +struct Running { + _proxy: dns_proxy::Proxy, + udp: SocketAddr, + tcp: SocketAddr, + dot: SocketAddr, + doh: SocketAddr, +} + +async fn start_proxy(pki: &Pki, upstreams: &str, allow: &str) -> Running { + let (c, k) = pki.leaf("localhost"); + let (c, k) = (c.display(), k.display()); + let toml = format!( + r#" + [limits] + upstream_timeout_ms = 1000 + query_timeout_ms = 3000 + + [[listen]] + proto = "udp" + addr = "127.0.0.1:0" + allow = [{allow}] + + [[listen]] + proto = "tcp" + addr = "127.0.0.1:0" + allow = [{allow}] + + [[listen]] + proto = "dot" + addr = "127.0.0.1:0" + allow = [{allow}] + cert = "{c}" + key = "{k}" + + [[listen]] + proto = "doh" + addr = "127.0.0.1:0" + allow = [{allow}] + cert = "{c}" + key = "{k}" + + {upstreams} + "# + ); + let cfg = Config::parse(&toml).unwrap(); + let proxy = dns_proxy::start(cfg).await.unwrap(); + let get = |p: Proto| proxy.bound.iter().find(|(x, _)| *x == p).unwrap().1; + Running { + udp: get(Proto::Udp), + tcp: get(Proto::Tcp), + dot: get(Proto::Dot), + doh: get(Proto::Doh), + _proxy: proxy, + } +} + +fn dot_upstream(pki: &Pki, name: &str, addr: SocketAddr) -> String { + format!( + "[[upstream]]\ntype = \"dot\"\nname = \"{name}\"\naddrs = [\"{addr}\"]\nca_file = \"{}\"\n", + pki.ca_file.display() + ) +} + +fn doh_upstream(pki: &Pki, name: &str, addr: SocketAddr) -> String { + format!( + "[[upstream]]\ntype = \"doh\"\nurl = \"https://{name}/dns-query\"\naddrs = [\"{addr}\"]\nca_file = \"{}\"\n", + pki.ca_file.display() + ) +} + +const LOCAL: &str = "\"127.0.0.0/8\""; + +async fn udp_query(addr: SocketAddr, msg: &[u8], wait: Duration) -> Option> { + let s = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + s.send_to(msg, addr).await.unwrap(); + let mut buf = vec![0; 65535]; + let n = timeout(wait, s.recv(&mut buf)).await.ok()?.unwrap(); + buf.truncate(n); + Some(buf) +} + +async fn framed(s: &mut S, msg: &[u8]) -> Option> { + let mut out = (msg.len() as u16).to_be_bytes().to_vec(); + out.extend_from_slice(msg); + s.write_all(&out).await.ok()?; + let len = timeout(Duration::from_secs(5), s.read_u16()).await.ok()?.ok()?; + let mut buf = vec![0; len as usize]; + s.read_exact(&mut buf).await.ok()?; + Some(buf) +} + +async fn tcp_query(addr: SocketAddr, msg: &[u8]) -> Option> { + let mut s = TcpStream::connect(addr).await.ok()?; + framed(&mut s, msg).await +} + +async fn dot_query(pki: &Pki, addr: SocketAddr, msg: &[u8]) -> Option> { + let tcp = TcpStream::connect(addr).await.unwrap(); + let mut s = pki + .connector(&[b"dot"]) + .connect(ServerName::try_from("localhost").unwrap(), tcp) + .await + .unwrap(); + framed(&mut s, msg).await +} + +/// Sends one DoH request over HTTP/2; returns status and body. +async fn doh(pki: &Pki, addr: SocketAddr, req: Request>) -> (StatusCode, Vec) { + let tcp = TcpStream::connect(addr).await.unwrap(); + let tls = pki + .connector(&[b"h2"]) + .connect(ServerName::try_from("localhost").unwrap(), tcp) + .await + .unwrap(); + let (mut send, conn) = hyper::client::conn::http2::handshake(TokioExecutor::new(), TokioIo::new(tls)) + .await + .unwrap(); + tokio::spawn(conn); + let resp = send.send_request(req).await.unwrap(); + let status = resp.status(); + let body = resp.into_body().collect().await.unwrap().to_bytes().to_vec(); + (status, body) +} + +fn post(path: &str, ct: &str, body: Vec) -> Request> { + Request::post(format!("https://localhost{path}")) + .header("content-type", ct) + .body(Full::new(Bytes::from(body))) + .unwrap() +} + +fn get(query: &str) -> Request> { + Request::get(format!("https://localhost/dns-query?{query}")) + .body(Full::default()) + .unwrap() +} + +fn b64url(b: &[u8]) -> String { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b) +} + +const WAIT: Duration = Duration::from_secs(5); + +// ---------------------------------------------------------------- tests + +#[tokio::test] +async fn all_inbound_protocols_via_dot_upstream() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + + assert_answer( + &udp_query(p.udp, &query(0x1001, "example.com", None), WAIT) + .await + .unwrap(), + 0x1001, + ); + assert_answer( + &tcp_query(p.tcp, &query(0x1002, "example.com", None)) + .await + .unwrap(), + 0x1002, + ); + assert_answer( + &dot_query(&pki, p.dot, &query(0x1003, "example.com", None)) + .await + .unwrap(), + 0x1003, + ); + let (st, body) = doh( + &pki, + p.doh, + post( + "/dns-query", + "application/dns-message", + query(0, "example.com", None), + ), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_answer(&body, 0); + let (st, body) = doh( + &pki, + p.doh, + get(&format!("dns={}", b64url(&query(0, "example.com", None)))), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_answer(&body, 0); +} + +#[tokio::test] +async fn via_doh_upstream() { + let pki = Pki::new(); + let up = fake_doh(&pki, "upstream.test").await; + let p = start_proxy(&pki, &doh_upstream(&pki, "upstream.test", up), LOCAL).await; + for id in [0x2001, 0x2002, 0x2003] { + assert_answer( + &udp_query(p.udp, &query(id, "example.com", None), WAIT) + .await + .unwrap(), + id, + ); + } + assert_answer( + &dot_query(&pki, p.dot, &query(0x2004, "example.com", None)) + .await + .unwrap(), + 0x2004, + ); +} + +#[tokio::test] +async fn pipelined_tcp_queries() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + let mut s = TcpStream::connect(p.tcp).await.unwrap(); + let mut out = Vec::new(); + for id in 1..=10u16 { + let q = query(id, "example.com", None); + out.extend_from_slice(&(q.len() as u16).to_be_bytes()); + out.extend_from_slice(&q); + } + s.write_all(&out).await.unwrap(); + let mut ids = Vec::new(); + for _ in 0..10 { + let len = s.read_u16().await.unwrap(); + let mut buf = vec![0; len as usize]; + s.read_exact(&mut buf).await.unwrap(); + assert_eq!(ancount(&buf), 1); + ids.push(u16::from_be_bytes([buf[0], buf[1]])); + } + ids.sort(); + assert_eq!(ids, (1..=10).collect::>()); +} + +#[tokio::test] +async fn failover_to_second_upstream() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let dead = dead_addr().await; + let ups = dot_upstream(&pki, "upstream.test", dead) + &dot_upstream(&pki, "upstream.test", up); + let p = start_proxy(&pki, &ups, LOCAL).await; + assert_answer( + &udp_query(p.udp, &query(0x3001, "example.com", None), WAIT) + .await + .unwrap(), + 0x3001, + ); + // Second query skips the penalised upstream. + assert_answer( + &udp_query(p.udp, &query(0x3002, "example.com", None), WAIT) + .await + .unwrap(), + 0x3002, + ); +} + +#[tokio::test] +async fn servfail_when_all_upstreams_fail() { + let pki = Pki::new(); + let dead = dead_addr().await; + let p = start_proxy(&pki, &doh_upstream(&pki, "upstream.test", dead), LOCAL).await; + let r = udp_query(p.udp, &query(0x4001, "example.com", None), WAIT) + .await + .unwrap(); + assert_eq!(u16::from_be_bytes([r[0], r[1]]), 0x4001); + assert_eq!(rcode(&r), 2); +} + +#[tokio::test] +async fn each_upstream_tried_once_per_query() { + let pki = Pki::new(); + let count = Arc::new(AtomicUsize::new(0)); + let a = closing_upstream(count.clone()).await; + let b = closing_upstream(count.clone()).await; + let ups = dot_upstream(&pki, "upstream.test", a) + &dot_upstream(&pki, "upstream.test", b); + let p = start_proxy(&pki, &ups, LOCAL).await; + let r = udp_query(p.udp, &query(0x4101, "example.com", None), WAIT) + .await + .unwrap(); + assert_eq!(rcode(&r), 2); + assert_eq!(count.load(Ordering::SeqCst), 2); +} + +#[tokio::test] +async fn upstream_certificate_is_verified() { + let pki = Pki::new(); + // Upstream presents a certificate for a different name. + let up = fake_dot(&pki, "evil.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + let r = udp_query(p.udp, &query(0x5001, "example.com", None), WAIT) + .await + .unwrap(); + assert_eq!(rcode(&r), 2); + // Same for a CA the proxy does not trust. + let other = Pki::new(); + let up = fake_doh(&other, "upstream.test").await; + let p = start_proxy(&pki, &doh_upstream(&pki, "upstream.test", up), LOCAL).await; + let r = udp_query(p.udp, &query(0x5002, "example.com", None), WAIT) + .await + .unwrap(); + assert_eq!(rcode(&r), 2); +} + +#[tokio::test] +async fn acl_rejects_other_clients() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), "\"10.0.0.0/8\"").await; + assert!( + udp_query(p.udp, &query(1, "example.com", None), Duration::from_millis(500)) + .await + .is_none() + ); + assert!(tcp_query(p.tcp, &query(1, "example.com", None)).await.is_none()); +} + +#[tokio::test] +async fn udp_truncation() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + + let r = udp_query(p.udp, &query(0x6001, "big.example", None), WAIT) + .await + .unwrap(); + assert!(r.len() <= 512); + assert_ne!(r[2] & 0x02, 0, "TC set"); + assert_eq!(ancount(&r), 0); + + let r = udp_query(p.udp, &query(0x6002, "big.example", Some(1232)), WAIT) + .await + .unwrap(); + assert_eq!(r[2] & 0x02, 0); + assert_eq!(ancount(&r), 60); + + let r = tcp_query(p.tcp, &query(0x6003, "big.example", None)) + .await + .unwrap(); + assert_eq!(ancount(&r), 60); +} + +#[tokio::test] +async fn invalid_queries_are_dropped() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + let mut resp = query(1, "example.com", None); + resp[2] |= 0x80; // QR set: a response, not a query + assert!( + udp_query(p.udp, &resp, Duration::from_millis(500)) + .await + .is_none() + ); + assert!( + udp_query(p.udp, &[0; 5], Duration::from_millis(500)) + .await + .is_none() + ); +} + +#[tokio::test] +async fn doh_request_errors() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + let q = query(0, "example.com", None); + + let (st, _) = doh(&pki, p.doh, post("/other", "application/dns-message", q.clone())).await; + assert_eq!(st, StatusCode::NOT_FOUND); + let (st, _) = doh(&pki, p.doh, post("/dns-query", "text/plain", q.clone())).await; + assert_eq!(st, StatusCode::UNSUPPORTED_MEDIA_TYPE); + let (st, _) = doh( + &pki, + p.doh, + post("/dns-query", "application/dns-message", vec![1, 2, 3]), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); + let (st, _) = doh( + &pki, + p.doh, + post("/dns-query", "application/dns-message", vec![0; 70_000]), + ) + .await; + assert_eq!(st, StatusCode::PAYLOAD_TOO_LARGE); + let (st, _) = doh(&pki, p.doh, get("dns=!!!")).await; + assert_eq!(st, StatusCode::BAD_REQUEST); + let (st, _) = doh(&pki, p.doh, get("foo=bar")).await; + assert_eq!(st, StatusCode::BAD_REQUEST); + let put = Request::put("https://localhost/dns-query") + .body(Full::default()) + .unwrap(); + let (st, _) = doh(&pki, p.doh, put).await; + assert_eq!(st, StatusCode::METHOD_NOT_ALLOWED); +} + +#[tokio::test] +async fn doh_over_http1() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let p = start_proxy(&pki, &dot_upstream(&pki, "upstream.test", up), LOCAL).await; + let tcp = TcpStream::connect(p.doh).await.unwrap(); + let tls = pki + .connector(&[b"http/1.1"]) + .connect(ServerName::try_from("localhost").unwrap(), tcp) + .await + .unwrap(); + let (mut send, conn) = hyper::client::conn::http1::handshake(TokioIo::new(tls)) + .await + .unwrap(); + tokio::spawn(conn); + let req = Request::post("/dns-query") + .header("host", "localhost") + .header("content-type", "application/dns-message") + .body(Full::new(Bytes::from(query(0x7001, "example.com", None)))) + .unwrap(); + let resp = send.send_request(req).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body = resp.into_body().collect().await.unwrap().to_bytes(); + assert_answer(&body, 0x7001); +} + +#[tokio::test] +async fn check_rejects_missing_certificate() { + let cfg = Config::parse( + r#" + [[listen]] + proto = "dot" + addr = "127.0.0.1:0" + allow = ["127.0.0.0/8"] + cert = "/nonexistent/cert.pem" + key = "/nonexistent/key.pem" + + [[upstream]] + type = "dot" + name = "dns.example" + addrs = ["192.0.2.1:853"] + "#, + ) + .unwrap(); + assert!(dns_proxy::check(&cfg).is_err()); +} From 27fa2b5e8dafe75511756362c8312d4ef282fa3d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 16:09:07 +0000 Subject: [PATCH 2/3] Allow clients by hostname (DynDNS) and document secret DoH paths Clients with dynamic public IPs can now be admitted via `allow_hosts`. Names are resolved in the background through the encrypted upstreams (never via the system resolver, never per packet); the packet path only reads the last known addresses. - A/AAAA lookups with TTL-driven refresh, clamped by [host_acl] - Rejected clients trigger an early, rate-limited refresh - Fail closed until the first lookup; NXDOMAIN/NODATA clears at once; on lookup failures the last addresses stay valid for max_stale - IPv4 matches /32, IPv6 /64 by default (per-host v4_prefix/v6_prefix, bounded to avoid accidental wide ranges) - Startup warning for allow_hosts on plain udp/tcp listeners - Minimal A/AAAA answer parsing in dns.rs, bounds-checked and fuzzed - Constant-time DoH path comparison so the path can carry a secret - README: threat model for DynDNS admission and the secret-path option Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011hHaUEqQpj7pg7F9XAM8Ce --- README.md | 61 +++++++++- config.example.toml | 28 +++++ src/acl.rs | 65 ++++++++-- src/config.rs | 162 ++++++++++++++++++++++++- src/dns.rs | 290 +++++++++++++++++++++++++++++++++++++++++++- src/hosts.rs | 247 +++++++++++++++++++++++++++++++++++++ src/lib.rs | 65 +++++++++- src/server/doh.rs | 25 +++- tests/e2e.rs | 248 +++++++++++++++++++++++++++++++++++-- 9 files changed, 1159 insertions(+), 32 deletions(-) create mode 100644 src/hosts.rs diff --git a/README.md b/README.md index d8e90be..71ecbad 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,9 @@ clients ── plain DNS (UDP/TCP) ─┐ ## Security properties -- **Closed by default.** Every listener requires an explicit `allow` CIDR list. An open resolver needs a deliberate `"0.0.0.0/0"` / `"::/0"`. +- **Closed by default.** Every listener requires an explicit `allow` CIDR list and/or `allow_hosts` hostnames. An open resolver needs a deliberate `"0.0.0.0/0"` / `"::/0"`. - **No plain-DNS bootstrap.** Upstream hostnames are never resolved. You configure their IPs (`addrs`). The hostname is used only for SNI and certificate verification, so nothing goes in circles and nothing leaks. +- **No system resolver.** `allow_hosts` names are resolved through the encrypted upstreams, in the background. The packet path only reads addresses that are already known. - **Verified TLS.** Uses rustls (ring provider, TLS 1.2/1.3, AEAD suites only). Upstream certificates are verified against the built-in Mozilla roots (`webpki-roots`) or a `ca_file` you supply. - **Validated responses.** Upstream responses must match the query's question and ID. - DoT queries get a fresh random ID, so the client's ID never leaves the host. @@ -48,9 +49,10 @@ See [`config.example.toml`](config.example.toml) for all options. Summary: | Section | Keys | |---|---| -| `[[listen]]` | `proto` (`udp` \| `tcp` \| `dot` \| `doh`), `addr`, `allow`. For `dot`/`doh` also `cert`, `key`; for `doh` optionally `path` (default `/dns-query`). | +| `[[listen]]` | `proto` (`udp` \| `tcp` \| `dot` \| `doh`), `addr`, `allow` and/or `allow_hosts`. For `dot`/`doh` also `cert`, `key`; for `doh` optionally `path` (default `/dns-query`). | | `[[upstream]]` | `type = "dot"`: `name`, `addrs`. `type = "doh"`: `url`, `addrs`. Optional `ca_file`. | | `[limits]` | Concurrency limits and timeouts (all optional). | +| `[host_acl]` | Refresh timing for `allow_hosts` (all optional). | Notes: @@ -58,6 +60,58 @@ Notes: - **Certificate paths.** In certificate paths, `${CREDENTIALS_DIRECTORY}` is expanded (systemd `LoadCredential=`). No other variables are. - **Logging.** Set the log level with `RUST_LOG` (default `info`), e.g. `RUST_LOG=debug`. +## Dynamic client IPs + +A typical deployment: clients on networks with a dynamic public IP (home, branch office) use the proxy over the internet. The upstreams then see only the proxy's static IP, which they may use for policy (filtering profiles, allowlists, logging). + +There are two ways to admit such clients. + +### `allow_hosts`: admission by DynDNS name + +```toml +allow_hosts = ["home.dyndns.example", { name = "office.dyndns.example", v6_prefix = 56 }] +``` + +How resolution works: + +- **Background refresh.** Names are resolved through the configured upstreams, with an A and an AAAA query each. +- **Refresh interval.** It follows the record TTL, clamped to `[host_acl] refresh_min_ms`/`refresh_max_ms`. +- **Refresh on reject.** A rejected client triggers an early refresh, at most every `trigger_min_interval_ms`. This shortens the window after an IP change. +- **Fail closed.** Until the first successful lookup, a name admits nobody. +- **Answers replace state.** A new address replaces the old one immediately. NXDOMAIN or an empty answer removes the addresses at once. +- **Lookup failures.** If lookups fail (SERVFAIL, timeouts), the last known addresses stay valid for `max_stale_ms` (default 1 h). +- **Prefixes.** IPv4 addresses match exactly by default (`v4_prefix = 32`). IPv6 addresses match their /64 (`v6_prefix = 64`). + +What you are trusting: + +- **The DynDNS account is now the credential.** Whoever can update the record can admit any address. Protect the account (strong password, 2FA, a per-host update token). +- **CGNAT / DS-Lite:** if the client's public IPv4 is shared, you admit everyone behind it. Don't use `allow_hosts` for such connections, or only for their IPv6. +- **IPv6:** the AAAA record must lie in the prefix the clients use. Many routers publish their WAN address instead, which may sit in a different /64 than the LAN. Check before relying on it, and widen `v6_prefix` (e.g. 56) only as far as your delegated prefix. +- **Timing:** after an IP change, the client is rejected until the DynDNS record is updated and the proxy has refreshed. Meanwhile, the old address stays admitted until the next refresh. It may already belong to someone else. +- **Integrity:** the proxy does not validate DNSSEC. It relies on the upstream resolver, which it reaches over authenticated TLS. Upstreams such as Quad9 and Cloudflare validate DNSSEC, which protects signed DynDNS zones. +- **Use DoT/DoH for such listeners.** On plain UDP, an attacker can spoof the admitted address and reflect responses to it. Plain DNS across the internet is also readable by every network in between, which defeats the purpose of encrypted upstreams. The proxy logs a warning at startup for `allow_hosts` on `udp`/`tcp` listeners. + +### Secret DoH path: admission by token + +IP-based admission is weak authentication. If the clients speak DoH (browsers, Apple/Android profiles, many routers), a secret path works regardless of the client's address: + +```toml +[[listen]] +proto = "doh" +addr = "0.0.0.0:443" +allow = ["0.0.0.0/0", "::/0"] +cert = "${CREDENTIALS_DIRECTORY}/cert.pem" +key = "${CREDENTIALS_DIRECTORY}/key.pem" +path = "/dns-query/" +``` + +How the token is protected: + +- **In transit:** the path travels inside TLS. +- **On the server:** the proxy compares it in constant time and does not log it. +- **Wrong token:** a request with a wrong path gets a plain 404. +- **Its weak spot:** the client configuration. Treat it like a password. + ## Run with systemd [`dist/dns-proxy.service`](dist/dns-proxy.service) runs the proxy as a transient unprivileged user (`DynamicUser=`). Its only capability is `CAP_NET_BIND_SERVICE`. It also enables a strict sandbox: read-only filesystem, a syscall filter, no new privileges, and more. @@ -90,7 +144,8 @@ The end-to-end tests start fake DoT and DoH upstreams with a throwaway CA and qu - failover, and SERVFAIL when every upstream fails - certificate verification -- the allowlist +- the allowlist, including `allow_hosts`: address changes, refresh on reject, stale handling and NXDOMAIN +- the secret DoH path - UDP truncation - TCP pipelining - DoH error handling diff --git a/config.example.toml b/config.example.toml index e0e6691..7909104 100644 --- a/config.example.toml +++ b/config.example.toml @@ -12,6 +12,14 @@ upstream_timeout_ms = 2000 # one attempt against one upstream query_timeout_ms = 5000 # overall, across failover attempts dot_pool_size = 8 # idle connections kept per DoT upstream +# Resolution of 'allow_hosts' names (optional; defaults shown). Names are +# resolved in the background through the upstreams below, never per query. +[host_acl] +refresh_min_ms = 30000 # lower bound of the refresh interval (TTL is clamped) +refresh_max_ms = 300000 # upper bound +max_stale_ms = 3600000 # keep last known addresses this long while lookups fail +trigger_min_interval_ms = 15000 # a rejected client triggers a refresh at most this often + # --- Inbound ----------------------------------------------------------------- [[listen]] @@ -37,10 +45,19 @@ allow = ["::1/128"] # DoT and DoH need a certificate. With the shipped systemd unit, use # LoadCredential= and reference the files via ${CREDENTIALS_DIRECTORY}. # +# Clients with dynamic public IPs can be admitted by hostname (DynDNS). +# A records match exactly (/32 by default); AAAA records match their /64 +# by default, since LAN clients use other addresses of the same prefix. +# See README, "Dynamic client IPs", for the security trade-offs. +# # [[listen]] # proto = "dot" # addr = "0.0.0.0:853" # allow = ["192.168.0.0/16", "10.0.0.0/8"] +# allow_hosts = [ +# "home.dyndns.example", +# { name = "office.dyndns.example", v6_prefix = 56 }, +# ] # cert = "${CREDENTIALS_DIRECTORY}/cert.pem" # key = "${CREDENTIALS_DIRECTORY}/key.pem" # @@ -51,6 +68,17 @@ allow = ["::1/128"] # cert = "${CREDENTIALS_DIRECTORY}/cert.pem" # key = "${CREDENTIALS_DIRECTORY}/key.pem" # path = "/dns-query" +# +# Alternative to IP-based admission: a DoH endpoint behind a secret path, +# usable from anywhere. Generate the token with e.g. `openssl rand -hex 16`. +# +# [[listen]] +# proto = "doh" +# addr = "0.0.0.0:8443" +# allow = ["0.0.0.0/0", "::/0"] +# cert = "${CREDENTIALS_DIRECTORY}/cert.pem" +# key = "${CREDENTIALS_DIRECTORY}/key.pem" +# path = "/dns-query/REPLACE-WITH-RANDOM-TOKEN" # --- Upstreams (tried in order, failed ones are deprioritised for 30 s) ------- # 'addrs' are bootstrap addresses: upstream hostnames are never resolved. diff --git a/src/acl.rs b/src/acl.rs index a6aef7d..2ec366c 100644 --- a/src/acl.rs +++ b/src/acl.rs @@ -1,20 +1,65 @@ -//! Client allowlist. +//! Client allowlist: static networks plus hostnames whose current +//! addresses are kept up to date by [`crate::hosts`]. +use crate::hosts::{HostSlot, Hosts}; use ipnet::IpNet; use std::net::IpAddr; +use std::sync::Arc; +use tracing::debug; -#[derive(Debug, Clone)] -pub struct Acl(Vec); +#[derive(Clone)] +pub struct HostRule { + slot: Arc, + v4_prefix: u8, + v6_prefix: u8, +} + +impl HostRule { + pub fn new(slot: Arc, v4_prefix: u8, v6_prefix: u8) -> Self { + Self { + slot, + v4_prefix, + v6_prefix, + } + } +} + +#[derive(Clone)] +pub struct Acl { + nets: Vec, + hosts: Vec, + /// Notified when a client is rejected and host rules exist. + registry: Option>, +} impl Acl { - pub fn new(nets: Vec) -> Self { - Self(nets) + pub fn new(nets: Vec, hosts: Vec, registry: Option>) -> Self { + Self { + nets, + hosts, + registry, + } } pub fn allows(&self, ip: IpAddr) -> bool { // IPv4-mapped IPv6 (dual-stack sockets) is matched as IPv4. let ip = ip.to_canonical(); - self.0.iter().any(|n| n.contains(&ip)) + if self.nets.iter().any(|n| n.contains(&ip)) + || self + .hosts + .iter() + .any(|h| h.slot.matches(ip, h.v4_prefix, h.v6_prefix)) + { + return true; + } + debug!(%ip, "client not allowed"); + // The client's DynDNS name may have just moved to this address. + if !self.hosts.is_empty() { + if let Some(r) = &self.registry { + r.trigger(); + } + } + false } } @@ -24,12 +69,16 @@ mod tests { #[test] fn matching() { - let acl = Acl::new(vec!["127.0.0.0/8".parse().unwrap(), "fd00::/8".parse().unwrap()]); + let acl = Acl::new( + vec!["127.0.0.0/8".parse().unwrap(), "fd00::/8".parse().unwrap()], + vec![], + None, + ); assert!(acl.allows("127.0.0.1".parse().unwrap())); assert!(acl.allows("::ffff:127.0.0.1".parse().unwrap())); assert!(acl.allows("fd12::1".parse().unwrap())); assert!(!acl.allows("10.0.0.1".parse().unwrap())); assert!(!acl.allows("::1".parse().unwrap())); - assert!(!Acl::new(vec![]).allows("127.0.0.1".parse().unwrap())); + assert!(!Acl::new(vec![], vec![], None).allows("127.0.0.1".parse().unwrap())); } } diff --git a/src/config.rs b/src/config.rs index 21713e6..62ce582 100644 --- a/src/config.rs +++ b/src/config.rs @@ -16,6 +16,48 @@ pub struct Config { pub listeners: Vec, #[serde(rename = "upstream", default)] pub upstreams: Vec, + #[serde(default)] + pub host_acl: HostAcl, +} + +/// Timing of allowlist hostname resolution (`allow_hosts`). +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct HostAcl { + /// Lower bound of the refresh interval (guards against tiny TTLs). + pub refresh_min_ms: u64, + /// Upper bound of the refresh interval. + pub refresh_max_ms: u64, + /// How long the last known addresses stay valid while resolution fails. + pub max_stale_ms: u64, + /// Minimum spacing of refreshes triggered by rejected clients. + pub trigger_min_interval_ms: u64, +} + +impl Default for HostAcl { + fn default() -> Self { + Self { + refresh_min_ms: 30_000, + refresh_max_ms: 300_000, + max_stale_ms: 3_600_000, + trigger_min_interval_ms: 15_000, + } + } +} + +impl HostAcl { + pub fn refresh_min(&self) -> Duration { + Duration::from_millis(self.refresh_min_ms) + } + pub fn refresh_max(&self) -> Duration { + Duration::from_millis(self.refresh_max_ms) + } + pub fn max_stale(&self) -> Duration { + Duration::from_millis(self.max_stale_ms) + } + pub fn trigger_min_interval(&self) -> Duration { + Duration::from_millis(self.trigger_min_interval_ms) + } } #[derive(Debug, Deserialize)] @@ -92,14 +134,72 @@ impl std::fmt::Display for Proto { pub struct Listener { pub proto: Proto, pub addr: SocketAddr, - /// Client networks allowed to use this listener. Mandatory. + /// Client networks allowed to use this listener. + #[serde(default)] pub allow: Vec, + /// Hostnames (e.g. DynDNS) whose current addresses are allowed. + #[serde(default)] + pub allow_hosts: Vec, pub cert: Option, pub key: Option, /// DoH only: request path (default `/dns-query`). pub path: Option, } +/// An `allow_hosts` entry: a hostname, or a table with prefix lengths. +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +pub enum HostSpec { + Name(String), + Detailed(HostDetail), +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HostDetail { + pub name: String, + pub v4_prefix: Option, + pub v6_prefix: Option, +} + +/// Bounds keep a typo from allowing a huge range; use `allow` for that. +const V4_PREFIX_RANGE: std::ops::RangeInclusive = 16..=32; +const V6_PREFIX_RANGE: std::ops::RangeInclusive = 32..=128; + +impl HostSpec { + pub fn name(&self) -> &str { + match self { + HostSpec::Name(n) => n, + HostSpec::Detailed(d) => &d.name, + } + } + /// Prefix length applied to the host's IPv4 addresses (default 32). + pub fn v4_prefix(&self) -> u8 { + match self { + HostSpec::Detailed(HostDetail { + v4_prefix: Some(p), .. + }) => *p, + _ => 32, + } + } + /// Prefix length applied to the host's IPv6 addresses (default 64: + /// clients in a LAN use other addresses of the same prefix). + pub fn v6_prefix(&self) -> u8 { + match self { + HostSpec::Detailed(HostDetail { + v6_prefix: Some(p), .. + }) => *p, + _ => 64, + } + } + /// Normalised (lowercase, no trailing dot) and validated name. + pub fn normalized(&self) -> Result { + let n = self.name(); + crate::dns::encode_name(n).map_err(|_| format!("allow_hosts: invalid hostname {n:?}"))?; + Ok(n.trim_end_matches('.').to_ascii_lowercase()) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum UpstreamKind { @@ -149,6 +249,20 @@ impl Config { return Err(format!("limits.{name} must be > 0")); } } + let h = &self.host_acl; + for (name, v) in [ + ("refresh_min_ms", h.refresh_min_ms), + ("refresh_max_ms", h.refresh_max_ms), + ("max_stale_ms", h.max_stale_ms), + ("trigger_min_interval_ms", h.trigger_min_interval_ms), + ] { + if v == 0 { + return Err(format!("host_acl.{name} must be > 0")); + } + } + if h.refresh_min_ms > h.refresh_max_ms { + return Err("host_acl.refresh_min_ms must not exceed refresh_max_ms".into()); + } if l.tcp_max_inflight_per_conn > u32::MAX as usize { return Err("limits.tcp_max_inflight_per_conn too large".into()); } @@ -162,11 +276,20 @@ impl Config { for li in &self.listeners { let ctx = format!("listen {} {}", li.proto, li.addr); - if li.allow.is_empty() { + if li.allow.is_empty() && li.allow_hosts.is_empty() { return Err(format!( - "{ctx}: 'allow' must not be empty (use \"0.0.0.0/0\" and \"::/0\" to deliberately run an open resolver)" + "{ctx}: 'allow' or 'allow_hosts' must not be empty (use \"0.0.0.0/0\" and \"::/0\" to deliberately run an open resolver)" )); } + for h in &li.allow_hosts { + h.normalized().map_err(|e| format!("{ctx}: {e}"))?; + if !V4_PREFIX_RANGE.contains(&h.v4_prefix()) || !V6_PREFIX_RANGE.contains(&h.v6_prefix()) { + return Err(format!( + "{ctx}: allow_hosts {}: v4_prefix must be in 16..=32, v6_prefix in 32..=128", + h.name() + )); + } + } let tls = matches!(li.proto, Proto::Dot | Proto::Doh); if tls != (li.cert.is_some() && li.key.is_some()) || li.cert.is_some() != li.key.is_some() { return Err(if tls { @@ -256,6 +379,39 @@ mod tests { assert!(parse("[[listen]]\nproto = \"udp\"\naddr = \"127.0.0.1:53\"\nallow = []").is_err()); } + #[test] + fn allow_hosts() { + let base = "[[listen]]\nproto = \"dot\"\naddr = \"0.0.0.0:853\"\ncert = \"c\"\nkey = \"k\"\n"; + let c = parse(&format!( + "{base}allow_hosts = [\"Home.Dyn.Example.\", {{ name = \"office.dyn.example\", v6_prefix = 56 }}]" + )) + .unwrap(); + let hosts = &c.listeners[0].allow_hosts; + assert!(c.listeners[0].allow.is_empty()); + assert_eq!(hosts[0].normalized().unwrap(), "home.dyn.example"); + assert_eq!((hosts[0].v4_prefix(), hosts[0].v6_prefix()), (32, 64)); + assert_eq!((hosts[1].v4_prefix(), hosts[1].v6_prefix()), (32, 56)); + + for bad in [ + "allow_hosts = []", + "allow_hosts = [\"1.2.3.4\"]", + "allow_hosts = [\"bad_name.example\"]", + "allow_hosts = [{ name = \"a.example\", v4_prefix = 8 }]", + "allow_hosts = [{ name = \"a.example\", v6_prefix = 16 }]", + "allow_hosts = [{ name = \"a.example\", bogus = 1 }]", + ] { + assert!(parse(&format!("{base}{bad}")).is_err(), "{bad}"); + } + let li = format!("{base}allow_hosts = [\"a.example\"]\n"); + assert!( + parse(&format!( + "{li}[host_acl]\nrefresh_min_ms = 10\nrefresh_max_ms = 5" + )) + .is_err() + ); + assert!(parse(&format!("{li}[host_acl]\nmax_stale_ms = 0")).is_err()); + } + #[test] fn tls_listeners_need_cert_and_key() { let base = "[[listen]]\nproto = \"dot\"\naddr = \"127.0.0.1:853\"\nallow = [\"::1/128\"]\n"; diff --git a/src/dns.rs b/src/dns.rs index 20b7fdf..caf91f5 100644 --- a/src/dns.rs +++ b/src/dns.rs @@ -1,14 +1,18 @@ //! Minimal DNS wire-format handling. //! -//! The proxy never interprets records. It only needs to: +//! The proxy does not interpret forwarded records. It only needs to: //! - validate that an inbound message is a sane standard query, //! - know the question (to match responses) and the client's UDP size, //! - rewrite message IDs, -//! - synthesise SERVFAIL and truncated (TC) replies. +//! - synthesise SERVFAIL and truncated (TC) replies, +//! - build A/AAAA queries for allowlist hostnames and read the addresses +//! from their answers. //! //! All access goes through bounds-checked helpers; malformed input yields //! an error, never a panic. +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + pub const HEADER_LEN: usize = 12; pub const MAX_MSG: usize = 65535; /// Classic DNS UDP limit for clients without EDNS0. @@ -23,8 +27,15 @@ const FLAG_TC: u16 = 0x0200; const FLAG_RD: u16 = 0x0100; const FLAG_RA: u16 = 0x0080; const OPCODE_MASK: u16 = 0x7800; +const RCODE_MASK: u16 = 0x000F; const RCODE_SERVFAIL: u16 = 2; +const RCODE_NXDOMAIN: u16 = 3; const TYPE_OPT: u16 = 41; +pub const TYPE_A: u16 = 1; +pub const TYPE_AAAA: u16 = 28; +const CLASS_IN: u16 = 1; +/// Maximum length of a hostname in presentation format. +const MAX_HOSTNAME_LEN: usize = 253; #[derive(Debug, PartialEq, Eq)] pub struct Malformed; @@ -37,6 +48,17 @@ impl std::fmt::Display for Malformed { impl std::error::Error for Malformed {} +/// Result of an address lookup (A or AAAA) for an allowlist hostname. +#[derive(Debug, PartialEq, Eq)] +pub enum Lookup { + /// Addresses of the queried type and the smallest TTL in the answer. + Found { addrs: Vec, ttl: u32 }, + /// Definitive: NXDOMAIN, or NOERROR without addresses (NODATA). + NotFound, + /// SERVFAIL, REFUSED, truncated or malformed: nothing is known. + Failed, +} + /// A validated standard query. #[derive(Debug, Clone)] pub struct Query { @@ -94,6 +116,67 @@ impl Query { }) } + /// Builds a recursive query for `name` (wire format, see + /// [`encode_name`]) and `qtype`, class IN. + pub fn build(name: &[u8], qtype: u16) -> Result { + let mut m = Vec::with_capacity(HEADER_LEN + name.len() + 4); + m.extend_from_slice(&[0, 0]); + m.extend_from_slice(&FLAG_RD.to_be_bytes()); + m.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 0]); + m.extend_from_slice(name); + m.extend_from_slice(&qtype.to_be_bytes()); + m.extend_from_slice(&CLASS_IN.to_be_bytes()); + Self::parse(&m) + } + + /// Extracts the addresses answering this (A or AAAA) query from `resp`, + /// which must already have passed [`Query::is_answered_by`]. + /// + /// Owner names are not matched against the CNAME chain: the response + /// comes from an authenticated (TLS) upstream resolver, which only puts + /// records relevant to the question into the answer section. + pub fn addresses(&self, resp: &[u8]) -> Lookup { + self.addresses_inner(resp).unwrap_or(Lookup::Failed) + } + + fn addresses_inner(&self, resp: &[u8]) -> Result { + let flags = be16(resp, 2)?; + if flags & FLAG_TC != 0 { + return Ok(Lookup::Failed); + } + match flags & RCODE_MASK { + 0 => {} + RCODE_NXDOMAIN => return Ok(Lookup::NotFound), + _ => return Ok(Lookup::Failed), + } + let qtype = be16(&self.msg, self.qend.checked_sub(4).ok_or(Malformed)?)?; + let ancount = be16(resp, 6)?; + let mut off = checked_end(resp, HEADER_LEN, self.question().len())?; + let mut addrs = Vec::new(); + let mut ttl = u32::MAX; + for _ in 0..ancount { + let rr = skip_rr(resp, off)?; + ttl = ttl.min(rr.ttl); + if rr.class == CLASS_IN && rr.rtype == qtype { + let rdata = resp.get(rr.rdata..rr.next).ok_or(Malformed)?; + let addr = match qtype { + TYPE_A => IpAddr::V4(Ipv4Addr::from(<[u8; 4]>::try_from(rdata).map_err(|_| Malformed)?)), + TYPE_AAAA => IpAddr::V6(Ipv6Addr::from( + <[u8; 16]>::try_from(rdata).map_err(|_| Malformed)?, + )), + _ => return Err(Malformed), + }; + addrs.push(addr); + } + off = rr.next; + } + Ok(if addrs.is_empty() { + Lookup::NotFound + } else { + Lookup::Found { addrs, ttl } + }) + } + /// The raw question section (QNAME, QTYPE, QCLASS). pub fn question(&self) -> &[u8] { self.msg.get(HEADER_LEN..self.qend).unwrap_or_default() @@ -149,6 +232,36 @@ impl Query { } } +/// Encodes a hostname (letters, digits, hyphens; optional trailing dot) +/// into lowercase wire format. IP address literals are rejected: the last +/// label must not be purely numeric. +pub fn encode_name(name: &str) -> Result, Malformed> { + let name = name.strip_suffix('.').unwrap_or(name); + if name.is_empty() || name.len() > MAX_HOSTNAME_LEN { + return Err(Malformed); + } + let mut out = Vec::with_capacity(name.len() + 2); + let mut last_numeric = false; + for label in name.split('.') { + let valid = !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-'); + if !valid { + return Err(Malformed); + } + last_numeric = label.bytes().all(|c| c.is_ascii_digit()); + out.push(label.len() as u8); + out.extend(label.bytes().map(|c| c.to_ascii_lowercase())); + } + if last_numeric { + return Err(Malformed); + } + out.push(0); + Ok(out) +} + pub fn id(msg: &[u8]) -> Option { be16(msg, 0).ok() } @@ -169,6 +282,16 @@ fn be16(b: &[u8], off: usize) -> Result { Ok(u16::from_be_bytes(s)) } +fn be32(b: &[u8], off: usize) -> Result { + let end = off.checked_add(4).ok_or(Malformed)?; + let s: [u8; 4] = b + .get(off..end) + .ok_or(Malformed)? + .try_into() + .map_err(|_| Malformed)?; + Ok(u32::from_be_bytes(s)) +} + /// Returns `off + n` if that many bytes are available. fn checked_end(b: &[u8], off: usize, n: usize) -> Result { let end = off.checked_add(n).ok_or(Malformed)?; @@ -206,6 +329,10 @@ fn skip_name(b: &[u8], mut off: usize, allow_ptr: bool) -> Result Result { let off = skip_name(b, off, true)?; let rtype = be16(b, off)?; let class = be16(b, off + 2)?; + let ttl = be32(b, off + 4)?; + // RFC 2181 8: a TTL with the most significant bit set is treated as 0. + let ttl = if ttl > i32::MAX as u32 { 0 } else { ttl }; let rdlen = be16(b, off + 8)?; - let next = checked_end(b, off + 10, usize::from(rdlen))?; - Ok(Rr { rtype, class, next }) + let rdata = off + 10; + let next = checked_end(b, rdata, usize::from(rdlen))?; + Ok(Rr { + rtype, + class, + ttl, + rdata, + next, + }) } #[cfg(test)] @@ -396,4 +533,149 @@ pub(crate) mod tests { } } } + + /// Response to `q` with the given RCODE and answer records + /// (type, TTL, RDATA), owner names compressed to the question. + fn response(q: &Query, rcode: u8, records: &[(u16, u32, &[u8])]) -> Vec { + let mut r = q.with_id(q.id); + r.truncate(HEADER_LEN + q.question().len()); + r[2] |= 0x80; + r[3] = 0x80 | rcode; + r[6..8].copy_from_slice(&(records.len() as u16).to_be_bytes()); + r[10..12].copy_from_slice(&[0, 0]); + for (t, ttl, data) in records { + r.extend_from_slice(&[0xC0, 0x0C]); + r.extend_from_slice(&t.to_be_bytes()); + r.extend_from_slice(&CLASS_IN.to_be_bytes()); + r.extend_from_slice(&ttl.to_be_bytes()); + r.extend_from_slice(&(data.len() as u16).to_be_bytes()); + r.extend_from_slice(data); + } + r + } + + fn host_query(name: &str, qtype: u16) -> Query { + Query::build(&encode_name(name).unwrap(), qtype).unwrap() + } + + #[test] + fn encode_names() { + assert_eq!( + encode_name("Home.Dyn.Example.").unwrap(), + b"\x04home\x03dyn\x07example\x00" + ); + assert!(encode_name("a-b.example").is_ok()); + assert!(encode_name(&format!("{}.example", "a".repeat(63))).is_ok()); + for bad in [ + "", + ".", + "a..b", + "-a.example", + "a-.example", + "a_b.example", + "a b.example", + "1.2.3.4", + "::1", + "example.123", + ] { + assert!(encode_name(bad).is_err(), "{bad:?}"); + } + assert!(encode_name(&format!("{}.example", "a".repeat(64))).is_err()); + let long = ["a".repeat(63).as_str(); 4].join("."); + assert!(encode_name(&long).is_err()); + } + + #[test] + fn built_query_is_valid() { + let q = host_query("home.dyn.example", TYPE_AAAA); + assert_eq!(&q.question()[q.question().len() - 4..], &[0, 28, 0, 1]); + assert_eq!(q.with_id(0)[2] & 0x01, 0x01, "RD set"); + } + + #[test] + fn address_extraction() { + let q = host_query("home.dyn.example", TYPE_A); + let r = response( + &q, + 0, + &[(TYPE_A, 300, &[192, 0, 2, 1]), (TYPE_A, 60, &[192, 0, 2, 2])], + ); + assert_eq!( + q.addresses(&r), + Lookup::Found { + addrs: vec!["192.0.2.1".parse().unwrap(), "192.0.2.2".parse().unwrap()], + ttl: 60 + } + ); + // CNAME first: its TTL counts, its RDATA is ignored. + let cname = b"\x03foo\x07example\x00"; + let r = response(&q, 0, &[(5, 30, cname), (TYPE_A, 300, &[192, 0, 2, 1])]); + assert_eq!( + q.addresses(&r), + Lookup::Found { + addrs: vec!["192.0.2.1".parse().unwrap()], + ttl: 30 + } + ); + // TTL with the high bit set counts as 0. + let r = response(&q, 0, &[(TYPE_A, 0x8000_0000, &[192, 0, 2, 1])]); + assert!(matches!(q.addresses(&r), Lookup::Found { ttl: 0, .. })); + + let q6 = host_query("home.dyn.example", TYPE_AAAA); + let v6: Ipv6Addr = "2001:db8::1".parse().unwrap(); + let r = response(&q6, 0, &[(TYPE_AAAA, 60, &v6.octets())]); + assert_eq!( + q6.addresses(&r), + Lookup::Found { + addrs: vec![IpAddr::V6(v6)], + ttl: 60 + } + ); + } + + #[test] + fn address_extraction_negative() { + let q = host_query("home.dyn.example", TYPE_A); + assert_eq!(q.addresses(&response(&q, 3, &[])), Lookup::NotFound); + assert_eq!(q.addresses(&response(&q, 0, &[])), Lookup::NotFound); + let cname_only = response(&q, 0, &[(5, 30, b"\x03foo\x00")]); + assert_eq!(q.addresses(&cname_only), Lookup::NotFound); + assert_eq!(q.addresses(&response(&q, 2, &[])), Lookup::Failed); + assert_eq!(q.addresses(&response(&q, 5, &[])), Lookup::Failed); + // Wrong RDATA length for A. + let r = response(&q, 0, &[(TYPE_A, 60, &[1, 2, 3])]); + assert_eq!(q.addresses(&r), Lookup::Failed); + // Truncated. + let mut r = response(&q, 0, &[(TYPE_A, 60, &[1, 2, 3, 4])]); + r[2] |= 0x02; + assert_eq!(q.addresses(&r), Lookup::Failed); + // Record cut off. + let r = response(&q, 0, &[(TYPE_A, 60, &[1, 2, 3, 4])]); + assert_eq!(q.addresses(&r[..r.len() - 1]), Lookup::Failed); + assert_eq!(q.addresses(&[]), Lookup::Failed); + } + + #[test] + fn random_responses_never_panic() { + let mut s: u64 = 0xD1B5_4A32_D192_ED03; + let mut next = || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + s + }; + let q = host_query("home.dyn.example", TYPE_A); + let seed = response(&q, 0, &[(5, 30, b"\x03foo\x00"), (TYPE_A, 60, &[192, 0, 2, 1])]); + for _ in 0..200_000 { + let mut m = seed.clone(); + m.truncate((next() as usize) % (seed.len() + 1)); + for _ in 0..(next() % 4) { + if !m.is_empty() { + let i = (next() as usize) % m.len(); + m[i] = next() as u8; + } + } + let _ = q.addresses(&m); + } + } } diff --git a/src/hosts.rs b/src/hosts.rs new file mode 100644 index 0000000..6ad55e5 --- /dev/null +++ b/src/hosts.rs @@ -0,0 +1,247 @@ +//! Allowlist hostnames (e.g. DynDNS): resolved in the background through +//! the encrypted upstreams, never per packet and never via the system +//! resolver. The packet path only reads the last known addresses. + +use crate::config::HostAcl; +use crate::dns::{self, Lookup, Query}; +use crate::upstream::Resolver; +use std::net::IpAddr; +use std::sync::{Arc, RwLock}; +use std::time::{Duration, Instant}; +use tokio::sync::Notify; +use tokio::task::JoinSet; +use tokio::time::sleep_until; +use tracing::{info, warn}; + +#[derive(Debug, Default)] +struct Family { + addrs: Vec, + /// Last definitive answer (addresses or NXDOMAIN/NODATA). + last_ok: Option, + /// Currently in a failure streak (for log deduplication). + failing: bool, +} + +/// One hostname with its last known IPv4 and IPv6 addresses. +#[derive(Debug)] +pub struct HostSlot { + name: String, + queries: [Query; 2], + families: [RwLock; 2], +} + +const LABELS: [&str; 2] = ["A", "AAAA"]; + +impl HostSlot { + fn new(name: String) -> Result { + let wire = dns::encode_name(&name).map_err(|_| format!("invalid hostname {name:?}"))?; + let q = |t| Query::build(&wire, t).map_err(|_| format!("invalid hostname {name:?}")); + Ok(Self { + queries: [q(dns::TYPE_A)?, q(dns::TYPE_AAAA)?], + families: Default::default(), + name, + }) + } + + /// Whether `ip` lies within `prefix` of any current address of its + /// family. + pub fn matches(&self, ip: IpAddr, v4_prefix: u8, v6_prefix: u8) -> bool { + let (fam, prefix) = match ip { + IpAddr::V4(_) => (&self.families[0], v4_prefix), + IpAddr::V6(_) => (&self.families[1], v6_prefix), + }; + let fam = fam.read().unwrap_or_else(|e| e.into_inner()); + fam.addrs.iter().any(|a| { + ipnet::IpNet::new(*a, prefix) + .map(|n| n.contains(&ip)) + .unwrap_or(false) + }) + } + + /// Applies a lookup result; returns when this family wants a refresh. + fn apply(&self, idx: usize, lookup: Lookup, now: Instant, cfg: &HostAcl) -> Duration { + let mut fam = self.families[idx].write().unwrap_or_else(|e| e.into_inner()); + let (name, rr) = (&self.name, LABELS[idx]); + match lookup { + Lookup::Found { mut addrs, ttl } => { + addrs.sort(); + addrs.dedup(); + if fam.addrs != addrs { + info!(host = %name, rr, old = ?fam.addrs, new = ?addrs, "allowlist host updated"); + } else if fam.failing { + info!(host = %name, rr, "allowlist host resolves again"); + } + fam.addrs = addrs; + fam.last_ok = Some(now); + fam.failing = false; + Duration::from_secs(u64::from(ttl)) + } + Lookup::NotFound => { + if !fam.addrs.is_empty() { + info!(host = %name, rr, old = ?fam.addrs, "allowlist host has no addresses anymore"); + } + fam.addrs.clear(); + fam.last_ok = Some(now); + fam.failing = false; + // Re-added records are picked up via the reject trigger. + cfg.refresh_max() + } + Lookup::Failed => { + if !fam.failing { + if fam.addrs.is_empty() { + warn!(host = %name, rr, "allowlist host resolution failed"); + } else { + warn!(host = %name, rr, old = ?fam.addrs, "allowlist host resolution failed, keeping last known addresses"); + } + fam.failing = true; + } + let expired = fam + .last_ok + .is_none_or(|t| now.duration_since(t) >= cfg.max_stale()); + if expired && !fam.addrs.is_empty() { + warn!(host = %name, rr, old = ?fam.addrs, "allowlist host addresses expired"); + fam.addrs.clear(); + } + cfg.refresh_min() + } + } + } +} + +/// All allowlist hostnames of the process, resolved by one task. +pub struct Hosts { + slots: Vec>, + trigger: Notify, + cfg: HostAcl, +} + +impl Hosts { + pub fn new(names: impl IntoIterator, cfg: &HostAcl) -> Result { + let mut names: Vec = names.into_iter().collect(); + names.sort(); + names.dedup(); + let slots = names + .into_iter() + .map(|n| HostSlot::new(n).map(Arc::new)) + .collect::>()?; + Ok(Self { + slots, + trigger: Notify::new(), + cfg: cfg.clone(), + }) + } + + pub fn slot(&self, name: &str) -> Option> { + self.slots.iter().find(|s| s.name == name).cloned() + } + + /// Requests an early refresh, e.g. because a client was rejected whose + /// DynDNS name may have just changed. Coalescing and cheap; the + /// refresher enforces `trigger_min_interval`. + pub fn trigger(&self) { + self.trigger.notify_one(); + } + + /// Refresh loop; never returns. + pub async fn run(self: Arc, resolver: Arc) { + let cfg = &self.cfg; + loop { + let started = Instant::now(); + let deadline = tokio::time::Instant::from_std(started + self.refresh(&resolver).await); + let earliest_trigger = tokio::time::Instant::from_std(started + cfg.trigger_min_interval()); + tokio::select! { + _ = sleep_until(deadline) => {} + _ = self.trigger.notified() => sleep_until(earliest_trigger.min(deadline)).await, + } + } + } + + /// Resolves every slot once; returns the delay until the next refresh. + async fn refresh(&self, resolver: &Arc) -> Duration { + let cfg = &self.cfg; + let mut tasks = JoinSet::new(); + for slot in &self.slots { + for idx in 0..2 { + let (slot, resolver) = (slot.clone(), resolver.clone()); + tasks.spawn(async move { + let q = &slot.queries[idx]; + let lookup = q.addresses(&resolver.resolve(q).await); + (slot, idx, lookup) + }); + } + } + let mut next = cfg.refresh_max(); + while let Some(res) = tasks.join_next().await { + let Ok((slot, idx, lookup)) = res else { continue }; + next = next.min(slot.apply(idx, lookup, Instant::now(), cfg)); + } + next.clamp(cfg.refresh_min(), cfg.refresh_max()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg() -> HostAcl { + HostAcl { + refresh_min_ms: 1_000, + refresh_max_ms: 10_000, + max_stale_ms: 60_000, + trigger_min_interval_ms: 1_000, + } + } + + fn found(addrs: &[&str], ttl: u32) -> Lookup { + Lookup::Found { + addrs: addrs.iter().map(|a| a.parse().unwrap()).collect(), + ttl, + } + } + + #[test] + fn matching_with_prefixes() { + let s = HostSlot::new("home.dyn.example".into()).unwrap(); + let now = Instant::now(); + s.apply(0, found(&["192.0.2.10"], 60), now, &cfg()); + s.apply(1, found(&["2001:db8:1:2::1"], 60), now, &cfg()); + assert!(s.matches("192.0.2.10".parse().unwrap(), 32, 64)); + assert!(!s.matches("192.0.2.11".parse().unwrap(), 32, 64)); + assert!(s.matches("192.0.2.11".parse().unwrap(), 24, 64)); + assert!(s.matches("2001:db8:1:2::abcd".parse().unwrap(), 32, 64)); + assert!(!s.matches("2001:db8:1:3::1".parse().unwrap(), 32, 64)); + assert!(s.matches("2001:db8:1:3::1".parse().unwrap(), 32, 56)); + } + + #[test] + fn lifecycle() { + let c = cfg(); + let s = HostSlot::new("home.dyn.example".into()).unwrap(); + let ip = "192.0.2.10".parse().unwrap(); + let t0 = Instant::now(); + // Nothing known yet: fail closed. + assert!(!s.matches(ip, 32, 64)); + assert_eq!(s.apply(0, Lookup::Failed, t0, &c), c.refresh_min()); + assert!(!s.matches(ip, 32, 64)); + + assert_eq!( + s.apply(0, found(&["192.0.2.10"], 42), t0, &c), + Duration::from_secs(42) + ); + assert!(s.matches(ip, 32, 64)); + // Failure within max_stale keeps the address. + s.apply(0, Lookup::Failed, t0 + Duration::from_secs(59), &c); + assert!(s.matches(ip, 32, 64)); + // Beyond max_stale it is dropped. + s.apply(0, Lookup::Failed, t0 + Duration::from_secs(60), &c); + assert!(!s.matches(ip, 32, 64)); + + // A new address replaces the old one immediately. + s.apply(0, found(&["192.0.2.10"], 60), t0, &c); + s.apply(0, found(&["198.51.100.1"], 60), t0, &c); + assert!(!s.matches(ip, 32, 64)); + // NXDOMAIN/NODATA clears at once. + s.apply(0, Lookup::NotFound, t0, &c); + assert!(!s.matches("198.51.100.1".parse().unwrap(), 32, 64)); + } +} diff --git a/src/lib.rs b/src/lib.rs index 44d9897..f6ed1ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,19 +6,21 @@ mod acl; pub mod config; mod dns; mod frame; +mod hosts; mod server; mod tls; mod upstream; -use acl::Acl; +use acl::{Acl, HostRule}; use config::{Config, Proto}; +use hosts::Hosts; use std::net::SocketAddr; use std::sync::Arc; use tokio::net::{TcpListener, UdpSocket}; use tokio::task::JoinSet; use tokio::time::timeout; use tokio_rustls::TlsAcceptor; -use tracing::{debug, info}; +use tracing::{debug, info, warn}; use upstream::Resolver; /// Running proxy. Dropping it stops all listeners. @@ -41,14 +43,44 @@ struct Prepared { acl: Acl, tls: Option, path: String, + has_hosts: bool, +} + +struct Plan { + resolver: Arc, + hosts: Option>, + listeners: Vec, } /// Validates everything that can fail without binding sockets: upstream /// URLs/names, CA files, listener certificates and keys. -fn prepare(cfg: &Config) -> Result<(Arc, Vec), String> { +fn prepare(cfg: &Config) -> Result { let resolver = Arc::new(Resolver::new(&cfg.upstreams, &cfg.limits)?); + + // One registry for all allowlist hostnames, shared by the listeners. + let mut names = Vec::new(); + for li in &cfg.listeners { + for h in &li.allow_hosts { + names.push(h.normalized()?); + } + } + let hosts = if names.is_empty() { + None + } else { + Some(Arc::new(Hosts::new(names, &cfg.host_acl)?)) + }; + let mut out = Vec::with_capacity(cfg.listeners.len()); for li in &cfg.listeners { + let mut rules = Vec::with_capacity(li.allow_hosts.len()); + if let Some(hosts) = &hosts { + for h in &li.allow_hosts { + let slot = hosts + .slot(&h.normalized()?) + .ok_or("allow_hosts: missing host slot")?; + rules.push(HostRule::new(slot, h.v4_prefix(), h.v6_prefix())); + } + } let tls = match (li.proto, &li.cert, &li.key) { (Proto::Dot | Proto::Doh, Some(cert), Some(key)) => { let alpn: &[&[u8]] = if li.proto == Proto::Dot { @@ -64,12 +96,17 @@ fn prepare(cfg: &Config) -> Result<(Arc, Vec), String> { out.push(Prepared { proto: li.proto, addr: li.addr, - acl: Acl::new(li.allow.clone()), + acl: Acl::new(li.allow.clone(), rules, hosts.clone()), tls, path: li.path.clone().unwrap_or_else(|| "/dns-query".into()), + has_hosts: !li.allow_hosts.is_empty(), }); } - Ok((resolver, out)) + Ok(Plan { + resolver, + hosts, + listeners: out, + }) } /// Checks the configuration including certificates, without binding. @@ -79,12 +116,28 @@ pub fn check(cfg: &Config) -> Result<(), String> { /// Binds all listeners and starts serving. pub async fn start(cfg: Config) -> Result { - let (resolver, listeners) = prepare(&cfg)?; + let Plan { + resolver, + hosts, + listeners, + } = prepare(&cfg)?; let limits = &cfg.limits; let mut tasks = JoinSet::new(); let mut bound = Vec::with_capacity(listeners.len()); + if let Some(hosts) = hosts { + tasks.spawn(hosts.run(resolver.clone())); + } + for l in listeners { + if l.has_hosts && matches!(l.proto, Proto::Udp | Proto::Tcp) { + warn!( + proto = %l.proto, + addr = %l.addr, + "allow_hosts on a plain DNS listener: traffic is unencrypted{}; prefer dot/doh", + if l.proto == Proto::Udp { " and source addresses can be spoofed" } else { "" } + ); + } let bind_err = |e: std::io::Error| format!("bind {} {}: {e}", l.proto, l.addr); if l.proto == Proto::Udp { let sock = UdpSocket::bind(l.addr).await.map_err(bind_err)?; diff --git a/src/server/doh.rs b/src/server/doh.rs index 6461e92..12153f0 100644 --- a/src/server/doh.rs +++ b/src/server/doh.rs @@ -113,6 +113,15 @@ where let _ = tokio::time::timeout(SHUTDOWN_GRACE, conn).await; } +/// Constant-time equality (only the length may leak). +fn ct_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let diff = a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)); + std::hint::black_box(diff) == 0 +} + fn status(code: StatusCode) -> Response> { let mut r = Response::new(Full::default()); *r.status_mut() = code; @@ -120,7 +129,8 @@ fn status(code: StatusCode) -> Response> { } async fn respond(req: Request, p: &Params) -> Response> { - if req.uri().path() != p.path { + // The path may carry a secret token, so compare in constant time. + if !ct_eq(req.uri().path().as_bytes(), p.path.as_bytes()) { return status(StatusCode::NOT_FOUND); } let msg = match *req.method() { @@ -170,3 +180,16 @@ async fn respond(req: Request, p: &Params) -> Response> { .insert(CONTENT_TYPE, DNS_MESSAGE.parse().expect("static header")); r } + +#[cfg(test)] +mod tests { + use super::ct_eq; + + #[test] + fn constant_time_eq() { + assert!(ct_eq(b"/dns-query/abc", b"/dns-query/abc")); + assert!(!ct_eq(b"/dns-query/abd", b"/dns-query/abc")); + assert!(!ct_eq(b"/dns-query", b"/dns-query/abc")); + assert!(ct_eq(b"", b"")); + } +} diff --git a/tests/e2e.rs b/tests/e2e.rs index e484b3d..a684f5b 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -9,10 +9,11 @@ use hyper_util::rt::{TokioExecutor, TokioIo}; use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair}; use rustls::pki_types::pem::PemObject; use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName}; -use std::net::SocketAddr; +use std::collections::HashMap; +use std::net::{Ipv4Addr, SocketAddr}; use std::path::PathBuf; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream, UdpSocket}; @@ -146,6 +147,57 @@ fn answer(q: &[u8]) -> Vec { r } +/// Records the fake upstream serves for allowlist hostnames; names not in +/// the zone get [`answer`]. +#[derive(Clone, Copy)] +enum Rec { + A(Ipv4Addr), + NxDomain, + ServFail, +} + +type Zone = Arc>>; + +fn zone(entries: &[(&str, Rec)]) -> Zone { + Arc::new(Mutex::new( + entries.iter().map(|(n, r)| (n.to_string(), *r)).collect(), + )) +} + +fn set(zone: &Zone, name: &str, rec: Rec) { + zone.lock().unwrap().insert(name.to_string(), rec); +} + +fn answer_zone(q: &[u8], zone: &Zone) -> Vec { + let mut off = 12; + let mut labels = Vec::new(); + while q[off] != 0 { + let len = q[off] as usize; + labels.push(String::from_utf8_lossy(&q[off + 1..off + 1 + len]).to_string()); + off += 1 + len; + } + let qend = off + 5; + let qtype = u16::from_be_bytes([q[off + 1], q[off + 2]]); + let Some(rec) = zone.lock().unwrap().get(&labels.join(".")).copied() else { + return answer(q); + }; + let (rcode, a) = match rec { + Rec::A(ip) if qtype == 1 => (0, Some(ip)), + Rec::A(_) => (0, None), // NODATA for AAAA + Rec::NxDomain => (3, None), + Rec::ServFail => (2, None), + }; + let mut r = Vec::new(); + r.extend_from_slice(&q[0..2]); + r.extend_from_slice(&[0x81, 0x80 | rcode, 0, 1, 0, u8::from(a.is_some()), 0, 0, 0, 0]); + r.extend_from_slice(&q[12..qend]); + if let Some(ip) = a { + r.extend_from_slice(&[0xC0, 0x0C, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4]); + r.extend_from_slice(&ip.octets()); + } + r +} + fn rcode(r: &[u8]) -> u8 { r[3] & 0x0F } @@ -164,6 +216,10 @@ fn assert_answer(r: &[u8], id: u16) { // ---------------------------------------------------------------- fake upstreams async fn fake_dot(pki: &Pki, name: &str) -> SocketAddr { + fake_dot_zone(pki, name, zone(&[])).await +} + +async fn fake_dot_zone(pki: &Pki, name: &str, zone: Zone) -> SocketAddr { let acc = pki.acceptor(name, &[]); let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = l.local_addr().unwrap(); @@ -171,6 +227,7 @@ async fn fake_dot(pki: &Pki, name: &str) -> SocketAddr { loop { let (tcp, _) = l.accept().await.unwrap(); let acc = acc.clone(); + let zone = zone.clone(); tokio::spawn(async move { let Ok(mut s) = acc.accept(tcp).await else { return }; loop { @@ -179,7 +236,7 @@ async fn fake_dot(pki: &Pki, name: &str) -> SocketAddr { if s.read_exact(&mut q).await.is_err() { return; } - let a = answer(&q); + let a = answer_zone(&q, &zone); let mut out = (a.len() as u16).to_be_bytes().to_vec(); out.extend_from_slice(&a); if s.write_all(&out).await.is_err() { @@ -260,6 +317,11 @@ struct Running { } async fn start_proxy(pki: &Pki, upstreams: &str, allow: &str) -> Running { + start_proxy_acl(pki, upstreams, &format!("allow = [{allow}]"), "").await +} + +/// `acl` is inserted into every listener, `extra` before the listeners. +async fn start_proxy_acl(pki: &Pki, upstreams: &str, acl: &str, extra: &str) -> Running { let (c, k) = pki.leaf("localhost"); let (c, k) = (c.display(), k.display()); let toml = format!( @@ -268,27 +330,29 @@ async fn start_proxy(pki: &Pki, upstreams: &str, allow: &str) -> Running { upstream_timeout_ms = 1000 query_timeout_ms = 3000 + {extra} + [[listen]] proto = "udp" addr = "127.0.0.1:0" - allow = [{allow}] + {acl} [[listen]] proto = "tcp" addr = "127.0.0.1:0" - allow = [{allow}] + {acl} [[listen]] proto = "dot" addr = "127.0.0.1:0" - allow = [{allow}] + {acl} cert = "{c}" key = "{k}" [[listen]] proto = "doh" addr = "127.0.0.1:0" - allow = [{allow}] + {acl} cert = "{c}" key = "{k}" @@ -697,3 +761,173 @@ async fn check_rejects_missing_certificate() { .unwrap(); assert!(dns_proxy::check(&cfg).is_err()); } + +// ---------------------------------------------------------------- allow_hosts + +/// Polls over UDP until the proxy answers (`true`) or ignores (`false`) +/// 127.0.0.1, within `within`. +async fn becomes(udp: SocketAddr, answered: bool, within: Duration) -> bool { + let deadline = tokio::time::Instant::now() + within; + while tokio::time::Instant::now() < deadline { + let r = udp_query( + udp, + &query(0x8001, "example.com", None), + Duration::from_millis(150), + ) + .await; + if r.is_some() == answered { + return true; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + false +} + +fn host_acl(refresh_min: u64, refresh_max: u64, max_stale: u64, trigger: u64) -> String { + format!( + "[host_acl]\nrefresh_min_ms = {refresh_min}\nrefresh_max_ms = {refresh_max}\nmax_stale_ms = {max_stale}\ntrigger_min_interval_ms = {trigger}\n" + ) +} + +const LOCALHOST: Rec = Rec::A(Ipv4Addr::new(127, 0, 0, 1)); +const ELSEWHERE: Rec = Rec::A(Ipv4Addr::new(127, 0, 0, 2)); + +#[tokio::test] +async fn allow_hosts_follows_address_changes() { + let pki = Pki::new(); + let z = zone(&[("client.test", LOCALHOST)]); + let up = fake_dot_zone(&pki, "upstream.test", z.clone()).await; + // Static allow does not match; only the hostname does. + let acl = "allow = [\"10.0.0.0/8\"]\nallow_hosts = [\"Client.Test.\"]"; + let p = start_proxy_acl( + &pki, + &dot_upstream(&pki, "upstream.test", up), + acl, + &host_acl(100, 200, 60_000, 50), + ) + .await; + + assert!( + becomes(p.udp, true, Duration::from_secs(3)).await, + "allowed once resolved" + ); + assert_answer( + &tcp_query(p.tcp, &query(0x8101, "example.com", None)) + .await + .unwrap(), + 0x8101, + ); + + set(&z, "client.test", ELSEWHERE); + assert!( + becomes(p.udp, false, Duration::from_secs(3)).await, + "rejected after move" + ); + assert!( + tcp_query(p.tcp, &query(0x8102, "example.com", None)) + .await + .is_none() + ); +} + +#[tokio::test] +async fn rejected_client_triggers_refresh() { + let pki = Pki::new(); + let z = zone(&[("client.test", ELSEWHERE)]); + let up = fake_dot_zone(&pki, "upstream.test", z.clone()).await; + // Scheduled refreshes only every 60 s: only the trigger can help. + let p = start_proxy_acl( + &pki, + &dot_upstream(&pki, "upstream.test", up), + "allow_hosts = [\"client.test\"]", + &host_acl(60_000, 60_000, 60_000, 100), + ) + .await; + tokio::time::sleep(Duration::from_millis(300)).await; + set(&z, "client.test", LOCALHOST); + assert!( + becomes(p.udp, true, Duration::from_secs(3)).await, + "refreshed on reject" + ); +} + +#[tokio::test] +async fn allow_hosts_keeps_addresses_until_stale() { + let pki = Pki::new(); + let z = zone(&[("client.test", LOCALHOST)]); + let up = fake_dot_zone(&pki, "upstream.test", z.clone()).await; + let p = start_proxy_acl( + &pki, + &dot_upstream(&pki, "upstream.test", up), + "allow_hosts = [\"client.test\"]", + &host_acl(100, 200, 1_000, 50), + ) + .await; + assert!(becomes(p.udp, true, Duration::from_secs(3)).await); + + set(&z, "client.test", Rec::ServFail); + let failing_since = std::time::Instant::now(); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + udp_query(p.udp, &query(0x8201, "example.com", None), WAIT) + .await + .is_some(), + "still allowed within max_stale" + ); + assert!( + becomes(p.udp, false, Duration::from_secs(3)).await, + "dropped after max_stale" + ); + assert!(failing_since.elapsed() >= Duration::from_millis(700)); +} + +#[tokio::test] +async fn allow_hosts_nxdomain_rejects_at_once() { + let pki = Pki::new(); + let z = zone(&[("client.test", LOCALHOST)]); + let up = fake_dot_zone(&pki, "upstream.test", z.clone()).await; + let p = start_proxy_acl( + &pki, + &dot_upstream(&pki, "upstream.test", up), + "allow_hosts = [\"client.test\"]", + &host_acl(100, 200, 600_000, 50), + ) + .await; + assert!(becomes(p.udp, true, Duration::from_secs(3)).await); + set(&z, "client.test", Rec::NxDomain); + assert!(becomes(p.udp, false, Duration::from_secs(3)).await); +} + +#[tokio::test] +async fn doh_secret_path() { + let pki = Pki::new(); + let up = fake_dot(&pki, "upstream.test").await; + let (c, k) = pki.leaf("localhost"); + let toml = format!( + "[[listen]]\nproto = \"doh\"\naddr = \"127.0.0.1:0\"\nallow = [\"0.0.0.0/0\", \"::/0\"]\n\ + cert = \"{}\"\nkey = \"{}\"\npath = \"/dns-query/s3cr3t\"\n{}", + c.display(), + k.display(), + dot_upstream(&pki, "upstream.test", up) + ); + let proxy = dns_proxy::start(Config::parse(&toml).unwrap()).await.unwrap(); + let addr = proxy.bound[0].1; + let q = query(0, "example.com", None); + let (st, body) = doh( + &pki, + addr, + post("/dns-query/s3cr3t", "application/dns-message", q.clone()), + ) + .await; + assert_eq!(st, StatusCode::OK); + assert_answer(&body, 0); + for wrong in [ + "/dns-query", + "/dns-query/s3cr3", + "/dns-query/s3cr3t/", + "/dns-query/S3CR3T", + ] { + let (st, _) = doh(&pki, addr, post(wrong, "application/dns-message", q.clone())).await; + assert_eq!(st, StatusCode::NOT_FOUND, "{wrong}"); + } +} From 7dcd2613405c333e9347f21b94b9e0287770c1da Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 16:22:56 +0000 Subject: [PATCH 3/3] Add release workflow and documentation site Release (on tags vX.Y.Z): - Static musl binaries for x86_64 and aarch64 via cargo-zigbuild - Refuses to run when the tag and Cargo.toml version disagree - SHA256SUMS and GitHub build provenance attestations - Pre-release for tags with a suffix; actions pinned to commit SHAs Pages: - Single-page documentation in docs/, deployed from main via GitHub Actions (requires Pages source "GitHub Actions") - Styled with the Nullthrone design system: tokens vendored unchanged from Claude Design, components recreated in plain CSS, no JavaScript, light and dark via the OS preference README: install from releases with verification, release process. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011hHaUEqQpj7pg7F9XAM8Ce --- .github/workflows/pages.yml | 36 +++ .github/workflows/release.yml | 99 ++++++ README.md | 35 ++- docs/.nojekyll | 0 docs/assets/nullthrone-mark.svg | 12 + docs/assets/nullthrone.css | 149 +++++++++ docs/assets/site.css | 519 ++++++++++++++++++++++++++++++++ docs/index.html | 266 ++++++++++++++++ 8 files changed, 1114 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/pages.yml create mode 100644 .github/workflows/release.yml create mode 100644 docs/.nojekyll create mode 100644 docs/assets/nullthrone-mark.svg create mode 100644 docs/assets/nullthrone.css create mode 100644 docs/assets/site.css create mode 100644 docs/index.html diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..013b284 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,36 @@ +name: Pages + +# Publishes docs/ to GitHub Pages. Requires Settings → Pages → Source: +# "GitHub Actions". +on: + push: + branches: [main] + paths: ["docs/**", ".github/workflows/pages.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + deploy: + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5 + - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3 + with: + path: docs + - id: deployment + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a24519e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,99 @@ +name: Release + +# Push a tag `vX.Y.Z` matching the version in Cargo.toml to publish a release +# with static Linux binaries, SHA256SUMS and build provenance attestations. +on: + push: + tags: ["v*.*.*"] + +permissions: + contents: read + +jobs: + build: + name: build (${{ matrix.target }}) + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + target: [x86_64-unknown-linux-musl, aarch64-unknown-linux-musl] + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - name: Check tag matches Cargo.toml version + run: | + version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "Tag $GITHUB_REF_NAME does not match Cargo.toml version $version." >&2 + exit 1 + fi + + - uses: dtolnay/rust-toolchain@89b12181fb390509a0842a86cc55eeb8eb928c1d # stable + with: + targets: ${{ matrix.target }} + + # zig serves as C compiler/linker for ring when cross-compiling to musl. + # setup-python avoids the runner's externally managed system Python. + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: "3.12" + - name: Install cargo-zigbuild + run: pip install cargo-zigbuild==0.23.4 ziglang==0.16.0 + + - name: Test + run: cargo test --locked + + - name: Build + run: cargo zigbuild --locked --release --target ${{ matrix.target }} + + - name: Package + run: | + name="dns-proxy-${GITHUB_REF_NAME}-${{ matrix.target }}" + mkdir -p "pkg/$name/dist" + cp "target/${{ matrix.target }}/release/dns-proxy" "pkg/$name/" + cp LICENSE README.md config.example.toml "pkg/$name/" + cp dist/dns-proxy.service "pkg/$name/dist/" + tar -C pkg --owner=0 --group=0 --numeric-owner -czf "$name.tar.gz" "$name" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: ${{ matrix.target }} + path: dns-proxy-*.tar.gz + if-no-files-found: error + + release: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write # create the release + id-token: write # sign the provenance attestation + attestations: write # store the attestation + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + path: out + merge-multiple: true + + - name: Checksums + working-directory: out + run: sha256sum dns-proxy-*.tar.gz > SHA256SUMS && cat SHA256SUMS + + - uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2 + with: + subject-path: out/dns-proxy-*.tar.gz + + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + run: | + flags="" + case "$GITHUB_REF_NAME" in *-*) flags="--prerelease" ;; esac + gh release create "$GITHUB_REF_NAME" \ + --repo "$GITHUB_REPOSITORY" \ + --verify-tag \ + --generate-notes \ + --title "$GITHUB_REF_NAME" \ + $flags \ + out/dns-proxy-*.tar.gz out/SHA256SUMS diff --git a/README.md b/README.md index 71ecbad..382f507 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # dns-proxy -A small, no-frills DNS forwarder written in Rust. +A small, no-frills DNS forwarder written in Rust. Documentation: ``` clients ── plain DNS (UDP/TCP) ─┐ @@ -30,13 +30,44 @@ clients ── plain DNS (UDP/TCP) ─┐ - **Private logs.** Query names are never logged. - `#![forbid(unsafe_code)]`. The DNS wire handling is a small, bounds-checked parser with tests, including a random-input test that checks it never panics. -## Build +## Install + +Releases ship static Linux binaries for `x86_64` and `aarch64` (musl). Each release includes `SHA256SUMS` and a build provenance attestation: + +```sh +VERSION=v0.1.0 +TARGET=x86_64-unknown-linux-musl # or aarch64-unknown-linux-musl +BASE=https://github.com/nullthrone/dns-proxy/releases/download/$VERSION +curl -LO "$BASE/dns-proxy-$VERSION-$TARGET.tar.gz" +curl -LO "$BASE/SHA256SUMS" +sha256sum --ignore-missing -c SHA256SUMS +gh attestation verify "dns-proxy-$VERSION-$TARGET.tar.gz" --repo nullthrone/dns-proxy +tar xzf "dns-proxy-$VERSION-$TARGET.tar.gz" +install -m 0755 "dns-proxy-$VERSION-$TARGET/dns-proxy" /usr/local/bin/ +``` + +Or build from source: ```sh cargo build --release --locked install -m 0755 target/release/dns-proxy /usr/local/bin/ ``` +### Releasing + +1. Bump `version` in `Cargo.toml`, then commit. +2. Push a matching tag, e.g. `git tag v0.2.0 && git push origin v0.2.0`. + +The [release workflow](.github/workflows/release.yml) then: + +- tests and cross-builds with `cargo-zigbuild`; +- refuses to run if the tag and `Cargo.toml` disagree; +- publishes the archives with checksums and provenance. + +A tag with a suffix (e.g. `v0.2.0-rc.1`) becomes a pre-release. + +The documentation site lives in [`docs/`](docs/). It is deployed by the [Pages workflow](.github/workflows/pages.yml) on pushes to `main`. This requires *Settings → Pages → Source: GitHub Actions*. Its styling uses the Nullthrone design system tokens, vendored in `docs/assets/nullthrone.css`. + ## Configure ```sh diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/docs/assets/nullthrone-mark.svg b/docs/assets/nullthrone-mark.svg new file mode 100644 index 0000000..010089e --- /dev/null +++ b/docs/assets/nullthrone-mark.svg @@ -0,0 +1,12 @@ + +Nullthrone + + + + + + + + + + \ No newline at end of file diff --git a/docs/assets/nullthrone.css b/docs/assets/nullthrone.css new file mode 100644 index 0000000..c88b978 --- /dev/null +++ b/docs/assets/nullthrone.css @@ -0,0 +1,149 @@ +/* Nullthrone Design System tokens, vendored from Claude Design + (project 88786eea-8130-44cb-ad5f-43f563687fb9: tokens/*.css). Do not edit + here; update from the design system instead. Fonts are loaded in index.html. */ + +/* --- tokens/colors.css --- */ +:root{ +color-scheme:light; +/* Base — ink & paper */ +--ink-950:#141317;--ink-900:#1E1C21;--ink-700:#3A3740;--ink-500:#6E6B72;--ink-400:#928F96;--ink-300:#B6B3B8;--ink-200:#D9D6D3;--ink-100:#E9E6DF; +--paper:#F4F2EC;--paper-raised:#FBFAF6;--paper-white:#FFFFFF; +/* Brass — the single accent */ +--brass-700:#7A5A1F;--brass-600:#8F6B26;--brass-500:#A87E2F;--brass-400:#C09A4B;--brass-200:#E4D5AC;--brass-100:#EFE6CD; +/* Signals — muted, architectural */ +--green-600:#2F6B4F;--green-100:#DFEAE3; +--amber-600:#A05E14;--amber-100:#F3E5D2; +--red-600:#8C2F2E;--red-100:#F0DDDC; +/* Semantic aliases */ +--text-body:var(--ink-950);--text-muted:var(--ink-500);--text-faint:var(--ink-400);--text-inverse:var(--paper);--text-accent:var(--brass-600); +--surface-page:var(--paper);--surface-card:var(--paper-raised);--surface-inset:var(--ink-100);--surface-inverse:var(--ink-950); +--border-line:var(--ink-200);--border-strong:var(--ink-950);--border-mid:var(--ink-300); +--accent:var(--brass-500);--accent-hover:var(--brass-600);--accent-active:var(--brass-700); +--focus-ring:0 0 0 2px var(--paper),0 0 0 4px var(--brass-500); +--ok:var(--green-600);--ok-bg:var(--green-100);--warn:var(--amber-600);--warn-bg:var(--amber-100);--danger:var(--red-600);--danger-bg:var(--red-100); +--press-ink:#000000;--danger-hover:#7A2827;--danger-active:#682221; +--overlay-scrim:rgba(20,19,23,.5); +} + +/* Dark — the brand inverted at primitive level. ink and paper swap roles. + Ratios follow the kenny Fleet Console (t11z/kenny). Elevation is shadow, never a lighter plane. */ +[data-theme="dark"]{ +color-scheme:dark; +--ink-950:#EFEDE7;--ink-900:#DEDBD4;--ink-700:#B4B0A9;--ink-500:#8A8781;--ink-400:#6E6B67;--ink-300:#4C4952;--ink-200:#33313A;--ink-100:#100F13; +--paper:#17161A;--paper-raised:#1F1D22;--paper-white:#2B2930; +--brass-700:#B98B36;--brass-600:#DCB768;--brass-500:#C89E4A;--brass-400:#8F6B26;--brass-200:#4A3A1B;--brass-100:#2A2110; +--green-600:#6FA98C;--green-100:#1A2A23; +--amber-600:#D9853C;--amber-100:#2C2117; +--red-600:#CB6A62;--red-100:#2C1B1B; +--press-ink:#8A8781;--danger-hover:#A9524E;--danger-active:#8E4341; +--overlay-scrim:rgba(6,6,8,.66); +} +@media (prefers-color-scheme:dark){ +:root{ +color-scheme:dark; +--ink-950:#EFEDE7;--ink-900:#DEDBD4;--ink-700:#B4B0A9;--ink-500:#8A8781;--ink-400:#6E6B67;--ink-300:#4C4952;--ink-200:#33313A;--ink-100:#100F13; +--paper:#17161A;--paper-raised:#1F1D22;--paper-white:#2B2930; +--brass-700:#B98B36;--brass-600:#DCB768;--brass-500:#C89E4A;--brass-400:#8F6B26;--brass-200:#4A3A1B;--brass-100:#2A2110; +--green-600:#6FA98C;--green-100:#1A2A23; +--amber-600:#D9853C;--amber-100:#2C2117; +--red-600:#CB6A62;--red-100:#2C1B1B; +--press-ink:#8A8781;--danger-hover:#A9524E;--danger-active:#8E4341; +--overlay-scrim:rgba(6,6,8,.66); +} +} + +/* Light re-assertion — last in cascade so [data-theme="light"] wins over the OS-dark default, + letting a region turn back into the light inside a dark ground. */ +[data-theme="light"]{ +color-scheme:light; +/* Base — ink & paper */ +--ink-950:#141317;--ink-900:#1E1C21;--ink-700:#3A3740;--ink-500:#6E6B72;--ink-400:#928F96;--ink-300:#B6B3B8;--ink-200:#D9D6D3;--ink-100:#E9E6DF; +--paper:#F4F2EC;--paper-raised:#FBFAF6;--paper-white:#FFFFFF; +/* Brass — the single accent */ +--brass-700:#7A5A1F;--brass-600:#8F6B26;--brass-500:#A87E2F;--brass-400:#C09A4B;--brass-200:#E4D5AC;--brass-100:#EFE6CD; +/* Signals — muted, architectural */ +--green-600:#2F6B4F;--green-100:#DFEAE3; +--amber-600:#A05E14;--amber-100:#F3E5D2; +--red-600:#8C2F2E;--red-100:#F0DDDC; +/* Semantic aliases */ +--text-body:var(--ink-950);--text-muted:var(--ink-500);--text-faint:var(--ink-400);--text-inverse:var(--paper);--text-accent:var(--brass-600); +--surface-page:var(--paper);--surface-card:var(--paper-raised);--surface-inset:var(--ink-100);--surface-inverse:var(--ink-950); +--border-line:var(--ink-200);--border-strong:var(--ink-950);--border-mid:var(--ink-300); +--accent:var(--brass-500);--accent-hover:var(--brass-600);--accent-active:var(--brass-700); +--focus-ring:0 0 0 2px var(--paper),0 0 0 4px var(--brass-500); +--ok:var(--green-600);--ok-bg:var(--green-100);--warn:var(--amber-600);--warn-bg:var(--amber-100);--danger:var(--red-600);--danger-bg:var(--red-100); +--press-ink:#000000;--danger-hover:#7A2827;--danger-active:#682221; +--overlay-scrim:rgba(20,19,23,.5); +} + +/* --- tokens/typography.css --- */ +:root{ +--font-display:'Jost',system-ui,sans-serif; +--font-body:'Public Sans',system-ui,sans-serif; +--font-mono:'JetBrains Mono',ui-monospace,monospace; +/* Scale */ +--display-xl:56px;--display-lg:40px;--display-md:28px;--display-sm:20px; +--text-lg:18px;--text-md:15px;--text-sm:13px;--text-xs:11px; +/* Tracking — letterspaced caps are a core brand motif */ +--track-caps:0.14em;--track-caps-wide:0.22em;--track-display:0.01em; +--leading-tight:1.15;--leading-body:1.55; +--weight-display:500;--weight-body:400;--weight-strong:600; +} + +/* --- tokens/spacing.css --- */ +:root{ +--space-1:4px;--space-2:8px;--space-3:12px;--space-4:16px;--space-5:24px;--space-6:32px;--space-7:48px;--space-8:64px;--space-9:96px; +--control-h-sm:28px;--control-h-md:36px;--control-h-lg:44px; +--container-max:1120px;--container-pad:var(--space-6); +} + +/* --- tokens/effects.css --- */ +:root{ +/* Corners are square. --radius-1 exists only for tiny inner elements. */ +--radius-0:0px;--radius-1:2px; +--line:1px solid var(--border-line);--line-strong:1px solid var(--border-strong); +--shadow-1:0 1px 2px rgba(20,19,23,.07);--shadow-2:0 2px 8px rgba(20,19,23,.10);--shadow-3:0 12px 32px rgba(20,19,23,.16); +--ease:cubic-bezier(.2,0,0,1);/* @kind other */ +--dur-fast:120ms;/* @kind other */ +--dur-med:200ms;/* @kind other */ +--dur-slow:320ms;/* @kind other */ +} + +[data-theme="dark"]{ +--shadow-1:0 1px 2px rgba(0,0,0,.45); +--shadow-2:0 2px 10px rgba(0,0,0,.55); +--shadow-3:0 14px 38px rgba(0,0,0,.66); +} +@media (prefers-color-scheme:dark){ +:root{ +--shadow-1:0 1px 2px rgba(0,0,0,.45); +--shadow-2:0 2px 10px rgba(0,0,0,.55); +--shadow-3:0 14px 38px rgba(0,0,0,.66); +} +} + +[data-theme="light"]{ +/* Corners are square. --radius-1 exists only for tiny inner elements. */ +--radius-0:0px;--radius-1:2px; +--line:1px solid var(--border-line);--line-strong:1px solid var(--border-strong); +--shadow-1:0 1px 2px rgba(20,19,23,.07);--shadow-2:0 2px 8px rgba(20,19,23,.10);--shadow-3:0 12px 32px rgba(20,19,23,.16); +--ease:cubic-bezier(.2,0,0,1);/* @kind other */ +--dur-fast:120ms;/* @kind other */ +--dur-med:200ms;/* @kind other */ +--dur-slow:320ms;/* @kind other */ +} + +/* --- tokens/motion.css --- */ +/* Motion primitives — fades and small translates only; no bounces. */ +@keyframes nt-fade-up{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}} +@keyframes nt-fade-in{from{opacity:0}to{opacity:1}} +@keyframes nt-bar-pulse{0%,100%{transform:scaleY(.35);opacity:.5}50%{transform:scaleY(1);opacity:1}} +@keyframes nt-indeterminate{0%{left:-35%}100%{left:100%}} + +/* --- tokens/base.css --- */ +body{font-family:var(--font-body);font-size:var(--text-md);line-height:var(--leading-body);color:var(--text-body);background:var(--surface-page);margin:0;-webkit-font-smoothing:antialiased} +h1,h2,h3,h4{font-family:var(--font-display);font-weight:var(--weight-display);line-height:var(--leading-tight);letter-spacing:var(--track-display);margin:0} +code,pre{font-family:var(--font-mono)} +a{color:var(--text-body);text-decoration:underline;text-decoration-color:var(--brass-500);text-underline-offset:3px;transition:color var(--dur-fast) var(--ease)} +a:hover{color:var(--brass-600)} +::selection{background:var(--brass-200)} diff --git a/docs/assets/site.css b/docs/assets/site.css new file mode 100644 index 0000000..26ca3a8 --- /dev/null +++ b/docs/assets/site.css @@ -0,0 +1,519 @@ +/* dns-proxy documentation page. Built strictly on the Nullthrone tokens in + nullthrone.css: square corners, hairline structure, brass used sparingly. */ + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + scroll-behavior: smooth; + scroll-padding-top: var(--space-5); +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + *, + *::before, + *::after { + animation: none !important; + transition: none !important; + } +} + +:focus-visible { + outline: none; + box-shadow: var(--focus-ring); +} + +.container { + max-width: var(--container-max); + margin: 0 auto; + padding: 0 var(--container-pad); +} + +.skip { + position: absolute; + left: var(--space-4); + top: -100px; + padding: var(--space-2) var(--space-4); + background: var(--surface-card); + color: var(--text-body); + z-index: 10; +} +.skip:focus { + top: var(--space-4); +} + +/* ---------------------------------------------------------------- labels */ + +.caps { + font-family: var(--font-display); + font-weight: 500; + letter-spacing: var(--track-caps); + text-transform: uppercase; +} + +.eyebrow { + font-family: var(--font-display); + font-size: 12px; + font-weight: 500; + letter-spacing: var(--track-caps-wide); + text-transform: uppercase; + color: var(--text-accent); +} + +/* ---------------------------------------------------------------- header + hero */ + +.inverse { + background: var(--surface-inverse); + color: var(--text-inverse); +} +.inverse a { + color: var(--text-inverse); +} + +.site-header .container { + height: 64px; + display: flex; + align-items: center; + gap: var(--space-6); +} + +.brand { + display: flex; + align-items: center; + gap: var(--space-3); + text-decoration: none; +} +.brand svg { + width: 26px; + height: auto; + flex: none; +} +.brand .wordmark { + font-size: 14px; + letter-spacing: var(--track-caps-wide); +} +.brand .product { + font-size: 11px; + color: var(--brass-400); + padding-left: var(--space-3); + border-left: 1px solid var(--ink-700); +} + +.site-nav { + display: flex; + gap: var(--space-5); + margin-left: auto; +} +.site-nav a { + font-size: 11px; + color: var(--ink-300); + text-decoration: none; + border-bottom: 1px solid transparent; + padding-bottom: 2px; + transition: color var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease); +} +.site-nav a:hover { + color: var(--brass-400); + border-bottom-color: var(--brass-400); +} + +.hero { + border-top: 1px solid var(--ink-700); + padding: var(--space-9) 0 var(--space-8); + text-align: center; +} +.hero .eyebrow { + color: var(--brass-400); +} +.hero h1 { + font-size: var(--display-xl); + margin: var(--space-4) 0 var(--space-5); + animation: nt-fade-up var(--dur-med) var(--ease); +} +.hero .lead { + max-width: 640px; + margin: 0 auto; + font-size: var(--text-lg); + color: var(--ink-300); +} +.hero .actions { + display: flex; + justify-content: center; + flex-wrap: wrap; + gap: var(--space-4); + margin-top: var(--space-6); +} + +.ornament { + display: flex; + align-items: center; + justify-content: center; + margin-top: var(--space-7); +} +.ornament span { + width: 56px; + border-top: 1px solid var(--ink-500); +} +.ornament svg { + width: 22px; + height: auto; + margin: 0 var(--space-3); +} + +/* ---------------------------------------------------------------- buttons */ + +.btn { + display: inline-flex; + align-items: center; + height: var(--control-h-lg); + padding: 0 var(--space-5); + border: 1px solid transparent; + border-radius: var(--radius-0); + font-family: var(--font-display); + font-size: 13px; + font-weight: 500; + letter-spacing: var(--track-caps); + text-transform: uppercase; + text-decoration: none; + white-space: nowrap; + transition: background var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease); +} +.btn-accent, +.inverse .btn-accent { + background: var(--accent); + color: var(--paper); +} +.btn-accent:hover, +.inverse .btn-accent:hover { + background: var(--accent-hover); + color: var(--paper); +} +.btn-accent:active { + background: var(--accent-active); +} +.btn-outline-inverse { + border-color: var(--text-inverse); +} +.inverse .btn-outline-inverse:hover { + background: var(--ink-900); + color: var(--text-inverse); +} + +/* ---------------------------------------------------------------- sections */ + +main section { + padding: var(--space-8) 0; + border-bottom: var(--line); +} +main section:last-child { + border-bottom: 0; +} + +.section-head { + margin-bottom: var(--space-6); +} +.section-head h2 { + font-size: var(--display-lg); + margin-top: var(--space-2); +} +.section-head p { + max-width: 720px; + margin: var(--space-4) 0 0; + color: var(--text-muted); +} + +.double-rule { + border-top: var(--line-strong); + margin: 0; +} +.double-rule::after { + content: ""; + display: block; + border-top: var(--line-strong); + margin-top: 3px; +} + +h3 { + font-size: var(--display-sm); + margin-bottom: var(--space-3); +} + +p { + margin: 0 0 var(--space-4); +} + +ul.plain { + margin: 0; + padding: 0; + list-style: none; +} +ul.plain li { + padding: var(--space-2) 0; + border-top: var(--line); +} +ul.plain li:first-child { + border-top: 0; +} + +.grid-3 { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 20px; +} + +/* Columns divided by hairlines where structure matters. */ +.ruled-2 { + display: grid; + grid-template-columns: 1fr 1fr; + border-top: var(--line); +} +.ruled-2 > div { + padding: var(--space-5) var(--space-5) var(--space-5) 0; + border-bottom: var(--line); +} +.ruled-2 > div:nth-child(2n) { + padding-left: var(--space-5); + padding-right: 0; + border-left: var(--line); +} +.ruled-2 h3 { + font-size: var(--text-lg); +} +.ruled-2 p { + margin: 0; + color: var(--text-muted); +} + +/* ---------------------------------------------------------------- card, badge, tag */ + +.card { + background: var(--surface-card); + border: var(--line); + box-shadow: var(--shadow-1); + padding: var(--space-5); +} +.card .eyebrow { + font-size: 11px; + letter-spacing: var(--track-caps); + margin-bottom: var(--space-2); +} +.card h3 { + margin-bottom: var(--space-3); +} +.card ul.plain li { + font-size: var(--text-sm); +} +.card .note { + margin: var(--space-4) 0 0; + padding-top: var(--space-3); + border-top: var(--line); + font-size: var(--text-sm); + color: var(--text-muted); +} + +.badge { + display: inline-flex; + align-items: center; + height: 20px; + padding: 0 var(--space-2); + font-family: var(--font-display); + font-size: 10px; + font-weight: 500; + letter-spacing: var(--track-caps); + text-transform: uppercase; + vertical-align: middle; +} +.badge-brass { + background: var(--brass-100); + color: var(--brass-700); + border: 1px solid var(--brass-400); +} +.badge-neutral { + background: var(--surface-inset); + color: var(--ink-700); + border: 1px solid var(--ink-300); +} + +.tag { + display: inline-flex; + align-items: center; + height: 24px; + padding: 0 var(--space-2); + border: var(--line); + background: var(--paper-white); + color: var(--ink-700); + font-family: var(--font-mono); + font-size: 12px; +} + +/* ---------------------------------------------------------------- steps + code */ + +.steps { + counter-reset: step; + display: grid; + gap: var(--space-6); +} +.step { + display: grid; + grid-template-columns: 48px 1fr; + gap: var(--space-4); +} +.step::before { + counter-increment: step; + content: counter(step, decimal-leading-zero); + font-family: var(--font-display); + font-size: var(--display-sm); + font-weight: 500; + color: var(--text-accent); + border-top: var(--line-strong); + padding-top: var(--space-2); +} +.step > div { + min-width: 0; + border-top: var(--line); + padding-top: var(--space-2); +} +.step p { + color: var(--text-muted); +} + +pre { + margin: 0; + padding: var(--space-4) var(--space-5); + background: var(--surface-card); + border: var(--line); + font-size: var(--text-sm); + line-height: 1.7; + overflow-x: auto; +} +pre .c { + color: var(--text-muted); +} +code { + font-size: 0.92em; +} +p code, +li code, +td code { + padding: 1px 4px; + background: var(--surface-inset); +} + +/* ---------------------------------------------------------------- table */ + +.table-wrap { + overflow-x: auto; + border-top: var(--line-strong); +} +table { + width: 100%; + border-collapse: collapse; + font-size: var(--text-sm); +} +th { + font-family: var(--font-display); + font-size: 11px; + font-weight: 500; + letter-spacing: var(--track-caps); + text-transform: uppercase; + color: var(--text-muted); + text-align: left; + padding: var(--space-3) var(--space-4) var(--space-3) 0; + border-bottom: var(--line); +} +td { + vertical-align: top; + padding: var(--space-3) var(--space-4) var(--space-3) 0; + border-bottom: var(--line); +} +td:first-child { + white-space: nowrap; +} + +.table-note { + margin: var(--space-4) 0 0; + font-size: var(--text-sm); + color: var(--text-muted); +} + +.span-2 { + grid-column: span 2; +} + +.split { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-6); + align-items: start; +} + +/* ---------------------------------------------------------------- footer */ + +.site-footer .container { + padding-top: var(--space-7); + padding-bottom: var(--space-7); + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: var(--space-5); +} +.site-footer p { + margin: 0; + font-size: var(--text-sm); + color: var(--ink-300); +} + +/* ---------------------------------------------------------------- narrow screens */ + +@media (max-width: 860px) { + .grid-3, + .split { + grid-template-columns: 1fr; + } + .span-2 { + grid-column: auto; + } + .ruled-2 { + grid-template-columns: 1fr; + } + .ruled-2 > div, + .ruled-2 > div:nth-child(2n) { + padding: var(--space-4) 0; + border-left: 0; + } +} + +@media (max-width: 640px) { + :root { + --container-pad: var(--space-4); + } + .site-nav a:not(.keep) { + display: none; + } + .brand .product { + display: none; + } + .hero { + padding: var(--space-8) 0 var(--space-7); + } + .hero h1 { + font-size: var(--display-lg); + } + .section-head h2 { + font-size: var(--display-md); + } + .step { + grid-template-columns: 1fr; + gap: var(--space-2); + } + .step > div { + border-top: 0; + } +} diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..459a441 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,266 @@ + + + + + +dns-proxy · Nullthrone + + + + + + + + + + + + + + +
+ + +
+
+
Open source · MIT license · Rust
+

A DNS proxy. Nothing more.

+

Plain DNS, DNS over TLS and DNS over HTTPS in. Only encrypted DNS out. Every listener is closed until you name who may use it.

+ + +
+
+
+ +
+
+ +
+
+
Scope
+

What it does, and what it does not

+

A forwarder for one job: take DNS queries from clients you allow and pass them to resolvers you trust, encrypted. Everything else stays out, because every feature is code you have to trust.

+
+
+
+
Inbound
+

Four protocols

+
    +
  • Plain DNS over UDP and TCP
  • +
  • DNS over TLS (RFC 7858)
  • +
  • DNS over HTTPS (RFC 8484), HTTP/1.1 and HTTP/2, GET and POST
  • +
  • Allowlist per listener: networks and hostnames
  • +
+
+
+
Outbound
+

Encrypted only

+
    +
  • DoT or DoH upstreams, tried in order
  • +
  • A failing upstream is moved to the back for 30 s
  • +
  • Upstreams reached by configured IPs; no plain-DNS bootstrap
  • +
  • Certificates verified against Mozilla roots or your CA
  • +
+
+
+
Not included
+

By decision

+
    +
  • No cache, no filtering, no statistics endpoint
  • +
  • No ACME; certificates come from files
  • +
  • No HTTP/3
  • +
  • No DNSSEC validation; the upstream resolver validates
  • +
+
+
+
+ +
+
+
Install
+

Three steps

+

Releases ship static binaries for x86_64 and aarch64 Linux. They have no runtime dependencies. Each archive is listed in SHA256SUMS and carries a build provenance attestation from GitHub Actions.

+
+
+
+
+

Download and verify

+

Check the checksum, then check that the archive was built by this repository's release workflow.

+
VERSION=v0.1.0
+TARGET=x86_64-unknown-linux-musl   # or aarch64-unknown-linux-musl
+BASE=https://github.com/nullthrone/dns-proxy/releases/download/$VERSION
+
+curl -LO "$BASE/dns-proxy-$VERSION-$TARGET.tar.gz"
+curl -LO "$BASE/SHA256SUMS"
+sha256sum --ignore-missing -c SHA256SUMS
+gh attestation verify "dns-proxy-$VERSION-$TARGET.tar.gz" --repo nullthrone/dns-proxy
+
+
+
+
+

Install and check the configuration

+

--check validates the configuration and loads all certificates without binding a socket.

+
tar xzf "dns-proxy-$VERSION-$TARGET.tar.gz" && cd "dns-proxy-$VERSION-$TARGET"
+install -m 0755 dns-proxy /usr/local/bin/
+install -d /etc/dns-proxy
+install -m 0644 config.example.toml /etc/dns-proxy/config.toml
+dns-proxy --config /etc/dns-proxy/config.toml --check
+
+
+
+
+

Run under systemd

+

The unit runs the proxy as a transient unprivileged user. Its only capability is binding ports below 1024, inside a strict sandbox. Certificates are passed in with LoadCredential=, so the private key can stay readable by root only.

+
install -m 0644 dist/dns-proxy.service /etc/systemd/system/
+systemctl daemon-reload
+systemctl enable --now dns-proxy
+systemd-analyze security dns-proxy
+
+
+
+
+ +
+
+
Configure
+

One TOML file

+

Unknown keys are errors. Missing allowlists are errors. Nothing ambiguous is filled in with a default.

+
+
+
# Local clients, plain DNS
+[[listen]]
+proto = "udp"
+addr = "127.0.0.1:53"
+allow = ["127.0.0.0/8"]
+
+# Remote clients, DNS over TLS
+[[listen]]
+proto = "dot"
+addr = "0.0.0.0:853"
+allow = ["192.168.0.0/16"]
+allow_hosts = ["home.dyndns.example"]
+cert = "${CREDENTIALS_DIRECTORY}/cert.pem"
+key = "${CREDENTIALS_DIRECTORY}/key.pem"
+
+[[upstream]]
+type = "dot"
+name = "dns.quad9.net"
+addrs = ["9.9.9.9:853", "149.112.112.112:853"]
+
+[[upstream]]
+type = "doh"
+url = "https://cloudflare-dns.com/dns-query"
+addrs = ["1.1.1.1:443", "1.0.0.1:443"]
+
+ + + + + + + + +
SectionKeys
[[listen]]proto (udp, tcp, dot, doh), addr, allow and/or allow_hosts. For dot and doh also cert and key; for doh optionally path.
[[upstream]]type = "dot" with name, or type = "doh" with url. Always addrs: the IPs to connect to. Optional ca_file.
[limits]Concurrency caps and timeouts. All optional.
[host_acl]Refresh timing for allow_hosts. All optional.
+

The full reference with all defaults is config.example.toml.

+
+
+
+ +
+
+
Dynamic client IPs
+

Admit clients that move

+

Clients on networks with a changing public IP can use the proxy over the internet. The upstreams then see one static address. There are two ways to admit such clients. They are not equally strong.

+
+
+
+
By hostname
+

allow_hosts IP-based

+

The proxy resolves DynDNS names in the background, through the encrypted upstreams. It never resolves per query and never uses the system resolver.

+
    +
  • The refresh follows the record TTL. A rejected client triggers an early refresh, at most every 15 s.
  • +
  • Fail closed until the first answer. NXDOMAIN removes the addresses at once.
  • +
  • If lookups fail, the last addresses stay valid for one hour.
  • +
  • IPv4 matches the exact address. IPv6 matches its /64; adjust with v6_prefix.
  • +
+

What you trust: the DynDNS account becomes the credential. Behind CGNAT, the IPv4 is shared with strangers. After an IP change, the old address stays admitted until the next refresh. Use DoT or DoH for such listeners; plain UDP sources can be spoofed.

+
+
+
By token
+

Secret DoH path Stronger

+

Admission by credential, independent of the client's address. The path travels inside TLS and is compared in constant time.

+
[[listen]]
+proto = "doh"
+addr = "0.0.0.0:443"
+allow = ["0.0.0.0/0", "::/0"]
+path = "/dns-query/<token>"
+

Generate the token with openssl rand -hex 16. Treat the client configuration like a password.

+
+
+
+ +
+
+
Security model
+

Properties, stated plainly

+
+
+
+

Closed by default

A listener without allow or allow_hosts is a configuration error. An open resolver requires writing 0.0.0.0/0 on purpose.

+

No plain DNS of its own

Upstreams are reached by IP. Hostnames serve only SNI and certificate checks. Allowlist names resolve through the encrypted upstreams.

+

Verified responses

An upstream answer must repeat the question and the expected ID. DoT queries carry a fresh random ID; DoH queries use ID 0.

+

Bounded amplification

UDP answers never exceed the client's EDNS size or 1232 bytes. Larger answers are truncated, and the client retries over TCP.

+

Bounded resources

Connections, queries in flight, handshakes, idle time, headers and request bodies all have limits.

+

Private by default

Query names are never logged. Failures are logged once per outage, not once per query.

+

No unsafe code

#![forbid(unsafe_code)]. The DNS parser checks every bound and is tested against random input.

+

Verifiable releases

Static binaries, SHA-256 checksums and signed build provenance. Actions in the release workflow are pinned to commit hashes.

+
+
+ +
+
+ + + +