Add 'conformance/' from commit '2a86c07974b27af6de6cdb0cc87074aaf57b8c39'

git-subtree-dir: conformance
git-subtree-mainline: f1489da675
git-subtree-split: 2a86c07974
This commit is contained in:
Jorge Aparicio 2024-06-07 11:03:57 +02:00
commit 2a04299fbc
58 changed files with 6439 additions and 0 deletions

52
conformance/.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,52 @@
name: CI
on:
pull_request:
branches: [main]
merge_group:
env:
HICKORY_REV: 107635c6c5934524894736f1b141198d0fa62fec
DNS_TEST_VERBOSE_DOCKER_BUILD: 1
jobs:
ci:
name: Continuous Integration
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Install ${{ matrix.rust }} toolchain
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
components: clippy, rustfmt
- name: Run dns-test tests
run: cargo test -p dns-test -- --include-ignored
- name: Run tests against unbound
run: DNS_TEST_PEER=bind cargo test -p conformance-tests -- --include-ignored
- name: Run tests against BIND
run: DNS_TEST_SUBJECT=bind cargo test -p conformance-tests -- --include-ignored
- name: Run tests against hickory
run: |
git clone https://github.com/hickory-dns/hickory-dns /tmp/hickory
( cd /tmp/hickory && git reset --hard ${{ env.HICKORY_REV }} )
DNS_TEST_SUBJECT="hickory /tmp/hickory" cargo test -p conformance-tests
- name: Check that ignored tests fail with hickory
run: |
tmpfile="$(mktemp)"
DNS_TEST_SUBJECT="hickory /tmp/hickory" cargo test -p conformance-tests -- --ignored | tee "$tmpfile"
grep 'test result: FAILED. 0 passed' "$tmpfile" || ( echo "expected ALL tests to fail but at least one passed; the passing tests must be un-#[ignore]-d" && exit 1 )
- name: Check that code is formatted
run: cargo fmt --all -- --check
- name: Lint code
run: cargo clippy --workspace --all-targets -- -D warnings

1
conformance/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

734
conformance/Cargo.lock generated Normal file
View File

@ -0,0 +1,734 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "base64"
version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"
[[package]]
name = "bumpalo"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
[[package]]
name = "cc"
version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
dependencies = [
"libc",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b"
dependencies = [
"android-tzdata",
"iana-time-zone",
"num-traits",
"serde",
"windows-targets",
]
[[package]]
name = "conformance-tests"
version = "0.1.0"
dependencies = [
"base64",
"dns-test",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "ctrlc"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b467862cc8610ca6fc9a1532d7777cee0804e678ab45410897b9396495994a0b"
dependencies = [
"nix",
"windows-sys",
]
[[package]]
name = "darling"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc5d6b04b3fd0ba9926f945895de7d806260a2d7431ba82e7edaecb043c4c6b8"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04e48a959bcd5c761246f5d090ebc2fbf7b9cd527a492b07a67510c108f1e7e3"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1545d67a2149e1d93b7e5c7752dce5a7426eb5d1357ddcfd89336b94444f77"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "deranged"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4"
dependencies = [
"powerfmt",
"serde",
]
[[package]]
name = "diff"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
[[package]]
name = "dns-test"
version = "0.1.0"
dependencies = [
"ctrlc",
"lazy_static",
"minijinja",
"pretty_assertions",
"serde",
"serde_json",
"serde_with",
"tempfile",
"url",
]
[[package]]
name = "equivalent"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "errno"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"
dependencies = [
"percent-encoding",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "iana-time-zone"
version = "0.1.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6"
dependencies = [
"unicode-bidi",
"unicode-normalization",
]
[[package]]
name = "indexmap"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
dependencies = [
"autocfg",
"hashbrown 0.12.3",
"serde",
]
[[package]]
name = "indexmap"
version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "233cf39063f058ea2caae4091bf4a3ef70a653afbc026f5c4a4135d114e3c177"
dependencies = [
"equivalent",
"hashbrown 0.14.3",
"serde",
]
[[package]]
name = "itoa"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
[[package]]
name = "js-sys"
version = "0.3.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "406cda4b368d531c842222cf9d2600a9a4acce8d29423695379c6868a143a9ee"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]]
name = "linux-raw-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
[[package]]
name = "log"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "minijinja"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fe0ff215195a22884d867b547c70a0c4815cbbcc70991f281dca604b20d10ce"
dependencies = [
"serde",
]
[[package]]
name = "nix"
version = "0.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053"
dependencies = [
"bitflags 2.4.2",
"cfg-if",
"libc",
]
[[package]]
name = "num-conv"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
[[package]]
name = "num-traits"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "percent-encoding"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "pretty_assertions"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66"
dependencies = [
"diff",
"yansi",
]
[[package]]
name = "proc-macro2"
version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "rustix"
version = "0.38.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949"
dependencies = [
"bitflags 2.4.2",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "ryu"
version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c"
[[package]]
name = "serde"
version = "1.0.196"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.196"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.113"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "serde_with"
version = "3.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15d167997bd841ec232f5b2b8e0e26606df2e7caa4c31b95ea9ca52b200bd270"
dependencies = [
"base64",
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.2.3",
"serde",
"serde_derive",
"serde_json",
"serde_with_macros",
"time",
]
[[package]]
name = "serde_with_macros"
version = "3.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "865f9743393e638991566a8b7a479043c2c8da94a33e0a31f18214c9cae0a64d"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "2.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa"
dependencies = [
"cfg-if",
"fastrand",
"redox_syscall",
"rustix",
"windows-sys",
]
[[package]]
name = "time"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749"
dependencies = [
"deranged",
"itoa",
"num-conv",
"powerfmt",
"serde",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
[[package]]
name = "time-macros"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774"
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "tinyvec"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "unicode-bidi"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75"
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-normalization"
version = "0.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
dependencies = [
"tinyvec",
]
[[package]]
name = "url"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1e124130aee3fb58c5bdd6b639a0509486b0338acaaae0c84a5124b0f588b7f"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9e7e1900c352b609c8488ad12639a311045f40a35491fb69ba8c12f758af70b"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b30af9e2d358182b5c7449424f017eba305ed32a7010509ede96cdc4696c46ed"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838"
[[package]]
name = "windows-core"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets",
]
[[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-targets"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef"
[[package]]
name = "windows_i686_gnu"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313"
[[package]]
name = "windows_i686_msvc"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04"
[[package]]
name = "yansi"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"

3
conformance/Cargo.toml Normal file
View File

@ -0,0 +1,3 @@
[workspace]
members = ["packages/*"]
resolver = "2"

202
conformance/LICENSE-APACHE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

17
conformance/LICENSE-MIT Normal file
View File

@ -0,0 +1,17 @@
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

167
conformance/README.md Normal file
View File

@ -0,0 +1,167 @@
# `dnssec-tests`
This repository contains two packages:
- `dns-test`. This is a test framework (library) for testing DNS implementations.
- `conformance-tests`. This is a collection of DNS, mainly DNSSEC, tests.
## Requirements
To use the code in this repository you need:
- a stable Rust toolchain to build the code
- a working Docker setup that can run *Linux* containers -- the host OS does not need to be Linux
## `dns-test`
This test framework was built with the following design goals and constraints in mind:
- Tests must work without access to the internet. That is, tests cannot rely on external services like `1.1.1.1`, `8.8.8.8`, `a.root-servers.net.`, etc. To this effect, each test runs into its own ephemeral network isolated from the internet and from the networks of other tests running concurrently.
- Test code must be decoupled from the API of any DNS implementation. That is, DNS implementation specific details (library/FFI calls, configuration files) must not appear in test code. To this end, interaction with DNS implementations is done at the network level using tools like `dig`, `delv` and `tshark`.
- It must be possible to switch the 'implementation under test' at runtime. In other words, one should not need to recompile the tests to switch the DNS implementation being tested. To this end, the `DNS_TEST_SUBJECT` environment variable is used to switch the DNS implementation that'll be tested.
### Test drive
To start a small DNS network using the `dns-test` framework run this command and follow the instructions to interact with the DNS network.
``` console
$ cargo run --example explore
```
By default, this will use `unbound` as the resolver. You can switch the resolver to `hickory-dns` using the `DNS_TEST_SUBJECT` environment variable:
``` shell
$ DNS_TEST_SUBJECT="hickory https://github.com/hickory-dns/hickory-dns" cargo run --example explore
```
### Environment variables
- `DNS_TEST_SUBJECT`. This variable controls what the `dns_test::subject` function returns. The variable can contain one of these values:
- `unbound`
- `hickory $REPOSITORY`. where `$REPOSITORY` is a placeholder for git repository. Examples values for `$REPOSITORY`: `https://github.com/hickory-dns/hickory-dns`; `/home/user/git-repos/hickory-dns`. NOTE: when using a local repository, changes that have not been committed, regardless of whether they are staged or not, will **not** be included in the `hickory-dns` build.
- `DNS_TEST_VERBOSE_DOCKER_BUILD`. Setting this variable prints the output of the `docker build` invocations that the framework does to the console. This is useful to verify that image caching is working; for example if you set `DNS_TEST_SUBJECT` to a local `hickory-dns` repository then consecutively running the `explore` example and/or `conformance-tests` test suite **must** not rebuild `hickory-dns` provided that you have not *committed* any new change to the local repository.
### Automatic clean-up
`dns-test` has been designed to clean up, that is remove, the Docker containers and Docker networks that it creates.
If you use `dns-test` and it does not clean up Docker resources, that's a bug that should be reported.
`dns-test` uses destructors (the `Drop` trait) to clean up resources.
If you forcefully terminate a process, e.g. using Ctrl+C or a signal like SIGINT, that uses `dns-test` then the destructors won't run and Docker resources won't be cleaned up.
Note that `cargo watch` terminates the last process using signals before starting a new instance of it.
Therefore we advise against using `cargo watch` to *run* tests that use the `dns-test` framework;
using `cargo-watch` to `check` such tests is perfectly fine, however.
### Writing tests
Here are some considerations when writing tests.
- Both `unbound` and BIND, in the resolver role, will initially query for the A record of their configured root server's FQDN as well as the A records of all the name servers covering the zones required to resolve the root server's FQDN. As of [49c89f7], All the name servers have a FQDN of the form `primaryNNN.nameservers.com.`, where `NNN` is a non-negative integer. These initial `A primaryNNN.nameservers.com.` queries will be sent to the name server that covers the `nameservers.com.` zone. What all this means in practice, is that you'll need to add these A records -- the root server's, `com.`'s name server and `nameservers.com.`'s name server -- to the `nameservers.com.` zone file; if you don't, most queries (expect perhaps for `SOA .`) will fail to resolve with return code SERVFAIL.
[49c89f7]: https://github.com/ferrous-systems/dnssec-tests/commit/49c89f764ede89aefe578b799e7766f051a600cc
``` rust
let root_ns: NameServer; // for `.` zone
let com_ns: NameServer; // for `com.` zone
let nameservers_ns: NameServer; // for `nameservers.com.` zone
nameservers_ns
.add(root_ns.a())
.add(com_ns.a());
// each `NameServer` will start out with an A record of its FQDN to its own IPv4 address in its
// zone file so NO need to add that one in the preceding statement
```
- To get resolution to work, you need referrals -- in the form of NS and A record pairs -- from parent zones to child zones. Check the [`dns::scenarios::can_resolve`] for an example of how to set up referrals.
[`dns::scenarios::can_resolve`]: https://github.com/ferrous-systems/dnssec-tests/blob/49c89f764ede89aefe578b799e7766f051a600cc/packages/conformance-tests/src/resolver/dns/scenarios.rs#L10
- To get DNSSEC validation to work, you need the DS record of the child zone in the parent zone. Furthermore, the DS record needs to be signed using parent zone's key. Check the [`dnssec::scenarios::secure::can_validate_with_delegation`] for an example of how to set up the DS records.
[`dnssec::scenarios::secure::can_validate_with_delegation`]: https://github.com/ferrous-systems/dnssec-tests/blob/49c89f764ede89aefe578b799e7766f051a600cc/packages/conformance-tests/src/resolver/dnssec/scenarios/secure.rs#L48
- You can get the logs of both a `Resolver` and `NameServer` using the `terminate` method. This method terminates the server and returns all the logs. This can be useful when trying to figure out why a query is not producing the expected results.
``` rust
let resolver: Resolver;
let ans = client.dig(/* .. */);
let logs = resolver.terminate()?;
// print the logs to figure out ...
eprintln!("{logs}");
// ... why this assertion is not working
assert!(ans.status.is_noerror());
```
## `conformance-tests`
This is a collection of tests that check the conformance of a DNS implementation to the different RFCs around DNS and DNSSEC.
### Running the test suite
To run the conformance tests against `unbound` run:
``` console
$ cargo test -p conformance-tests -- --include-ignored
```
To run the conformance tests against `hickory-dns` run:
``` console
$ DNS_TEST_SUBJECT="hickory /path/to/repository" cargo test -p conformance-tests
```
### Test organization
The module organization is not yet set in stone but currently uses the following structure:
``` console
packages/conformance-tests/src
├── lib.rs
├── resolver
│ ├── dns
│ │ └── scenarios.rs
│ ├── dns.rs
│ ├── dnssec
│ │ ├── rfc4035
│ │ │ ├── section_4
│ │ │ │ └── section_4_1.rs
│ │ │ └── section_4.rs
│ │ ├── rfc4035.rs
│ │ └── scenarios.rs
│ └── dnssec.rs
└── resolver.rs
```
The modules in the root correspond to the *role* being tested: `resolver` (recursive resolver), `name-server` (authoritative-only name server), etc.
The next module level contains the *functionality* being tested: (plain) DNS, DNSSEC, NSEC3, etc.
The next module level contains the RFC documents, whose requirements are being tested: RFC4035, etc.
The next module levels contain sections, subsections and any other subdivision that may be relevant.
At the RFC module level there's a special module called `scenarios`. This module contains tests that map to representative use cases of the parent functionality. Each use case can be tested in successful and failure scenarios, hence the name. The organization within this module will be ad hoc.
### Adding tests and the use of `#[ignore]`
When adding a new test to the test suite, it must pass with the `unbound` implementation, which is treated as the *reference* implementation. The CI workflow will check that *all* tests, including the ones that have the `#[ignore]` attribute, pass with the `unbound` implementation.
New tests that don't pass with the `hickory-dns` implementation must be marked as `#[ignore]`-d. The CI workflow will check that non-`#[ignore]`-d tests pass with the `hickory-dns` implementation. Additionally, the CI workflow will check that all `#[ignore]`-d tests *fail* with the `hickory-dns` implementation; this is to ensure that fixed tests get un-`#[ignore]`-d.
## License
Licensed under either of
- Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <https://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <https://opensource.org/licenses/MIT>)
at your option.

View File

@ -0,0 +1,13 @@
[package]
edition = "2021"
license = "MIT OR Apache-2.0"
name = "conformance-tests"
publish = false
version = "0.1.0"
[dependencies]
base64 = "0.21.7"
dns-test.path = "../dns-test"
[lib]
doctest = false

View File

@ -0,0 +1,4 @@
#![cfg(test)]
mod name_server;
mod resolver;

View File

@ -0,0 +1,2 @@
mod rfc4035;
mod scenarios;

View File

@ -0,0 +1 @@
mod section_3;

View File

@ -0,0 +1 @@
mod section_3_1;

View File

@ -0,0 +1 @@
mod section_3_1_1;

View File

@ -0,0 +1,64 @@
use dns_test::client::{Client, DigSettings};
use dns_test::name_server::NameServer;
use dns_test::record::{Record, RecordType};
use dns_test::{Network, Result, FQDN};
#[test]
#[ignore]
fn rrsig_in_answer_section() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&dns_test::SUBJECT, FQDN::ROOT, &network)?
.sign()?
.start()?;
let client = Client::new(&network)?;
let ns_fqdn = ns.fqdn();
let ans = client.dig(
*DigSettings::default().dnssec(),
ns.ipv4_addr(),
RecordType::A,
ns_fqdn,
)?;
assert!(ans.status.is_noerror());
let [a, rrsig] = ans.answer.try_into().unwrap();
assert!(matches!(a, Record::A(..)));
let rrsig = rrsig.try_into_rrsig().unwrap();
assert_eq!(RecordType::A, rrsig.type_covered);
assert_eq!(ns_fqdn, &rrsig.fqdn);
Ok(())
}
#[test]
#[ignore]
fn rrsig_in_authority_section() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&dns_test::SUBJECT, FQDN::ROOT, &network)?
.sign()?
.start()?;
let client = Client::new(&network)?;
let ans = client.dig(
*DigSettings::default().dnssec(),
ns.ipv4_addr(),
RecordType::SOA,
&FQDN::ROOT,
)?;
assert!(ans.status.is_noerror());
let [ns, rrsig] = ans.authority.try_into().unwrap();
assert!(matches!(ns, Record::NS(..)));
let rrsig = rrsig.try_into_rrsig().unwrap();
assert_eq!(RecordType::NS, rrsig.type_covered);
assert_eq!(FQDN::ROOT, rrsig.fqdn);
Ok(())
}
// TODO Additional section
// TODO TC bit

View File

@ -0,0 +1,23 @@
use dns_test::client::{Client, DigSettings};
use dns_test::name_server::NameServer;
use dns_test::record::RecordType;
use dns_test::{Network, Result, FQDN};
#[test]
fn authoritative_answer() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&dns_test::SUBJECT, FQDN::ROOT, network)?.start()?;
let client = Client::new(network)?;
let ans = client.dig(
DigSettings::default(),
ns.ipv4_addr(),
RecordType::SOA,
&FQDN::ROOT,
)?;
assert!(ans.status.is_noerror());
assert!(ans.flags.authoritative_answer);
Ok(())
}

View File

@ -0,0 +1,4 @@
//! Recursive resolver role
mod dns;
mod dnssec;

View File

@ -0,0 +1,3 @@
//! plain DNS functionality
mod scenarios;

View File

@ -0,0 +1,68 @@
use std::net::Ipv4Addr;
use dns_test::client::{Client, DigSettings};
use dns_test::name_server::{Graph, NameServer, Sign};
use dns_test::record::{Record, RecordType};
use dns_test::{Network, Resolver, Result, FQDN};
#[test]
fn can_resolve() -> Result<()> {
let expected_ipv4_addr = Ipv4Addr::new(1, 2, 3, 4);
let needle_fqdn = FQDN("example.nameservers.com.")?;
let network = Network::new()?;
let mut leaf_ns = NameServer::new(&dns_test::PEER, FQDN::NAMESERVERS, &network)?;
leaf_ns.add(Record::a(needle_fqdn.clone(), expected_ipv4_addr));
let Graph {
nameservers: _nameservers,
root,
..
} = Graph::build(leaf_ns, Sign::No)?;
let resolver = Resolver::new(&network, root).start(&dns_test::SUBJECT)?;
let resolver_ip_addr = resolver.ipv4_addr();
let client = Client::new(&network)?;
let settings = *DigSettings::default().recurse();
let output = client.dig(settings, resolver_ip_addr, RecordType::A, &needle_fqdn)?;
assert!(output.status.is_noerror());
let [answer] = output.answer.try_into().unwrap();
let a = answer.try_into_a().unwrap();
assert_eq!(needle_fqdn, a.fqdn);
assert_eq!(expected_ipv4_addr, a.ipv4_addr);
Ok(())
}
#[ignore]
#[test]
fn nxdomain() -> Result<()> {
let needle_fqdn = FQDN("unicorn.nameservers.com.")?;
let network = Network::new()?;
let leaf_ns = NameServer::new(&dns_test::PEER, FQDN::NAMESERVERS, &network)?;
let Graph {
nameservers: _nameservers,
root,
..
} = Graph::build(leaf_ns, Sign::No)?;
let resolver = Resolver::new(&network, root).start(&dns_test::SUBJECT)?;
let resolver_ip_addr = resolver.ipv4_addr();
let client = Client::new(&network)?;
let settings = *DigSettings::default().recurse();
let output = client.dig(settings, resolver_ip_addr, RecordType::A, &needle_fqdn)?;
assert!(dbg!(output).status.is_nxdomain());
Ok(())
}

View File

@ -0,0 +1,5 @@
//! DNSSEC functionality
mod fixtures;
mod rfc4035;
mod scenarios;

View File

@ -0,0 +1,75 @@
use std::net::Ipv4Addr;
use base64::prelude::*;
use dns_test::{
name_server::{Graph, NameServer, Running, Sign},
record::Record,
Network, Resolver, Result, TrustAnchor, FQDN,
};
pub fn bad_signature_in_leaf_nameserver(
leaf_fqdn: &FQDN,
leaf_ipv4_addr: Ipv4Addr,
) -> Result<(Resolver, Graph)> {
assert_eq!(Some(FQDN::NAMESERVERS), leaf_fqdn.parent());
let network = Network::new()?;
let mut leaf_ns = NameServer::new(&dns_test::PEER, FQDN::NAMESERVERS, &network)?;
leaf_ns.add(Record::a(leaf_fqdn.clone(), leaf_ipv4_addr));
let graph = Graph::build(
leaf_ns,
Sign::AndAmend(&|zone, records| {
if zone == &FQDN::NAMESERVERS {
let mut modified = 0;
for record in records {
if let Record::RRSIG(rrsig) = record {
if rrsig.fqdn == *leaf_fqdn {
let mut signature = BASE64_STANDARD.decode(&rrsig.signature).unwrap();
let last = signature.last_mut().expect("empty signature");
*last = !*last;
rrsig.signature = BASE64_STANDARD.encode(&signature);
modified += 1;
}
}
}
assert_eq!(modified, 1, "sanity check");
}
}),
)?;
let trust_anchor = graph.trust_anchor.as_ref().unwrap();
let resolver = Resolver::new(&network, graph.root.clone())
.trust_anchor(trust_anchor)
.start(&dns_test::SUBJECT)?;
Ok((resolver, graph))
}
pub fn minimally_secure(
leaf_fqdn: FQDN,
leaf_ipv4_addr: Ipv4Addr,
) -> Result<(Resolver, Vec<NameServer<Running>>, TrustAnchor)> {
assert_eq!(Some(FQDN::NAMESERVERS), leaf_fqdn.parent());
let network = Network::new()?;
let mut leaf_ns = NameServer::new(&dns_test::PEER, FQDN::NAMESERVERS, &network)?;
leaf_ns.add(Record::a(leaf_fqdn.clone(), leaf_ipv4_addr));
let Graph {
nameservers,
root,
trust_anchor,
} = Graph::build(leaf_ns, Sign::Yes)?;
let trust_anchor = trust_anchor.unwrap();
let resolver = Resolver::new(&network, root)
.trust_anchor(&trust_anchor)
.start(&dns_test::SUBJECT)?;
Ok((resolver, nameservers, trust_anchor))
}

View File

@ -0,0 +1,2 @@
mod section_3;
mod section_4;

View File

@ -0,0 +1,2 @@
mod section_3_1;
mod section_3_2;

View File

@ -0,0 +1,76 @@
use dns_test::{
client::{Client, DigSettings},
name_server::{Graph, NameServer, Sign},
record::RecordType,
tshark::{Capture, Direction},
Network, Resolver, Result, FQDN,
};
#[test]
fn on_clients_ds_query_it_queries_the_parent_zone() -> Result<()> {
let network = Network::new()?;
let leaf_ns = NameServer::new(&dns_test::PEER, FQDN::NAMESERVERS, &network)?;
let Graph {
nameservers,
root,
trust_anchor,
} = Graph::build(leaf_ns, Sign::Yes)?;
let mut com_ns_addr = None;
for nameserver in &nameservers {
if nameserver.zone() == &FQDN::COM {
com_ns_addr = Some(nameserver.ipv4_addr());
}
}
let com_ns_addr = com_ns_addr.expect("com. NS not found");
let trust_anchor = &trust_anchor.unwrap();
let resolver = Resolver::new(&network, root)
.trust_anchor(trust_anchor)
.start(&dns_test::SUBJECT)?;
let mut tshark = resolver.eavesdrop()?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(&network)?;
let settings = *DigSettings::default().recurse();
let output = client.dig(settings, resolver_addr, RecordType::DS, &FQDN::NAMESERVERS)?;
tshark.wait_for_capture()?;
let captures = tshark.terminate()?;
// check that we were able to retrieve the DS record
assert!(output.status.is_noerror());
let [record] = output.answer.try_into().unwrap();
let ds = record.try_into_ds().unwrap();
assert_eq!(ds.zone, FQDN::NAMESERVERS);
// check that DS query was forwarded to the `com.` (parent zone) nameserver
let client_addr = client.ipv4_addr();
let mut outgoing_ds_query_count = 0;
for Capture { message, direction } in captures {
if let Direction::Outgoing { destination } = direction {
if destination != client_addr {
let queries = message.as_value()["Queries"]
.as_object()
.expect("expected Object");
for query in queries.keys() {
if query.contains("type DS") {
assert!(query.contains("nameservers.com"));
assert_eq!(com_ns_addr, destination);
outgoing_ds_query_count += 1;
}
}
}
}
}
assert_eq!(1, outgoing_ds_query_count);
Ok(())
}

View File

@ -0,0 +1,122 @@
mod section_3_2_2;
use dns_test::{
client::{Client, DigSettings},
name_server::NameServer,
record::{Record, RecordType},
tshark::{Capture, Direction},
Network, Resolver, Result, FQDN,
};
#[test]
fn do_bit_not_set_in_request() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&dns_test::PEER, FQDN::ROOT, network)?
.sign()?
.start()?;
let resolver = Resolver::new(network, ns.root_hint()).start(&dns_test::SUBJECT)?;
let mut tshark = resolver.eavesdrop()?;
let client = Client::new(network)?;
let settings = *DigSettings::default().recurse();
let ans = client.dig(settings, resolver.ipv4_addr(), RecordType::SOA, &FQDN::ROOT)?;
// "the name server side MUST strip any authenticating DNSSEC RRs from the response"
let [answer] = ans.answer.try_into().unwrap();
assert!(matches!(answer, Record::SOA(_)));
tshark.wait_for_capture()?;
let captures = tshark.terminate()?;
let ns_addr = ns.ipv4_addr();
for Capture { message, direction } in captures {
if let Direction::Outgoing { destination } = direction {
if destination == client.ipv4_addr() {
continue;
}
// sanity check
assert_eq!(ns_addr, destination);
// "The resolver side of a security-aware recursive name server MUST set the DO bit
// when sending requests"
if destination == ns_addr {
assert_eq!(Some(true), message.is_do_bit_set());
}
}
}
Ok(())
}
#[test]
fn if_do_bit_not_set_in_request_then_requested_dnssec_record_is_not_stripped() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&dns_test::PEER, FQDN::ROOT, network)?
.sign()?
.start()?;
let resolver = Resolver::new(network, ns.root_hint()).start(&dns_test::SUBJECT)?;
let client = Client::new(network)?;
let settings = *DigSettings::default().recurse();
let ans = client.dig(
settings,
resolver.ipv4_addr(),
RecordType::DNSKEY,
&FQDN::ROOT,
)?;
// "MUST NOT strip any DNSSEC RR types that the initiating query explicitly requested"
for record in &ans.answer {
assert!(matches!(record, Record::DNSKEY(_)))
}
Ok(())
}
#[test]
fn do_bit_set_in_request() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&dns_test::PEER, FQDN::ROOT, network)?
.sign()?
.start()?;
let resolver = Resolver::new(network, ns.root_hint()).start(&dns_test::SUBJECT)?;
let mut tshark = resolver.eavesdrop()?;
let client = Client::new(network)?;
let settings = *DigSettings::default().dnssec().recurse();
let ans = client.dig(settings, resolver.ipv4_addr(), RecordType::SOA, &FQDN::ROOT)?;
let [answer, rrsig] = ans.answer.try_into().unwrap();
assert!(matches!(answer, Record::SOA(_)));
assert!(matches!(rrsig, Record::RRSIG(_)));
tshark.wait_for_capture()?;
let captures = tshark.terminate()?;
let ns_addr = ns.ipv4_addr();
for Capture { message, direction } in captures {
if let Direction::Outgoing { destination } = direction {
if destination == client.ipv4_addr() {
continue;
}
// sanity check
assert_eq!(ns_addr, destination);
// "The resolver side of a security-aware recursive name server MUST set the DO bit
// when sending requests"
if destination == ns_addr {
assert_eq!(Some(true), message.is_do_bit_set());
}
}
}
Ok(())
}

View File

@ -0,0 +1,55 @@
use std::net::Ipv4Addr;
use dns_test::{
client::{Client, DigSettings},
name_server::NameServer,
record::RecordType,
Network, Resolver, Result, FQDN,
};
use crate::resolver::dnssec::fixtures;
#[test]
fn copies_cd_bit_from_query_to_response() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&dns_test::PEER, FQDN::ROOT, network)?.start()?;
let resolver = Resolver::new(network, ns.root_hint()).start(&dns_test::SUBJECT)?;
let client = Client::new(network)?;
let settings = *DigSettings::default().checking_disabled().recurse();
let ans = client.dig(settings, resolver.ipv4_addr(), RecordType::SOA, &FQDN::ROOT)?;
assert!(ans.flags.checking_disabled);
Ok(())
}
#[test]
fn if_cd_bit_is_set_then_respond_with_data_that_fails_authentication() -> Result<()> {
let needle_fqdn = FQDN("example.nameservers.com.")?;
let needle_ipv4_addr = Ipv4Addr::new(1, 2, 3, 4);
let (resolver, _graph) =
fixtures::bad_signature_in_leaf_nameserver(&needle_fqdn, needle_ipv4_addr)?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(resolver.network())?;
let settings = *DigSettings::default()
.recurse()
.authentic_data()
.checking_disabled();
let output = client.dig(settings, resolver_addr, RecordType::A, &needle_fqdn)?;
assert!(output.status.is_noerror());
assert!(!output.flags.authenticated_data);
let [record] = output.answer.try_into().unwrap();
let record = record.try_into_a().unwrap();
assert_eq!(needle_fqdn, record.fqdn);
assert_eq!(needle_ipv4_addr, record.ipv4_addr);
Ok(())
}

View File

@ -0,0 +1,2 @@
mod section_4_1;
mod section_4_6;

View File

@ -0,0 +1,46 @@
use dns_test::client::{Client, DigSettings};
use dns_test::name_server::NameServer;
use dns_test::record::RecordType;
use dns_test::tshark::{Capture, Direction};
use dns_test::{Network, Resolver, Result, FQDN};
#[test]
fn edns_support() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&dns_test::PEER, FQDN::ROOT, network)?.start()?;
let resolver = Resolver::new(network, ns.root_hint()).start(&dns_test::SUBJECT)?;
let mut tshark = resolver.eavesdrop()?;
let client = Client::new(network)?;
let settings = *DigSettings::default().authentic_data().recurse();
let _ans = client.dig(settings, resolver.ipv4_addr(), RecordType::SOA, &FQDN::ROOT)?;
// implementation-specific behavior
// unbound replies with SERVFAIL
// BIND replies with NOERROR
// assert!(_ans.status.is_servfail());
tshark.wait_for_capture()?;
let captures = tshark.terminate()?;
let ns_addr = ns.ipv4_addr();
for Capture { message, direction } in captures {
if let Direction::Outgoing { destination } = direction {
if destination == client.ipv4_addr() {
continue;
}
// sanity check
assert_eq!(ns_addr, destination);
if destination == ns_addr {
assert_eq!(Some(true), message.is_do_bit_set());
assert!(message.udp_payload_size().unwrap() >= 1220);
}
}
}
Ok(())
}

View File

@ -0,0 +1,70 @@
use std::net::Ipv4Addr;
use dns_test::{
client::{Client, DigSettings},
record::RecordType,
tshark::{Capture, Direction},
Result, FQDN,
};
use crate::resolver::dnssec::fixtures;
#[test]
fn clears_ad_bit_in_outgoing_queries() -> Result<()> {
let leaf_ipv4_addr = Ipv4Addr::new(1, 2, 3, 4);
let leaf_fqdn = FQDN("example.nameservers.com.")?;
let (resolver, nameservers, _trust_anchor) =
fixtures::minimally_secure(leaf_fqdn.clone(), leaf_ipv4_addr)?;
let mut tshark = resolver.eavesdrop()?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(resolver.network())?;
let settings = *DigSettings::default().recurse().authentic_data();
let _output = client.dig(settings, resolver_addr, RecordType::A, &leaf_fqdn)?;
tshark.wait_for_capture()?;
let captures = tshark.terminate()?;
let client_addr = client.ipv4_addr();
let mut ns_checks_count = 0;
let mut client_checks_count = 0;
let ns_addrs = nameservers
.iter()
.map(|ns| ns.ipv4_addr())
.collect::<Vec<_>>();
for Capture { message, direction } in captures {
match direction {
Direction::Incoming { source } => {
if source == client_addr {
// sanity check
assert!(message.is_ad_flag_set());
client_checks_count += 1;
}
}
Direction::Outgoing { destination } => {
if destination == client_addr {
// skip response to client
continue;
}
// sanity check
assert!(ns_addrs.contains(&destination));
assert!(!message.is_ad_flag_set());
ns_checks_count += 1;
}
}
}
// sanity checks
assert_eq!(1, client_checks_count);
assert_ne!(0, dbg!(ns_checks_count));
Ok(())
}

View File

@ -0,0 +1,3 @@
mod bogus;
mod ede;
mod secure;

View File

@ -0,0 +1,29 @@
use std::net::Ipv4Addr;
use dns_test::client::{Client, DigSettings};
use dns_test::record::RecordType;
use dns_test::{Result, FQDN};
use crate::resolver::dnssec::fixtures;
// TODO find out which RFC section states this
#[ignore]
#[test]
fn if_cd_bit_is_clear_and_data_is_not_authentic_then_respond_with_servfail() -> Result<()> {
let needle_fqdn = FQDN("example.nameservers.com.")?;
let needle_ipv4_addr = Ipv4Addr::new(1, 2, 3, 4);
let (resolver, _graph) =
fixtures::bad_signature_in_leaf_nameserver(&needle_fqdn, needle_ipv4_addr)?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(resolver.network())?;
let settings = *DigSettings::default().recurse().authentic_data();
let output = client.dig(settings, resolver_addr, RecordType::A, &needle_fqdn)?;
assert!(output.status.is_servfail());
Ok(())
}

View File

@ -0,0 +1,171 @@
use std::net::Ipv4Addr;
use dns_test::client::{Client, DigSettings, ExtendedDnsError};
use dns_test::name_server::{Graph, NameServer, Sign};
use dns_test::record::{Record, RecordType};
use dns_test::{Network, Resolver, Result, FQDN};
#[ignore]
#[test]
fn dnskey_missing() -> Result<()> {
fixture(
ExtendedDnsError::DnskeyMissing,
|_needle_fqdn, zone, records| {
if zone == &FQDN::NAMESERVERS {
// remove the DNSKEY record that contains the ZSK
let mut remove_count = 0;
*records = records
.drain(..)
.filter(|record| {
let remove = if let Record::DNSKEY(dnskey) = record {
dnskey.is_zone_signing_key()
} else {
false
};
if remove {
remove_count += 1;
}
!remove
})
.collect();
assert_eq!(1, remove_count, "sanity check");
}
},
)
}
#[ignore]
#[test]
fn rrsigs_missing() -> Result<()> {
fixture(
ExtendedDnsError::RrsigsMissing,
|needle_fqdn, zone, records| {
if zone == &FQDN::NAMESERVERS {
// remove the RRSIG records that covers the needle record
let mut remove_count = 0;
*records = records
.drain(..)
.filter(|record| {
let remove = if let Record::RRSIG(rrsig) = record {
rrsig.type_covered == RecordType::A && rrsig.fqdn == *needle_fqdn
} else {
false
};
if remove {
remove_count += 1;
}
!remove
})
.collect();
assert_eq!(1, remove_count, "sanity check");
}
},
)
}
#[ignore]
#[test]
fn unsupported_dnskey_algorithm() -> Result<()> {
fixture(
ExtendedDnsError::UnsupportedDnskeyAlgorithm,
|needle_fqdn, zone, records| {
if zone == &FQDN::NAMESERVERS {
// lie about the algorithm that was used to sign the needle record
let mut modified_count = 0;
for record in records {
if let Record::RRSIG(rrsig) = record {
if rrsig.type_covered == RecordType::A && rrsig.fqdn == *needle_fqdn {
assert_ne!(1, rrsig.algorithm, "modify the value below");
rrsig.algorithm = 1;
modified_count += 1;
}
}
}
assert_eq!(1, modified_count, "sanity check");
}
},
)
}
#[ignore]
#[test]
fn dnssec_bogus() -> Result<()> {
fixture(
ExtendedDnsError::DnssecBogus,
|needle_fqdn, zone, records| {
if zone == &FQDN::NAMESERVERS {
// corrupt the RRSIG record that covers the needle record
let mut modified_count = 0;
for record in records {
if let Record::RRSIG(rrsig) = record {
if rrsig.type_covered == RecordType::A && rrsig.fqdn == *needle_fqdn {
rrsig.signature_expiration = rrsig.signature_inception - 1;
modified_count += 1;
}
}
}
assert_eq!(1, modified_count, "sanity check");
}
},
)
}
// Sets up a minimal, DNSSEC-enabled DNS graph where the leaf zone contains a "needle" A record
// that we'll search for
//
// `amend` can be used to modify zone files *after* they have been signed. it's used to introduce
// errors in the signed zone files
//
// the query for the needle record is expected to fail with the `expected` Extended DNS Error
fn fixture(
expected: ExtendedDnsError,
amend: fn(needle_fqdn: &FQDN, zone: &FQDN, records: &mut Vec<Record>),
) -> Result<()> {
let subject = &dns_test::SUBJECT;
let supports_ede = subject.supports_ede();
let expected_ipv4_addr = Ipv4Addr::new(1, 2, 3, 4);
let needle_fqdn = FQDN("example.nameservers.com.")?;
let network = Network::new()?;
let mut leaf_ns = NameServer::new(&dns_test::PEER, FQDN::NAMESERVERS, &network)?;
leaf_ns.add(Record::a(needle_fqdn.clone(), expected_ipv4_addr));
let Graph {
nameservers: _nameservers,
root,
trust_anchor,
} = Graph::build(
leaf_ns,
Sign::AndAmend(&|zone, records| {
amend(&needle_fqdn, zone, records);
}),
)?;
let mut resolver = Resolver::new(&network, root);
if supports_ede {
resolver.extended_dns_errors();
}
let trust_anchor = &trust_anchor.unwrap();
let resolver = resolver.trust_anchor(trust_anchor).start(subject)?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(&network)?;
let settings = *DigSettings::default().recurse().authentic_data();
let output = client.dig(settings, resolver_addr, RecordType::A, &needle_fqdn)?;
assert!(output.status.is_servfail());
if supports_ede {
assert_eq!(Some(expected), output.ede);
}
Ok(())
}

View File

@ -0,0 +1,79 @@
use std::net::Ipv4Addr;
use dns_test::client::{Client, DigSettings};
use dns_test::name_server::NameServer;
use dns_test::record::RecordType;
use dns_test::{Network, Resolver, Result, TrustAnchor, FQDN};
use crate::resolver::dnssec::fixtures;
// no DS records are involved; this is a single-link chain of trust
#[ignore]
#[test]
fn can_validate_without_delegation() -> Result<()> {
let network = Network::new()?;
let mut ns = NameServer::new(&dns_test::PEER, FQDN::ROOT, &network)?;
ns.add(ns.a());
let ns = ns.sign()?;
let root_ksk = ns.key_signing_key().clone();
let root_zsk = ns.zone_signing_key().clone();
eprintln!("root.zone.signed:\n{}", ns.signed_zone_file());
let ns = ns.start()?;
eprintln!("root.zone:\n{}", ns.zone_file());
let trust_anchor = &TrustAnchor::from_iter([root_ksk.clone(), root_zsk.clone()]);
let resolver = Resolver::new(&network, ns.root_hint())
.trust_anchor(trust_anchor)
.start(&dns_test::SUBJECT)?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(&network)?;
let settings = *DigSettings::default().recurse().authentic_data();
let output = client.dig(settings, resolver_addr, RecordType::SOA, &FQDN::ROOT)?;
assert!(output.status.is_noerror());
assert!(output.flags.authenticated_data);
let output = client.delv(resolver_addr, RecordType::SOA, &FQDN::ROOT, trust_anchor)?;
assert!(output.starts_with("; fully validated"));
Ok(())
}
#[ignore]
#[test]
fn can_validate_with_delegation() -> Result<()> {
let expected_ipv4_addr = Ipv4Addr::new(1, 2, 3, 4);
let needle_fqdn = FQDN("example.nameservers.com.")?;
let (resolver, _nameservers, trust_anchor) =
fixtures::minimally_secure(needle_fqdn.clone(), expected_ipv4_addr)?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(resolver.network())?;
let settings = *DigSettings::default().recurse().authentic_data();
let output = client.dig(settings, resolver_addr, RecordType::A, &needle_fqdn)?;
assert!(output.status.is_noerror());
assert!(output.flags.authenticated_data);
let [a] = output.answer.try_into().unwrap();
let a = a.try_into_a().unwrap();
assert_eq!(needle_fqdn, a.fqdn);
assert_eq!(expected_ipv4_addr, a.ipv4_addr);
let output = client.delv(resolver_addr, RecordType::A, &needle_fqdn, &trust_anchor)?;
assert!(output.starts_with("; fully validated"));
Ok(())
}
// TODO nxdomain with NSEC records
// TODO nxdomain with NSEC3 records

View File

@ -0,0 +1,22 @@
[package]
edition = "2021"
license = "MIT OR Apache-2.0"
name = "dns-test"
publish = false
version = "0.1.0"
[dependencies]
lazy_static = "1.4.0"
minijinja = "1.0.12"
serde = { version = "1.0.196", features = ["derive"] }
serde_json = "1.0.113"
serde_with = "3.6.1"
tempfile = "3.9.0"
url = "2.5.0"
[lib]
doctest = false
[dev-dependencies]
ctrlc = "3.4.2"
pretty_assertions = "1.4.0"

View File

@ -0,0 +1,132 @@
use std::env;
use std::net::Ipv4Addr;
use std::sync::mpsc;
use dns_test::client::Client;
use dns_test::name_server::{Graph, NameServer, Sign};
use dns_test::record::RecordType;
use dns_test::{Network, Resolver, Result, FQDN};
fn main() -> Result<()> {
let args = Args::from_env()?;
let network = Network::new()?;
let peer = &dns_test::PEER;
println!("building docker image...");
let leaf_ns = NameServer::new(peer, FQDN("mydomain.com.")?, &network)?;
println!("DONE");
println!("setting up name servers...");
let sign = if args.dnssec { Sign::Yes } else { Sign::No };
let Graph {
root,
trust_anchor,
nameservers,
} = Graph::build(leaf_ns, sign)?;
println!("DONE");
let client = Client::new(&network)?;
if args.dnssec {
// this will send queries to the loopback address and fail because there's no resolver
// but as a side-effect it will generate the `/etc/bind.keys` file we want
// ignore the expected error
let _ = client.delv(
Ipv4Addr::new(127, 0, 0, 1),
RecordType::SOA,
&FQDN::ROOT,
trust_anchor.as_ref().unwrap(),
)?;
}
println!("building docker image...");
let mut builder = Resolver::new(&network, root);
if let Some(trust_anchor) = trust_anchor {
builder.trust_anchor(&trust_anchor);
}
let resolver = builder.start(&dns_test::SUBJECT)?;
println!("DONE\n\n");
let (tx, rx) = mpsc::channel();
ctrlc::set_handler(move || tx.send(()).expect("could not forward signal"))?;
for ns in &nameservers {
println!("{} name server's IP address: {}", ns.zone(), ns.ipv4_addr());
println!(
"attach to this container with: `docker exec -it {} bash`\n",
ns.container_id()
);
}
let resolver_addr = resolver.ipv4_addr();
println!("resolver's IP address: {resolver_addr}",);
println!(
"attach to this container with: `docker exec -it {} bash`\n",
resolver.container_id()
);
println!("client's IP address: {}", client.ipv4_addr());
println!(
"attach to this container with: `docker exec -it {} bash`\n\n",
client.container_id()
);
println!("example queries (run these in the client container):\n");
let adflag = if args.dnssec { "+adflag" } else { "+noadflag" };
println!("`dig @{resolver_addr} {adflag} SOA .`\n");
if args.dnssec {
println!(
"`delv -a /etc/bind.keys @{resolver_addr} SOA .` (you MUST use the `-a` flag with delv)\n\n"
);
}
println!(
"to print the DNS traffic flowing through the resolver run this command in
the resolver container before performing queries:\n"
);
println!("`tshark -f 'udp port 53' -O dns`\n\n");
println!("press Ctrl+C to take down the network");
rx.recv()?;
println!("\ntaking down network...");
Ok(())
}
struct Args {
dnssec: bool,
}
impl Args {
fn from_env() -> Result<Self> {
let args: Vec<_> = env::args().skip(1).collect();
let num_args = args.len();
let dnssec = if num_args == 0 {
false
} else if num_args == 1 {
if args[0] == "--dnssec" {
true
} else {
return cli_error();
}
} else {
return cli_error();
};
Ok(Self { dnssec })
}
}
fn cli_error<T>() -> Result<T> {
eprintln!(
"usage: explore [--dnssec]
Options:
--dnssec sign zone files to enable DNSSEC"
);
Err("CLI error".into())
}

View File

@ -0,0 +1,470 @@
use core::str::FromStr;
use std::net::Ipv4Addr;
use crate::container::{Container, Image, Network};
use crate::record::{Record, RecordType};
use crate::trust_anchor::TrustAnchor;
use crate::{Error, Result, FQDN};
pub struct Client {
inner: Container,
}
impl Client {
pub fn new(network: &Network) -> Result<Self> {
Ok(Self {
inner: Container::run(&Image::Client, network)?,
})
}
pub fn container_id(&self) -> &str {
self.inner.id()
}
pub fn ipv4_addr(&self) -> Ipv4Addr {
self.inner.ipv4_addr()
}
pub fn delv(
&self,
server: Ipv4Addr,
record_type: RecordType,
fqdn: &FQDN,
trust_anchor: &TrustAnchor,
) -> Result<String> {
const TRUST_ANCHOR_PATH: &str = "/etc/bind.keys";
assert!(
!trust_anchor.is_empty(),
"`delv` cannot be used with an empty trust anchor"
);
self.inner.cp(TRUST_ANCHOR_PATH, &trust_anchor.delv())?;
self.inner.stdout(&[
"delv",
&format!("@{server}"),
"-a",
TRUST_ANCHOR_PATH,
fqdn.as_str(),
record_type.as_str(),
])
}
pub fn dig(
&self,
settings: DigSettings,
server: Ipv4Addr,
record_type: RecordType,
fqdn: &FQDN,
) -> Result<DigOutput> {
let output = self.inner.stdout(&[
"dig",
settings.rdflag(),
settings.do_bit(),
settings.adflag(),
settings.cdflag(),
&format!("@{server}"),
record_type.as_str(),
fqdn.as_str(),
])?;
output.parse()
}
}
#[derive(Clone, Copy, Default)]
pub struct DigSettings {
adflag: bool,
cdflag: bool,
dnssec: bool,
recurse: bool,
}
impl DigSettings {
/// Sets the AD bit in the query
pub fn authentic_data(&mut self) -> &mut Self {
self.adflag = true;
self
}
fn adflag(&self) -> &'static str {
if self.adflag {
"+adflag"
} else {
"+noadflag"
}
}
/// Sets the CD bit in the query
pub fn checking_disabled(&mut self) -> &mut Self {
self.cdflag = true;
self
}
fn cdflag(&self) -> &'static str {
if self.cdflag {
"+cdflag"
} else {
"+nocdflag"
}
}
/// Sets the DO bit in the query
pub fn dnssec(&mut self) -> &mut Self {
self.dnssec = true;
self
}
fn do_bit(&self) -> &'static str {
if self.dnssec {
"+dnssec"
} else {
"+nodnssec"
}
}
/// Sets the RD bit in the query
pub fn recurse(&mut self) -> &mut Self {
self.recurse = true;
self
}
fn rdflag(&self) -> &'static str {
if self.recurse {
"+recurse"
} else {
"+norecurse"
}
}
}
#[derive(Debug)]
pub struct DigOutput {
pub ede: Option<ExtendedDnsError>,
pub flags: DigFlags,
pub status: DigStatus,
pub answer: Vec<Record>,
pub authority: Vec<Record>,
// TODO(if needed) other sections
}
impl FromStr for DigOutput {
type Err = Error;
fn from_str(input: &str) -> Result<Self> {
const FLAGS_PREFIX: &str = ";; flags: ";
const STATUS_PREFIX: &str = ";; ->>HEADER<<- opcode: QUERY, status: ";
const EDE_PREFIX: &str = "; EDE: ";
const ANSWER_HEADER: &str = ";; ANSWER SECTION:";
const AUTHORITY_HEADER: &str = ";; AUTHORITY SECTION:";
fn not_found(prefix: &str) -> String {
format!("`{prefix}` line was not found")
}
fn more_than_once(prefix: &str) -> String {
format!("`{prefix}` line was found more than once")
}
fn missing(prefix: &str, delimiter: &str) -> String {
format!("`{prefix}` line is missing a {delimiter}")
}
let mut flags = None;
let mut status = None;
let mut answer = None;
let mut authority = None;
let mut ede = None;
let mut lines = input.lines();
while let Some(line) = lines.next() {
if let Some(unprefixed) = line.strip_prefix(FLAGS_PREFIX) {
let (flags_text, _rest) = unprefixed
.split_once(';')
.ok_or_else(|| missing(FLAGS_PREFIX, "semicolon (;)"))?;
if flags.is_some() {
return Err(more_than_once(FLAGS_PREFIX).into());
}
flags = Some(flags_text.parse()?);
} else if let Some(unprefixed) = line.strip_prefix(STATUS_PREFIX) {
let (status_text, _rest) = unprefixed
.split_once(',')
.ok_or_else(|| missing(STATUS_PREFIX, "comma (,)"))?;
if status.is_some() {
return Err(more_than_once(STATUS_PREFIX).into());
}
status = Some(status_text.parse()?);
} else if let Some(unprefixed) = line.strip_prefix(EDE_PREFIX) {
let code = unprefixed
.split_once(' ')
.map(|(code, _rest)| code)
.unwrap_or(unprefixed);
if ede.is_some() {
return Err(more_than_once(EDE_PREFIX).into());
}
ede = Some(code.parse()?);
} else if line.starts_with(ANSWER_HEADER) {
if answer.is_some() {
return Err(more_than_once(ANSWER_HEADER).into());
}
let mut records = vec![];
for line in lines.by_ref() {
if line.is_empty() {
break;
}
records.push(line.parse()?);
}
answer = Some(records);
} else if line.starts_with(AUTHORITY_HEADER) {
if authority.is_some() {
return Err(more_than_once(AUTHORITY_HEADER).into());
}
let mut records = vec![];
for line in lines.by_ref() {
if line.is_empty() {
break;
}
records.push(line.parse()?);
}
authority = Some(records);
}
}
Ok(Self {
answer: answer.unwrap_or_default(),
authority: authority.unwrap_or_default(),
ede,
flags: flags.ok_or_else(|| not_found(FLAGS_PREFIX))?,
status: status.ok_or_else(|| not_found(STATUS_PREFIX))?,
})
}
}
#[derive(Debug, PartialEq)]
pub enum ExtendedDnsError {
DnskeyMissing,
DnssecBogus,
RrsigsMissing,
UnsupportedDnskeyAlgorithm,
}
impl FromStr for ExtendedDnsError {
type Err = Error;
fn from_str(input: &str) -> std::prelude::v1::Result<Self, Self::Err> {
let code: u16 = input.parse()?;
let code = match code {
1 => Self::UnsupportedDnskeyAlgorithm,
6 => Self::DnssecBogus,
9 => Self::DnskeyMissing,
10 => Self::RrsigsMissing,
_ => todo!("EDE {code} has not yet been implemented"),
};
Ok(code)
}
}
#[derive(Debug, Default, PartialEq)]
pub struct DigFlags {
pub authenticated_data: bool,
pub authoritative_answer: bool,
pub checking_disabled: bool,
pub qr: bool,
pub recursion_available: bool,
pub recursion_desired: bool,
}
impl FromStr for DigFlags {
type Err = Error;
fn from_str(input: &str) -> std::prelude::v1::Result<Self, Self::Err> {
let mut qr = false;
let mut recursion_desired = false;
let mut recursion_available = false;
let mut authoritative_answer = false;
let mut authenticated_data = false;
let mut checking_disabled = false;
for flag in input.split_whitespace() {
match flag {
"qr" => qr = true,
"rd" => recursion_desired = true,
"ra" => recursion_available = true,
"aa" => authoritative_answer = true,
"ad" => authenticated_data = true,
"cd" => checking_disabled = true,
_ => return Err(format!("unknown flag: {flag}").into()),
}
}
Ok(Self {
authenticated_data,
authoritative_answer,
checking_disabled,
qr,
recursion_available,
recursion_desired,
})
}
}
#[allow(clippy::upper_case_acronyms)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DigStatus {
NOERROR,
NXDOMAIN,
REFUSED,
SERVFAIL,
}
impl DigStatus {
#[must_use]
pub fn is_noerror(&self) -> bool {
matches!(self, Self::NOERROR)
}
#[must_use]
pub fn is_nxdomain(&self) -> bool {
matches!(self, Self::NXDOMAIN)
}
#[must_use]
pub fn is_servfail(&self) -> bool {
matches!(self, Self::SERVFAIL)
}
}
impl FromStr for DigStatus {
type Err = Error;
fn from_str(input: &str) -> Result<Self> {
let status = match input {
"NXDOMAIN" => Self::NXDOMAIN,
"NOERROR" => Self::NOERROR,
"REFUSED" => Self::REFUSED,
"SERVFAIL" => Self::SERVFAIL,
_ => return Err(format!("unknown status: {input}").into()),
};
Ok(status)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dig_nxdomain() -> Result<()> {
// $ dig nonexistent.domain.
let input = "
; <<>> DiG 9.18.18-0ubuntu0.22.04.1-Ubuntu <<>> nonexistent.domain.
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 45583
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;nonexistent.domain. IN A
;; Query time: 3 msec
;; SERVER: 192.168.1.1#53(192.168.1.1) (UDP)
;; WHEN: Tue Feb 06 15:00:12 UTC 2024
;; MSG SIZE rcvd: 47
";
let output: DigOutput = input.parse()?;
assert_eq!(DigStatus::NXDOMAIN, output.status);
assert_eq!(
DigFlags {
qr: true,
recursion_desired: true,
recursion_available: true,
..DigFlags::default()
},
output.flags
);
assert!(output.answer.is_empty());
Ok(())
}
#[test]
fn authority_section() -> Result<()> {
// $ dig A .
let input = "
; <<>> DiG 9.18.24 <<>> A .
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39670
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;. IN A
;; AUTHORITY SECTION:
. 2910 IN SOA a.root-servers.net. nstld.verisign-grs.com. 2024022600 1800 900 604800 86400
;; Query time: 43 msec
;; SERVER: 192.168.1.1#53(192.168.1.1) (UDP)
;; WHEN: Mon Feb 26 11:55:50 CET 2024
;; MSG SIZE rcvd: 103
";
let output: DigOutput = input.parse()?;
let [record] = output.authority.try_into().expect("exactly one record");
matches!(record, Record::SOA(..));
Ok(())
}
#[test]
fn ede() -> Result<()> {
let input = "; <<>> DiG 9.18.24-1-Debian <<>> +recurse +nodnssec +adflag +nocdflag @192.168.176.5 A example.nameservers.com.
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 49801
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; EDE: 9 (DNSKEY Missing)
;; QUESTION SECTION:
;example.nameservers.com. IN A
;; Query time: 26 msec
;; SERVER: 192.168.176.5#53(192.168.176.5) (UDP)
;; WHEN: Tue Mar 05 17:45:29 UTC 2024
;; MSG SIZE rcvd: 58
";
let output: DigOutput = input.parse()?;
assert_eq!(Some(ExtendedDnsError::DnskeyMissing), output.ede);
Ok(())
}
}

View File

@ -0,0 +1,443 @@
mod network;
use core::{fmt, str};
use std::net::Ipv4Addr;
use std::process::{self, ChildStdout, ExitStatus};
use std::process::{Command, Stdio};
use std::sync::atomic::AtomicUsize;
use std::sync::{atomic, Arc, Once};
use std::{env, fs};
use tempfile::{NamedTempFile, TempDir};
pub use crate::container::network::Network;
use crate::{Error, Implementation, Repository, Result};
#[derive(Clone)]
pub struct Container {
inner: Arc<Inner>,
}
const PACKAGE_NAME: &str = env!("CARGO_PKG_NAME");
#[derive(Clone)]
pub enum Image {
Bind,
Client,
Hickory(Repository<'static>),
Unbound,
}
impl Image {
fn dockerfile(&self) -> &'static str {
match self {
Self::Bind => include_str!("docker/bind.Dockerfile"),
Self::Client => include_str!("docker/client.Dockerfile"),
Self::Hickory { .. } => include_str!("docker/hickory.Dockerfile"),
Self::Unbound => include_str!("docker/unbound.Dockerfile"),
}
}
fn once(&self) -> &'static Once {
match self {
Self::Bind => {
static BIND_ONCE: Once = Once::new();
&BIND_ONCE
}
Self::Client => {
static CLIENT_ONCE: Once = Once::new();
&CLIENT_ONCE
}
Self::Hickory { .. } => {
static HICKORY_ONCE: Once = Once::new();
&HICKORY_ONCE
}
Self::Unbound => {
static UNBOUND_ONCE: Once = Once::new();
&UNBOUND_ONCE
}
}
}
}
impl From<Implementation> for Image {
fn from(implementation: Implementation) -> Self {
match implementation {
Implementation::Bind => Self::Bind,
Implementation::Unbound => Self::Unbound,
Implementation::Hickory(repo) => Self::Hickory(repo),
}
}
}
impl fmt::Display for Image {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Client => "client",
Self::Bind => "bind",
Self::Hickory { .. } => "hickory",
Self::Unbound => "unbound",
};
f.write_str(s)
}
}
impl Container {
/// Starts the container in a "parked" state
pub fn run(image: &Image, network: &Network) -> Result<Self> {
// TODO make this configurable and support hickory & bind
let dockerfile = image.dockerfile();
let docker_build_dir = TempDir::new()?;
let docker_build_dir = docker_build_dir.path();
fs::write(docker_build_dir.join("Dockerfile"), dockerfile)?;
let image_tag = format!("{PACKAGE_NAME}-{image}");
let mut command = Command::new("docker");
command
.args(["build", "-t"])
.arg(&image_tag)
.arg(docker_build_dir);
let repo = if let Image::Hickory(repo) = image {
Some(repo)
} else {
None
};
image.once().call_once(|| {
if let Some(repo) = repo {
let mut cp_r = Command::new("git");
cp_r.args([
"clone",
"--depth",
"1",
repo.as_str(),
&docker_build_dir.join("src").display().to_string(),
]);
exec_or_panic(&mut cp_r, false);
}
fs::write(docker_build_dir.join(".dockerignore"), "src/.git")
.expect("could not create .dockerignore file");
exec_or_panic(&mut command, verbose_docker_build());
});
let mut command = Command::new("docker");
let pid = process::id();
let count = container_count();
let name = format!("{PACKAGE_NAME}-{image}-{pid}-{count}");
command
.args([
"run",
"--rm",
"--detach",
"--cap-add=NET_RAW",
"--cap-add=NET_ADMIN",
"--network",
network.name(),
"--name",
&name,
"-it",
])
.arg(image_tag)
.args(["sleep", "infinity"]);
let output: Output = checked_output(&mut command)?.try_into()?;
let id = output.stdout;
let ipv4_addr = get_ipv4_addr(&id)?;
let inner = Inner {
id,
name,
ipv4_addr,
network: network.clone(),
};
Ok(Self {
inner: Arc::new(inner),
})
}
pub fn cp(&self, path_in_container: &str, file_contents: &str) -> Result<()> {
const CHMOD_RW_EVERYONE: &str = "666";
let mut temp_file = NamedTempFile::new()?;
fs::write(&mut temp_file, file_contents)?;
let src_path = temp_file.path().display().to_string();
let dest_path = format!("{}:{path_in_container}", self.inner.id);
let mut command = Command::new("docker");
command.args(["cp", &src_path, &dest_path]);
checked_output(&mut command)?;
self.status_ok(&["chmod", CHMOD_RW_EVERYONE, path_in_container])?;
Ok(())
}
/// Similar to `std::process::Command::output` but runs `command_and_args` in the container
pub fn output(&self, command_and_args: &[&str]) -> Result<Output> {
let mut command = Command::new("docker");
command
.args(["exec", "-t", &self.inner.id])
.args(command_and_args);
command.output()?.try_into()
}
/// Similar to `Self::output` but checks `command_and_args` ran successfully and only
/// returns the stdout
pub fn stdout(&self, command_and_args: &[&str]) -> Result<String> {
let Output {
status,
stderr,
stdout,
} = self.output(command_and_args)?;
if status.success() {
Ok(stdout)
} else {
eprintln!("STDOUT:\n{stdout}\nSTDERR:\n{stderr}");
Err(format!("[{}] `{command_and_args:?}` failed", self.inner.name).into())
}
}
/// Similar to `std::process::Command::status` but runs `command_and_args` in the container
pub fn status(&self, command_and_args: &[&str]) -> Result<ExitStatus> {
let mut command = Command::new("docker");
command
.args(["exec", "-t", &self.inner.id])
.args(command_and_args);
Ok(command.status()?)
}
/// Like `Self::status` but checks that `command_and_args` executed successfully
pub fn status_ok(&self, command_and_args: &[&str]) -> Result<()> {
let status = self.status(command_and_args)?;
if status.success() {
Ok(())
} else {
Err(format!("[{}] `{command_and_args:?}` failed", self.inner.name).into())
}
}
pub fn spawn(&self, cmd: &[&str]) -> Result<Child> {
let mut command = Command::new("docker");
command.stdout(Stdio::piped()).stderr(Stdio::piped());
command.args(["exec", "-t", &self.inner.id]).args(cmd);
let inner = command.spawn()?;
Ok(Child {
inner: Some(inner),
_container: self.inner.clone(),
})
}
pub fn ipv4_addr(&self) -> Ipv4Addr {
self.inner.ipv4_addr
}
pub fn id(&self) -> &str {
&self.inner.id
}
pub(crate) fn network(&self) -> &Network {
&self.inner.network
}
}
fn verbose_docker_build() -> bool {
env::var("DNS_TEST_VERBOSE_DOCKER_BUILD").as_deref().is_ok()
}
fn exec_or_panic(command: &mut Command, verbose: bool) {
if verbose {
let status = command.status().unwrap();
assert!(status.success());
} else {
let output = command.output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"--- STDOUT ---\n{stdout}\n--- STDERR ---\n{stderr}"
);
}
}
fn container_count() -> usize {
static COUNT: AtomicUsize = AtomicUsize::new(0);
COUNT.fetch_add(1, atomic::Ordering::Relaxed)
}
struct Inner {
name: String,
id: String,
// TODO probably also want the IPv6 address
ipv4_addr: Ipv4Addr,
network: Network,
}
/// NOTE unlike `std::process::Child`, the drop implementation of this type will `kill` the
/// child process
// this wrapper over `std::process::Child` stores a reference to the container the child process
// runs inside of, to prevent the scenario of the container being destroyed _before_
// the child is killed
pub struct Child {
inner: Option<process::Child>,
_container: Arc<Inner>,
}
impl Child {
/// Returns a handle to the child's stdout
///
/// This method will succeed at most once
pub fn stdout(&mut self) -> Result<ChildStdout> {
Ok(self
.inner
.as_mut()
.and_then(|child| child.stdout.take())
.ok_or("could not retrieve child's stdout")?)
}
pub fn wait(mut self) -> Result<Output> {
let output = self.inner.take().expect("unreachable").wait_with_output()?;
output.try_into()
}
}
impl Drop for Child {
fn drop(&mut self) {
if let Some(mut inner) = self.inner.take() {
let _ = inner.kill();
}
}
}
#[derive(Debug)]
pub struct Output {
pub status: ExitStatus,
pub stderr: String,
pub stdout: String,
}
impl TryFrom<process::Output> for Output {
type Error = Error;
fn try_from(output: process::Output) -> Result<Self> {
let mut stderr = String::from_utf8(output.stderr)?;
while stderr.ends_with(|c| matches!(c, '\n' | '\r')) {
stderr.pop();
}
let mut stdout = String::from_utf8(output.stdout)?;
while stdout.ends_with(|c| matches!(c, '\n' | '\r')) {
stdout.pop();
}
Ok(Self {
status: output.status,
stderr,
stdout,
})
}
}
fn checked_output(command: &mut Command) -> Result<process::Output> {
let output = command.output()?;
if output.status.success() {
Ok(output)
} else {
Err(format!("`{command:?}` failed").into())
}
}
fn get_ipv4_addr(container_id: &str) -> Result<Ipv4Addr> {
let mut command = Command::new("docker");
command
.args([
"inspect",
"-f",
"{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
])
.arg(container_id);
let output = command.output()?;
if !output.status.success() {
return Err(format!("`{command:?}` failed").into());
}
let ipv4_addr = str::from_utf8(&output.stdout)?.trim().to_string();
Ok(ipv4_addr.parse()?)
}
// this ensures the container gets deleted and does not linger after the test runner process ends
impl Drop for Inner {
fn drop(&mut self) {
// running this to completion would block the current thread for several seconds so just
// fire and forget
let _ = Command::new("docker")
.args(["rm", "-f", &self.id])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_works() -> Result<()> {
let network = Network::new()?;
let container = Container::run(&Image::Client, &network)?;
let output = container.output(&["true"])?;
assert!(output.status.success());
Ok(())
}
#[test]
fn ipv4_addr_works() -> Result<()> {
let network = Network::new()?;
let container = Container::run(&Image::Client, &network)?;
let ipv4_addr = container.ipv4_addr();
let output = container.output(&["ping", "-c1", &format!("{ipv4_addr}")])?;
assert!(output.status.success());
Ok(())
}
#[test]
fn cp_works() -> Result<()> {
let network = Network::new()?;
let container = Container::run(&Image::Client, &network)?;
let path = "/tmp/somefile";
let contents = "hello";
container.cp(path, contents)?;
let output = container.output(&["cat", path])?;
dbg!(&output);
assert!(output.status.success());
assert_eq!(contents, output.stdout);
Ok(())
}
}

View File

@ -0,0 +1,156 @@
use std::{
process::{self, Command, Stdio},
sync::{
atomic::{self, AtomicUsize},
Arc,
},
};
use crate::Result;
/// Represents a network in which to put containers into.
#[derive(Clone)]
pub struct Network(Arc<NetworkInner>);
impl Network {
/// Returns the name of the network.
pub fn name(&self) -> &str {
self.0.name.as_str()
}
/// Returns the subnet mask
pub fn netmask(&self) -> &str {
&self.0.config.subnet
}
}
struct NetworkInner {
name: String,
config: NetworkConfig,
}
impl Network {
pub fn new() -> Result<Self> {
let pid = process::id();
let network_name = env!("CARGO_PKG_NAME");
Ok(Self(Arc::new(NetworkInner::new(pid, network_name)?)))
}
}
/// This ensure the Docker network is deleted after the test runner process ends.
impl Drop for NetworkInner {
fn drop(&mut self) {
let _ = Command::new("docker")
.args(["network", "rm", "--force", self.name.as_str()])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
}
impl NetworkInner {
pub fn new(pid: u32, network_name: &str) -> Result<Self> {
let count = network_count();
let network_name = format!("{network_name}-{pid}-{count}");
let mut command = Command::new("docker");
command
.args(["network", "create"])
.args(["--internal", "--attachable"])
.arg(&network_name);
// create network
let output = command.output()?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
return Err(format!("--- STDOUT ---\n{stdout}\n--- STDERR ---\n{stderr}").into());
}
// inspect & parse network details
let config = get_network_config(&network_name)?;
Ok(Self {
name: network_name,
config,
})
}
}
/// Collects all important configs.
pub struct NetworkConfig {
/// The CIDR subnet mask, e.g. "172.21.0.0/16"
subnet: String,
}
/// Return network config
fn get_network_config(network_name: &str) -> Result<NetworkConfig> {
let mut command = Command::new("docker");
command
.args([
"network",
"inspect",
"-f",
"{{range .IPAM.Config}}{{.Subnet}}{{end}}",
])
.arg(network_name);
let output = command.output()?;
if !output.status.success() {
return Err(format!("{command:?} failed").into());
}
let subnet = std::str::from_utf8(&output.stdout)?.trim().to_string();
Ok(NetworkConfig { subnet })
}
fn network_count() -> usize {
static COUNT: AtomicUsize = AtomicUsize::new(1);
COUNT.fetch_add(1, atomic::Ordering::Relaxed)
}
#[cfg(test)]
mod tests {
use crate::container::{Container, Image};
use super::*;
fn exists_network(network_name: &str) -> bool {
let mut command = Command::new("docker");
command.args(["network", "ls", "--format={{ .Name }}"]);
let output = command.output().expect("Failed to get output");
let stdout = String::from_utf8_lossy(&output.stdout);
stdout.trim().lines().any(|line| line == network_name)
}
#[test]
fn create_works() -> Result<()> {
let network = Network::new();
assert!(network.is_ok());
let network = network.expect("Failed to construct network");
assert!(exists_network(network.name()));
Ok(())
}
#[test]
fn remove_network_works() -> Result<()> {
let network = Network::new().expect("Failed to create network");
let network_name = network.name().to_string();
let container =
Container::run(&Image::Client, &network).expect("Failed to start container");
assert!(exists_network(&network_name));
drop(network);
assert!(exists_network(&network_name));
drop(container);
assert!(!exists_network(&network_name));
Ok(())
}
}

View File

@ -0,0 +1,10 @@
FROM debian:bookworm-slim
# ldns-utils = ldns-{key2ds,keygen,signzone}
# rm = remove default configuration files
RUN apt-get update && \
apt-get install -y \
bind9 \
ldnsutils \
tshark && \
rm -f /etc/bind/*

View File

@ -0,0 +1,8 @@
FROM debian:bookworm-slim
# dnsutils = dig & delv
# iputils-ping = ping
RUN apt-get update && \
apt-get install -y \
dnsutils \
iputils-ping

View File

@ -0,0 +1,15 @@
FROM rust:1-slim-bookworm
# ldns-utils = ldns-{key2ds,keygen,signzone}
RUN apt-get update && \
apt-get install -y \
ldnsutils \
tshark
# `dns-test` will invoke `docker build` from a temporary directory that contains
# a clone of the hickory repository. `./src` here refers to that clone; not to
# any directory inside the `dns-test` repository
COPY ./src /usr/src/hickory
RUN cargo install --path /usr/src/hickory/bin --features recursor,dnssec-ring --debug && \
mkdir /etc/hickory
env RUST_LOG=debug

View File

@ -0,0 +1,9 @@
FROM debian:bookworm-slim
# ldns-utils = ldns-{key2ds,keygen,signzone}
RUN apt-get update && \
apt-get install -y \
ldnsutils \
nsd \
tshark \
unbound

View File

@ -0,0 +1,134 @@
use core::fmt;
use core::str::FromStr;
use std::borrow::Cow;
use crate::{Error, Result};
#[derive(Clone, PartialEq)]
pub struct FQDN {
inner: Cow<'static, str>,
}
// TODO likely needs further validation
#[allow(non_snake_case)]
pub fn FQDN(input: impl Into<Cow<'static, str>>) -> Result<FQDN> {
let input = input.into();
if !input.ends_with('.') {
return Err("FQDN must end with a `.`".into());
}
if input != "." && input.starts_with('.') {
return Err("non-root FQDN cannot start with a `.`".into());
}
Ok(FQDN { inner: input })
}
impl FQDN {
pub const ROOT: FQDN = FQDN {
inner: Cow::Borrowed("."),
};
pub const COM: FQDN = FQDN {
inner: Cow::Borrowed("com."),
};
pub const NAMESERVERS: FQDN = FQDN {
inner: Cow::Borrowed("nameservers.com."),
};
pub fn is_root(&self) -> bool {
self.inner == "."
}
pub fn as_str(&self) -> &str {
&self.inner
}
pub fn into_owned(self) -> FQDN {
let owned = match self.inner {
Cow::Borrowed(borrowed) => borrowed.to_string(),
Cow::Owned(owned) => owned,
};
FQDN {
inner: Cow::Owned(owned),
}
}
pub fn parent(&self) -> Option<FQDN> {
let (fragment, parent) = self.inner.split_once('.').unwrap();
if fragment.is_empty() {
None
} else {
let parent = if parent.is_empty() {
FQDN::ROOT
} else {
FQDN(parent.to_string()).unwrap()
};
Some(parent)
}
}
pub fn num_labels(&self) -> usize {
self.inner
.split('.')
.filter(|label| !label.is_empty())
.count()
}
}
impl FromStr for FQDN {
type Err = Error;
fn from_str(input: &str) -> Result<Self> {
FQDN(input.to_string())
}
}
impl fmt::Debug for FQDN {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for FQDN {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.inner)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parent() -> Result<()> {
let mut fqdn = FQDN("example.nameservers.com.")?;
assert_eq!(3, fqdn.num_labels());
let parent = fqdn.parent();
assert_eq!(
Some("nameservers.com."),
parent.as_ref().map(|fqdn| fqdn.as_str())
);
fqdn = parent.unwrap();
assert_eq!(2, fqdn.num_labels());
let parent = fqdn.parent();
assert_eq!(Some(FQDN::COM), parent);
fqdn = parent.unwrap();
assert_eq!(1, fqdn.num_labels());
let parent = fqdn.parent();
assert_eq!(Some(FQDN::ROOT), parent);
fqdn = parent.unwrap();
assert_eq!(0, fqdn.num_labels());
let parent = fqdn.parent();
assert!(parent.is_none());
Ok(())
}
}

View File

@ -0,0 +1,211 @@
use core::fmt;
use std::borrow::Cow;
use std::path::Path;
use url::Url;
use crate::FQDN;
#[derive(Clone, Copy)]
pub enum Config<'a> {
NameServer {
origin: &'a FQDN,
},
Resolver {
use_dnssec: bool,
netmask: &'a str,
/// Extended DNS error (RFC8914)
ede: bool,
},
}
impl Config<'_> {
pub fn role(&self) -> Role {
match self {
Config::NameServer { .. } => Role::NameServer,
Config::Resolver { .. } => Role::Resolver,
}
}
}
#[derive(Clone, Copy)]
pub enum Role {
NameServer,
Resolver,
}
#[derive(Clone, Debug)]
pub enum Implementation {
Bind,
Hickory(Repository<'static>),
Unbound,
}
impl Implementation {
pub fn supports_ede(&self) -> bool {
match self {
Implementation::Bind => false,
Implementation::Hickory(_) => true,
Implementation::Unbound => true,
}
}
#[must_use]
pub fn is_bind(&self) -> bool {
matches!(self, Self::Bind)
}
#[must_use]
pub fn is_hickory(&self) -> bool {
matches!(self, Self::Hickory(_))
}
pub(crate) fn format_config(&self, config: Config) -> String {
match config {
Config::Resolver {
use_dnssec,
netmask,
ede,
} => match self {
Self::Bind => {
assert!(!ede, "the BIND resolver does not support EDE (RFC8914)");
minijinja::render!(
include_str!("templates/named.resolver.conf.jinja"),
use_dnssec => use_dnssec,
netmask => netmask,
)
}
Self::Hickory(_) => {
// TODO enable EDE in Hickory when supported
minijinja::render!(
include_str!("templates/hickory.resolver.toml.jinja"),
use_dnssec => use_dnssec,
)
}
Self::Unbound => {
minijinja::render!(
include_str!("templates/unbound.conf.jinja"),
use_dnssec => use_dnssec,
netmask => netmask,
ede => ede,
)
}
},
Config::NameServer { origin } => match self {
Self::Bind => {
minijinja::render!(
include_str!("templates/named.name-server.conf.jinja"),
fqdn => origin.as_str()
)
}
Self::Unbound => {
minijinja::render!(
include_str!("templates/nsd.conf.jinja"),
fqdn => origin.as_str()
)
}
Self::Hickory(_) => {
minijinja::render!(
include_str!("templates/hickory.name-server.toml.jinja"),
fqdn => origin.as_str()
)
}
},
}
}
pub(crate) fn conf_file_path(&self, role: Role) -> &'static str {
match self {
Self::Bind => "/etc/bind/named.conf",
Self::Hickory(_) => "/etc/named.toml",
Self::Unbound => match role {
Role::NameServer => "/etc/nsd/nsd.conf",
Role::Resolver => "/etc/unbound/unbound.conf",
},
}
}
pub(crate) fn cmd_args(&self, role: Role) -> &[&'static str] {
match self {
Implementation::Bind => &["named", "-g", "-d5"],
Implementation::Hickory(_) => &[
"sh",
"-c",
"echo $$ > /tmp/hickory.pid
exec hickory-dns -d",
],
Implementation::Unbound => match role {
Role::NameServer => &["nsd", "-d"],
Role::Resolver => &["unbound", "-d"],
},
}
}
pub(crate) fn pidfile(&self, role: Role) -> &'static str {
match self {
Implementation::Bind => "/tmp/named.pid",
Implementation::Hickory(_) => "/tmp/hickory.pid",
Implementation::Unbound => match role {
Role::NameServer => "/tmp/nsd.pid",
Role::Resolver => "/tmp/unbound.pid",
},
}
}
}
impl fmt::Display for Implementation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Implementation::Bind => "bind",
Implementation::Hickory(_) => "hickory",
Implementation::Unbound => "unbound",
};
f.write_str(s)
}
}
#[derive(Clone, Debug)]
pub struct Repository<'a> {
inner: Cow<'a, str>,
}
impl Repository<'_> {
pub(crate) fn as_str(&self) -> &str {
&self.inner
}
}
/// checks that `input` looks like a valid repository which can be either local or remote
///
/// # Panics
///
/// this function panics if `input` is not a local `Path` that exists or a well-formed URL
#[allow(non_snake_case)]
pub fn Repository(input: impl Into<Cow<'static, str>>) -> Repository<'static> {
let input = input.into();
assert!(
Path::new(&*input).exists() || Url::parse(&input).is_ok(),
"{input} is not a valid repository"
);
Repository { inner: input }
}
impl Default for Implementation {
fn default() -> Self {
Self::Unbound
}
}

View File

@ -0,0 +1,113 @@
//! A test framework for all things DNS
use std::env;
use lazy_static::lazy_static;
pub use crate::container::Network;
pub use crate::fqdn::FQDN;
pub use crate::implementation::{Implementation, Repository};
pub use crate::resolver::Resolver;
pub use crate::trust_anchor::TrustAnchor;
pub mod client;
mod container;
mod fqdn;
mod implementation;
pub mod name_server;
pub mod record;
mod resolver;
mod trust_anchor;
pub mod tshark;
pub mod zone_file;
pub type Error = Box<dyn std::error::Error>;
pub type Result<T> = core::result::Result<T, Error>;
// TODO maybe this should be a TLS variable that each unit test (thread) can override
const DEFAULT_TTL: u32 = 24 * 60 * 60; // 1 day
lazy_static! {
pub static ref SUBJECT: Implementation = parse_subject();
pub static ref PEER: Implementation = parse_peer();
}
fn parse_subject() -> Implementation {
if let Ok(subject) = env::var("DNS_TEST_SUBJECT") {
if subject == "unbound" {
return Implementation::Unbound;
}
if subject == "bind" {
return Implementation::Bind;
}
if subject.starts_with("hickory") {
if let Some(url) = subject.strip_prefix("hickory ") {
Implementation::Hickory(Repository(url.to_string()))
} else {
panic!("the syntax of DNS_TEST_SUBJECT is 'hickory $URL', e.g. 'hickory /tmp/hickory' or 'hickory https://github.com/owner/repo'")
}
} else {
panic!("unknown implementation: {subject}")
}
} else {
Implementation::default()
}
}
fn parse_peer() -> Implementation {
if let Ok(peer) = env::var("DNS_TEST_PEER") {
match peer.as_str() {
"unbound" => Implementation::Unbound,
"bind" => Implementation::Bind,
_ => panic!("`{peer}` is not supported as a test peer implementation"),
}
} else {
Implementation::default()
}
}
#[cfg(test)]
mod tests {
use std::env;
use super::*;
impl PartialEq for Implementation {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Hickory(_), Self::Hickory(_)) => true,
_ => core::mem::discriminant(self) == core::mem::discriminant(other),
}
}
}
#[test]
fn immutable_subject() {
let before = super::SUBJECT.clone();
let newval = if before == Implementation::Unbound {
"bind"
} else {
"unbound"
};
env::set_var("DNS_TEST_SUBJECT", newval);
let after = super::SUBJECT.clone();
assert_eq!(before, after);
}
#[test]
fn immutable_peer() {
let before = super::PEER.clone();
let newval = if before == Implementation::Unbound {
"bind"
} else {
"unbound"
};
env::set_var("DNS_TEST_PEER", newval);
let after = super::PEER.clone();
assert_eq!(before, after);
}
}

View File

@ -0,0 +1,609 @@
use core::sync::atomic::{self, AtomicUsize};
use std::net::Ipv4Addr;
use crate::container::{Child, Container, Network};
use crate::implementation::{Config, Role};
use crate::record::{self, Record, SoaSettings, DS, SOA};
use crate::tshark::Tshark;
use crate::zone_file::{self, Root, ZoneFile};
use crate::{Implementation, Result, TrustAnchor, DEFAULT_TTL, FQDN};
pub struct Graph {
pub nameservers: Vec<NameServer<Running>>,
pub root: Root,
pub trust_anchor: Option<TrustAnchor>,
}
/// Whether to sign the zone files
pub enum Sign<'a> {
No,
Yes,
/// Signs the zone files and then modifies the records produced by the signing process
AndAmend(&'a dyn Fn(&FQDN, &mut Vec<Record>)),
}
impl Graph {
/// Builds up a minimal DNS graph from `leaf` up to a root name server and returns all the
/// name servers in the graph
///
/// All new name servers will share the `Implementation` of `leaf`.
///
/// The returned name servers are sorted from leaf zone to root zone.
///
/// both `Sign::Yes` and `Sign::AndAmend` will add a DS record with the hash of the child's
/// key to the parent's zone file
///
/// a non-empty `TrustAnchor` is returned only when `Sign::Yes` or `Sign::AndAmend` is used
pub fn build(leaf: NameServer<Stopped>, sign: Sign) -> Result<Self> {
assert_eq!(2, leaf.zone().num_labels(), "not yet implemented");
assert_eq!(Some(FQDN::COM), leaf.zone().parent(), "not yet implemented");
// first pass: create nameservers for parent zones
let mut zone = leaf.zone().clone();
let network = leaf.container.network().clone();
let implementation = leaf.implementation.clone();
let (mut nameservers_ns, leaf) = if leaf.zone() != &FQDN::NAMESERVERS {
let nameservers_ns = NameServer::new(&implementation, FQDN::NAMESERVERS, &network)?;
(nameservers_ns, Some(leaf))
} else {
(leaf, None)
};
// the nameserver covering `FQDN::NAMESERVERS` needs A records about all the nameservers in the graph
let mut nameservers = vec![];
while let Some(parent) = zone.parent() {
let nameserver = NameServer::new(&implementation, parent.clone(), &network)?;
nameservers_ns.add(nameserver.a());
nameservers.push(nameserver);
zone = parent;
}
drop((network, implementation));
if let Some(leaf) = leaf {
nameservers.insert(0, leaf);
}
nameservers.insert(0, nameservers_ns);
// second pass: add referrals from parent to child
// the nameservers are sorted leaf-most zone first but siblings may be next to each other
// for each child (e.g. `nameservers.com.`), do a linear search for its parent (`com.`)
for index in 1..nameservers.len() {
let (left, right) = nameservers.split_at_mut(index);
let child = left.last_mut().unwrap();
for maybe_parent in right {
if Some(maybe_parent.zone()) == child.zone().parent().as_ref() {
let parent = maybe_parent;
parent.referral_nameserver(child);
break;
}
}
}
let root = nameservers.last().unwrap().root_hint();
// start name servers
let (nameservers, trust_anchor) = match sign {
Sign::No => (
nameservers
.into_iter()
.map(|nameserver| nameserver.start())
.collect::<Result<_>>()?,
None,
),
_ => {
let mut trust_anchor = TrustAnchor::empty();
let maybe_mutate = match sign {
Sign::No => unreachable!(),
Sign::Yes => None,
Sign::AndAmend(f) => Some(f),
};
let mut running = vec![];
let mut children_ds = vec![];
let mut children_num_labels = 0;
let len = nameservers.len();
for (index, mut nameserver) in nameservers.into_iter().enumerate() {
if !children_ds.is_empty() {
let is_parent = nameserver.zone().num_labels() + 1 == children_num_labels;
if is_parent {
for ds in children_ds.drain(..) {
nameserver.add(ds);
}
}
}
let mut nameserver = nameserver.sign()?;
children_ds.push(nameserver.ds().clone());
children_num_labels = nameserver.zone().num_labels();
if let Some(mutate) = maybe_mutate {
let zone = nameserver.zone().clone();
mutate(&zone, &mut nameserver.signed_zone_file_mut().records);
}
if index == len - 1 {
// the last nameserver covers `.`
trust_anchor.add(nameserver.key_signing_key().clone());
trust_anchor.add(nameserver.zone_signing_key().clone());
}
running.push(nameserver.start()?);
}
(running, Some(trust_anchor))
}
};
Ok(Graph {
nameservers,
root,
trust_anchor,
})
}
}
pub struct NameServer<State> {
container: Container,
implementation: Implementation,
state: State,
zone_file: ZoneFile,
}
impl NameServer<Stopped> {
/// Spins up a primary name server that has authority over the given `zone`
///
/// The initial state of the server is the "Stopped" state where it won't answer any query.
///
/// The FQDN of the name server will have the form `primary{count}.nameservers.com.` where
/// `{count}` is a (process-wide) unique, monotonically increasing integer
///
/// The zone file will contain these records
///
/// - one SOA record, with the primary name server field set to this name server's FQDN
/// - one NS record, with this name server's FQDN set as the only available name server for
/// the zone
pub fn new(implementation: &Implementation, zone: FQDN, network: &Network) -> Result<Self> {
let ns_count = ns_count();
let nameserver = primary_ns(ns_count, &zone);
let image = implementation.clone().into();
let container = Container::run(&image, network)?;
let soa = SOA {
zone: zone.clone(),
ttl: DEFAULT_TTL,
nameserver: nameserver.clone(),
admin: admin_ns(ns_count, &zone),
settings: SoaSettings::default(),
};
let mut zone_file = ZoneFile::new(soa);
zone_file.add(Record::ns(zone, nameserver.clone()));
// BIND requires that `nameserver` has an A record
zone_file.add(Record::a(nameserver.clone(), container.ipv4_addr()));
Ok(Self {
container,
implementation: implementation.clone(),
zone_file,
state: Stopped,
})
}
/// Adds a NS + A record pair to the zone file
pub fn referral(&mut self, zone: FQDN, nameserver: FQDN, ipv4_addr: Ipv4Addr) -> &mut Self {
self.zone_file.referral(zone, nameserver, ipv4_addr);
self
}
/// Adds a NS + A record pair to the zone file from another NameServer
pub fn referral_nameserver<T>(&mut self, nameserver: &NameServer<T>) -> &mut Self {
self.referral(
nameserver.zone().clone(),
nameserver.fqdn().clone(),
nameserver.ipv4_addr(),
)
}
/// Adds a record to the name server's zone file
pub fn add(&mut self, record: impl Into<Record>) -> &mut Self {
self.zone_file.add(record);
self
}
/// Freezes and signs the name server's zone file
pub fn sign(self) -> Result<NameServer<Signed>> {
// TODO do we want to make these settings configurable?
const ZSK_BITS: usize = 1024;
const KSK_BITS: usize = 2048;
const ALGORITHM: &str = "RSASHA1-NSEC3-SHA1";
let Self {
container,
zone_file,
implementation,
state: _,
} = self;
container.status_ok(&["mkdir", "-p", ZONES_DIR])?;
let zone_file_path = zone_file_path();
container.cp(&zone_file_path, &zone_file.to_string())?;
let zone = zone_file.origin();
let zsk_keygen =
format!("cd {ZONES_DIR} && ldns-keygen -a {ALGORITHM} -b {ZSK_BITS} {zone}");
let zsk_filename = container.stdout(&["sh", "-c", &zsk_keygen])?;
let zsk_path = format!("{ZONES_DIR}/{zsk_filename}.key");
let zsk: zone_file::DNSKEY = container.stdout(&["cat", &zsk_path])?.parse()?;
let ksk_keygen =
format!("cd {ZONES_DIR} && ldns-keygen -k -a {ALGORITHM} -b {KSK_BITS} {zone}");
let ksk_filename = container.stdout(&["sh", "-c", &ksk_keygen])?;
let ksk_path = format!("{ZONES_DIR}/{ksk_filename}.key");
let ksk: zone_file::DNSKEY = container.stdout(&["cat", &ksk_path])?.parse()?;
// -n = use NSEC3 instead of NSEC
// -p = set the opt-out flag on all nsec3 rrs
let signzone = format!(
"cd {ZONES_DIR} && ldns-signzone -n -p {ZONE_FILENAME} {zsk_filename} {ksk_filename}"
);
container.status_ok(&["sh", "-c", &signzone])?;
// TODO do we want to make the hashing algorithm configurable?
// -2 = use SHA256 for the DS hash
let key2ds = format!("cd {ZONES_DIR} && ldns-key2ds -n -2 {ZONE_FILENAME}.signed");
let ds: DS = container.stdout(&["sh", "-c", &key2ds])?.parse()?;
let signed: ZoneFile = container
.stdout(&["cat", &format!("{zone_file_path}.signed")])?
.parse()?;
let ttl = zone_file.soa.ttl;
Ok(NameServer {
container,
implementation,
zone_file,
state: Signed {
ds,
signed,
// inherit SOA's TTL value
ksk: ksk.with_ttl(ttl),
zsk: zsk.with_ttl(ttl),
},
})
}
/// Moves the server to the "Start" state where it can answer client queries
pub fn start(self) -> Result<NameServer<Running>> {
let Self {
container,
zone_file,
implementation,
state: _,
} = self;
let config = Config::NameServer {
origin: zone_file.origin(),
};
container.cp(
implementation.conf_file_path(config.role()),
&implementation.format_config(config),
)?;
container.status_ok(&["mkdir", "-p", ZONES_DIR])?;
container.cp(&zone_file_path(), &zone_file.to_string())?;
let child = container.spawn(implementation.cmd_args(config.role()))?;
Ok(NameServer {
container,
implementation,
zone_file,
state: Running { child },
})
}
}
const ZONES_DIR: &str = "/etc/zones";
const ZONE_FILENAME: &str = "main.zone";
fn zone_file_path() -> String {
format!("{ZONES_DIR}/{ZONE_FILENAME}")
}
fn ns_count() -> usize {
static COUNT: AtomicUsize = AtomicUsize::new(0);
COUNT.fetch_add(1, atomic::Ordering::Relaxed)
}
impl NameServer<Signed> {
/// Moves the server to the "Start" state where it can answer client queries
pub fn start(self) -> Result<NameServer<Running>> {
let Self {
container,
zone_file,
implementation,
state,
} = self;
let config = Config::NameServer {
origin: zone_file.origin(),
};
container.cp(
implementation.conf_file_path(config.role()),
&implementation.format_config(config),
)?;
container.cp(&zone_file_path(), &state.signed.to_string())?;
let child = container.spawn(implementation.cmd_args(config.role()))?;
Ok(NameServer {
container,
implementation,
zone_file,
state: Running { child },
})
}
pub fn key_signing_key(&self) -> &record::DNSKEY {
&self.state.ksk
}
pub fn zone_signing_key(&self) -> &record::DNSKEY {
&self.state.zsk
}
pub fn signed_zone_file(&self) -> &ZoneFile {
&self.state.signed
}
pub fn signed_zone_file_mut(&mut self) -> &mut ZoneFile {
&mut self.state.signed
}
pub fn ds(&self) -> &DS {
&self.state.ds
}
}
impl NameServer<Running> {
/// Starts a `tshark` instance that captures DNS messages flowing through this network node
pub fn eavesdrop(&self) -> Result<Tshark> {
self.container.eavesdrop()
}
/// gracefully terminates the name server collecting all logs
pub fn terminate(self) -> Result<String> {
let pidfile = self.implementation.pidfile(Role::NameServer);
// if `terminate` is called right after `start` NSD may not have had the chance to create
// the PID file so if it doesn't exist wait for a bit before invoking `kill`
let kill = format!(
"test -f {pidfile} || sleep 1
kill -TERM $(cat {pidfile})"
);
self.container.status_ok(&["sh", "-c", &kill])?;
let output = self.state.child.wait()?;
// the hickory-dns binary does not do signal handling so it won't shut down gracefully; we
// will still get some logs so we'll ignore the fact that it fails to shut down ...
let is_hickory = matches!(self.implementation, Implementation::Hickory(_));
if !is_hickory && !output.status.success() {
return Err(
format!("could not terminate the `{}` process", self.implementation).into(),
);
}
assert!(
output.stderr.is_empty(),
"stderr should be returned if not empty"
);
Ok(output.stdout)
}
}
impl<S> NameServer<S> {
pub fn container_id(&self) -> &str {
self.container.id()
}
pub fn ipv4_addr(&self) -> Ipv4Addr {
self.container.ipv4_addr()
}
/// Zone file BEFORE signing
pub fn zone_file(&self) -> &ZoneFile {
&self.zone_file
}
pub fn zone(&self) -> &FQDN {
self.zone_file.origin()
}
pub fn fqdn(&self) -> &FQDN {
&self.zone_file.soa.nameserver
}
/// Returns the [`Record::A`] record for this server.
pub fn a(&self) -> Record {
Record::a(self.fqdn().clone(), self.ipv4_addr())
}
/// Returns the [`Root`] hint for this server.
pub fn root_hint(&self) -> Root {
Root::new(self.fqdn().clone(), self.ipv4_addr())
}
}
pub struct Stopped;
pub struct Signed {
ds: DS,
zsk: record::DNSKEY,
ksk: record::DNSKEY,
signed: ZoneFile,
}
pub struct Running {
child: Child,
}
fn primary_ns(ns_count: usize, zone: &FQDN) -> FQDN {
FQDN(format!("primary{ns_count}.{}", expand_zone(zone))).unwrap()
}
fn admin_ns(ns_count: usize, zone: &FQDN) -> FQDN {
FQDN(format!("admin{ns_count}.{}", expand_zone(zone))).unwrap()
}
fn expand_zone(zone: &FQDN) -> String {
if zone == &FQDN::ROOT {
"nameservers.com.".to_string()
} else if zone.num_labels() == 1 {
format!("nameservers.{}", zone.as_str())
} else {
zone.to_string()
}
}
#[cfg(test)]
mod tests {
use std::thread;
use std::time::Duration;
use crate::client::{Client, DigSettings};
use crate::record::RecordType;
use crate::Repository;
use super::*;
#[test]
fn simplest() -> Result<()> {
let network = Network::new()?;
let tld_ns = NameServer::new(&Implementation::Unbound, FQDN::COM, &network)?.start()?;
let ip_addr = tld_ns.ipv4_addr();
let client = Client::new(&network)?;
let output = client.dig(DigSettings::default(), ip_addr, RecordType::SOA, &FQDN::COM)?;
assert!(output.status.is_noerror());
Ok(())
}
#[test]
fn with_referral() -> Result<()> {
let network = Network::new()?;
let expected_ip_addr = Ipv4Addr::new(172, 17, 200, 1);
let mut root_ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, &network)?;
root_ns.referral(
FQDN::COM,
FQDN("primary.tld-server.com.")?,
expected_ip_addr,
);
let root_ns = root_ns.start()?;
eprintln!("root.zone:\n{}", root_ns.zone_file());
let ipv4_addr = root_ns.ipv4_addr();
let client = Client::new(&network)?;
let output = client.dig(
DigSettings::default(),
ipv4_addr,
RecordType::NS,
&FQDN::COM,
)?;
assert!(output.status.is_noerror());
Ok(())
}
#[test]
fn signed() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, &network)?.sign()?;
eprintln!("KSK:\n{}", ns.key_signing_key());
eprintln!("ZSK:\n{}", ns.zone_signing_key());
eprintln!("root.zone.signed:\n{}", ns.signed_zone_file());
let tld_ns = ns.start()?;
let ns_addr = tld_ns.ipv4_addr();
let client = Client::new(&network)?;
let settings = *DigSettings::default().dnssec();
let output = client.dig(settings, ns_addr, RecordType::SOA, &FQDN::ROOT)?;
assert!(output.status.is_noerror());
let [soa, rrsig] = output
.answer
.try_into()
.expect("two records in answer section");
assert!(soa.is_soa());
let rrsig = rrsig.try_into_rrsig().unwrap();
assert_eq!(RecordType::SOA, rrsig.type_covered);
Ok(())
}
#[test]
fn terminate_nsd_works() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, &network)?.start()?;
let logs = ns.terminate()?;
assert!(logs.contains("nsd starting"));
Ok(())
}
#[test]
fn terminate_named_works() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&Implementation::Bind, FQDN::ROOT, &network)?.start()?;
let logs = ns.terminate()?;
eprintln!("{logs}");
assert!(logs.contains("starting BIND"));
Ok(())
}
#[test]
fn terminate_hickory_works() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(
&Implementation::Hickory(Repository("https://github.com/hickory-dns/hickory-dns")),
FQDN::ROOT,
&network,
)?
.start()?;
// hickory-dns does not do signal handling so we need to wait until it prints something to
// the console
thread::sleep(Duration::from_millis(500));
let logs = ns.terminate()?;
eprintln!("{logs}");
let mut found = false;
for line in logs.lines() {
if line.contains("Hickory DNS") && line.contains("starting") {
found = true;
}
}
assert!(found);
Ok(())
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,222 @@
use core::fmt::Write;
use std::io::{BufRead, BufReader};
use std::net::Ipv4Addr;
use crate::container::{Child, Container, Network};
use crate::implementation::{Config, Role};
use crate::record::DNSKEY;
use crate::trust_anchor::TrustAnchor;
use crate::tshark::Tshark;
use crate::zone_file::Root;
use crate::{Implementation, Result};
pub struct Resolver {
container: Container,
child: Child,
implementation: Implementation,
}
impl Resolver {
#[allow(clippy::new_ret_no_self)]
pub fn new(network: &Network, root: Root) -> ResolverSettings {
ResolverSettings {
ede: false,
network: network.clone(),
roots: vec![root],
trust_anchor: TrustAnchor::empty(),
}
}
pub fn eavesdrop(&self) -> Result<Tshark> {
self.container.eavesdrop()
}
pub fn network(&self) -> &Network {
self.container.network()
}
pub fn container_id(&self) -> &str {
self.container.id()
}
pub fn ipv4_addr(&self) -> Ipv4Addr {
self.container.ipv4_addr()
}
/// Gracefully terminates the name server collecting all logs
pub fn terminate(self) -> Result<String> {
let Resolver {
implementation,
container,
child,
} = self;
let pidfile = implementation.pidfile(Role::Resolver);
let kill = format!(
"test -f {pidfile} || sleep 1
kill -TERM $(cat {pidfile})"
);
container.status_ok(&["sh", "-c", &kill])?;
let output = child.wait()?;
// the hickory-dns binary does not do signal handling so it won't shut down gracefully; we
// will still get some logs so we'll ignore the fact that it fails to shut down ...
if !implementation.is_hickory() && !output.status.success() {
return Err(format!("could not terminate the `{}` process", implementation).into());
}
assert!(
output.stderr.is_empty(),
"stderr should be returned if not empty"
);
Ok(output.stdout)
}
}
pub struct ResolverSettings {
/// Extended DNS Errors (RFC8914)
ede: bool,
network: Network,
roots: Vec<Root>,
trust_anchor: TrustAnchor,
}
impl ResolverSettings {
/// Starts a DNS server in the recursive resolver role
///
/// This server is not an authoritative name server; it does not serve a zone file to clients
pub fn start(&self, implementation: &Implementation) -> Result<Resolver> {
let image = implementation.clone().into();
let container = Container::run(&image, &self.network)?;
let mut hints = String::new();
for root in &self.roots {
writeln!(hints, "{root}").unwrap();
}
container.cp("/etc/root.hints", &hints)?;
let use_dnssec = !self.trust_anchor.is_empty();
let config = Config::Resolver {
use_dnssec,
netmask: self.network.netmask(),
ede: self.ede,
};
container.cp(
implementation.conf_file_path(config.role()),
&implementation.format_config(config),
)?;
if use_dnssec {
let path = if implementation.is_bind() {
"/etc/bind/bind.keys"
} else {
"/etc/trusted-key.key"
};
let contents = if implementation.is_bind() {
self.trust_anchor.delv()
} else {
self.trust_anchor.to_string()
};
container.cp(path, &contents)?;
}
let mut child = container.spawn(implementation.cmd_args(config.role()))?;
// For HickoryDNS we need to wait until its start sequence finished. Only then the server is able
// to accept connections. The start sequence logs are consumed here.
if implementation.is_hickory() {
let stdout = child.stdout()?;
let lines = BufReader::new(stdout).lines();
for line in lines {
let line = line?;
if line.contains("Server starting up") {
break;
}
}
}
Ok(Resolver {
child,
container,
implementation: implementation.clone(),
})
}
/// Enables the Extended DNS Errors (RFC8914) feature
pub fn extended_dns_errors(&mut self) -> &mut Self {
self.ede = true;
self
}
/// Adds a root hint
pub fn root(&mut self, root: Root) -> &mut Self {
self.roots.push(root);
self
}
/// Adds a DNSKEY record to the trust anchor
pub fn trust_anchor_key(&mut self, key: DNSKEY) -> &mut Self {
self.trust_anchor.add(key.clone());
self
}
/// Adds all the keys in the `other` trust anchor to ours
pub fn trust_anchor(&mut self, other: &TrustAnchor) -> &mut Self {
for key in other.keys() {
self.trust_anchor.add(key.clone());
}
self
}
}
#[cfg(test)]
mod tests {
use crate::{name_server::NameServer, Repository, FQDN};
use super::*;
#[test]
fn terminate_unbound_works() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, &network)?.start()?;
let resolver = Resolver::new(&network, ns.root_hint()).start(&Implementation::Unbound)?;
let logs = resolver.terminate()?;
eprintln!("{logs}");
assert!(logs.contains("start of service"));
Ok(())
}
#[test]
fn terminate_bind_works() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, &network)?.start()?;
let resolver = Resolver::new(&network, ns.root_hint()).start(&Implementation::Bind)?;
let logs = resolver.terminate()?;
eprintln!("{logs}");
assert!(logs.contains("starting BIND"));
Ok(())
}
#[test]
fn terminate_hickory_works() -> Result<()> {
let network = Network::new()?;
let ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, &network)?.start()?;
let resolver = Resolver::new(&network, ns.root_hint()).start(&Implementation::Hickory(
Repository("https://github.com/hickory-dns/hickory-dns"),
))?;
let logs = resolver.terminate()?;
// Hickory-DNS start sequence log has been consumed in `ResolverSettings.start`.
assert!(logs.is_empty());
Ok(())
}
}

View File

@ -0,0 +1,4 @@
[[zones]]
zone = "{{ fqdn }}"
zone_type = "Primary"
file = "/etc/zones/main.zone"

View File

@ -0,0 +1,5 @@
[[zones]]
zone = "."
zone_type = "Hint"
stores = { type = "recursor", roots = "/etc/root.hints", security_aware = true }
enable_dnssec = {{ use_dnssec }}

View File

@ -0,0 +1,14 @@
options {
directory "/var/cache/bind";
pid-file "/tmp/named.pid";
recursion no;
dnssec-validation no;
allow-transfer { none; };
# significantly reduces noise in logs
empty-zones-enable no;
};
zone "{{ fqdn }}" IN {
type primary;
file "/etc/zones/main.zone";
};

View File

@ -0,0 +1,14 @@
options {
directory "/var/cache/bind";
pid-file "/tmp/named.pid";
recursion yes;
dnssec-validation {% if use_dnssec %} auto {% else %} no {% endif %};
allow-transfer { none; };
# significantly reduces noise in logs
empty-zones-enable no;
};
zone "." {
type hint;
file "/etc/root.hints";
};

View File

@ -0,0 +1,9 @@
server:
pidfile: /tmp/nsd.pid
remote-control:
control-enable: no
zone:
name: {{ fqdn }}
zonefile: /etc/zones/main.zone

View File

@ -0,0 +1,14 @@
server:
verbosity: 4
use-syslog: no
interface: 0.0.0.0
access-control: {{ netmask }} allow
root-hints: /etc/root.hints
pidfile: /tmp/unbound.pid
ede: {% if ede %} yes {% else %} no {% endif %}
{% if use_dnssec %}
trust-anchor-file: /etc/trusted-key.key
{% endif %}
remote-control:
control-enable: no

View File

@ -0,0 +1,55 @@
use core::fmt;
use crate::record::DNSKEY;
pub struct TrustAnchor {
keys: Vec<DNSKEY>,
}
impl TrustAnchor {
pub fn empty() -> Self {
Self { keys: Vec::new() }
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
pub fn add(&mut self, key: DNSKEY) -> &mut Self {
self.keys.push(key);
self
}
pub(crate) fn keys(&self) -> &[DNSKEY] {
&self.keys
}
/// formats the `TrustAnchor` in the format `delv` expects
pub(super) fn delv(&self) -> String {
let mut buf = "trust-anchors {".to_string();
for key in &self.keys {
buf.push_str(&key.delv());
}
buf.push_str("};");
buf
}
}
impl fmt::Display for TrustAnchor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for key in &self.keys {
writeln!(f, "{key}")?;
}
Ok(())
}
}
impl FromIterator<DNSKEY> for TrustAnchor {
fn from_iter<T: IntoIterator<Item = DNSKEY>>(iter: T) -> Self {
Self {
keys: iter.into_iter().collect(),
}
}
}

View File

@ -0,0 +1,391 @@
//! `tshark` JSON output parser
use core::result::Result as CoreResult;
use std::io::{BufRead, BufReader, Lines};
use std::net::Ipv4Addr;
use std::process::ChildStdout;
use std::sync::atomic::{self, AtomicUsize};
use serde::Deserialize;
use serde_with::{serde_as, DisplayFromStr};
use crate::container::{Child, Container};
use crate::Result;
static ID: AtomicUsize = AtomicUsize::new(0);
const UDP_PORT: u16 = 53;
impl Container {
pub fn eavesdrop(&self) -> Result<Tshark> {
let id = ID.fetch_add(1, atomic::Ordering::Relaxed);
let pidfile = pid_file(id);
let capture_file = capture_file(id);
// `docker exec $child` merges the child's stderr and stdout streams and pipes them into
// its stdout. as we cannot tell stdout (JSON) from stderr (log message) from the host side,
// we'll redirect the JSON output to a file inside the container and read the log messages
// from the host side
// --log-level info --log-domain main
let tshark = format!(
"echo $$ > {pidfile}
exec tshark --log-level debug --log-domain main,capture -l -i eth0 -T json -O dns -f 'udp port {UDP_PORT}' > {capture_file}"
);
let mut child = self.spawn(&["sh", "-c", &tshark])?;
let stdout = child.stdout()?;
let mut stdout = BufReader::new(stdout).lines();
for res in stdout.by_ref() {
let line = res?;
if line.contains("Capture started") {
break;
}
}
Ok(Tshark {
container: self.clone(),
child,
stdout,
id,
})
}
}
fn pid_file(id: usize) -> String {
format!("/tmp/tshark{id}.pid")
}
fn capture_file(id: usize) -> String {
format!("/tmp/tshark{id}.json")
}
pub struct Tshark {
child: Child,
container: Container,
id: usize,
stdout: Lines<BufReader<ChildStdout>>,
}
impl Tshark {
/// Blocks until `tshark` reports that it has captured new DNS messages
///
/// This method returns the number of newly captured messages
// XXX maybe do this automatically / always in `terminate`?
pub fn wait_for_capture(&mut self) -> Result<usize> {
// sync_pipe_input_cb(): new packets NN
for res in self.stdout.by_ref() {
let line = res?;
if line.contains(": new packets ") {
let (_rest, count) = line.rsplit_once(' ').unwrap();
return Ok(count.parse()?);
}
}
Err("unexpected EOF".into())
}
pub fn terminate(self) -> Result<Vec<Capture>> {
let pidfile = pid_file(self.id);
let kill = format!("test -f {pidfile} || sleep 1; kill $(cat {pidfile})");
self.container.status_ok(&["sh", "-c", &kill])?;
let output = self.child.wait()?;
if !output.status.success() {
return Err("could not terminate the `tshark` process".into());
}
// wait until the message "NN packets captured" appears
// wireshark will close stderr after printing that so exhausting
// the file descriptor produces the same result
for res in self.stdout {
res?;
}
let capture_file = capture_file(self.id);
let output = self.container.stdout(&["cat", &capture_file])?;
let mut messages = vec![];
let entries: Vec<Entry> = serde_json::from_str(&output)?;
let own_addr = self.container.ipv4_addr();
for entry in entries {
let Layers { ip, dns } = entry._source.layers;
let direction = if ip.dst == own_addr {
Direction::Incoming { source: ip.src }
} else if ip.src == own_addr {
Direction::Outgoing {
destination: ip.dst,
}
} else {
return Err(
format!("unexpected IP packet found in wireshark trace: {ip:?}").into(),
);
};
messages.push(Capture {
message: Message { inner: dns },
direction,
});
}
Ok(messages)
}
}
#[derive(Debug)]
pub struct Capture {
pub message: Message,
pub direction: Direction,
}
#[derive(Debug)]
pub struct Message {
// TODO this should be more "cooked", i.e. be deserialized into a `struct`
inner: serde_json::Value,
}
impl Message {
/// Returns `true` if the DO bit is set
///
/// Returns `None` if there's no OPT pseudo-RR
pub fn is_do_bit_set(&self) -> Option<bool> {
let do_bit = match self
.opt_record()?
.get("dns.resp.z_tree")?
.get("dns.resp.z.do")?
.as_str()?
{
"1" => true,
"0" => false,
_ => return None,
};
Some(do_bit)
}
/// Returns the "sender's UDP payload size" field in the OPT pseudo-RR
///
/// Returns `None` if there's no OPT record present
pub fn udp_payload_size(&self) -> Option<u16> {
self.opt_record()?
.get("dns.rr.udp_payload_size")?
.as_str()?
.parse()
.ok()
}
pub fn as_value(&self) -> &serde_json::Value {
&self.inner
}
pub fn is_ad_flag_set(&self) -> bool {
let Some(authenticated) = self.inner["dns.flags_tree"]
.as_object()
.unwrap()
.get("dns.flags.authenticated")
else {
return false;
};
let authenticated = authenticated.as_str().unwrap();
assert_eq!("1", authenticated);
true
}
fn opt_record(&self) -> Option<&serde_json::Value> {
for (key, value) in self.inner.get("Additional records")?.as_object()? {
if key.ends_with(": type OPT") {
return Some(value);
}
}
None
}
}
#[derive(Clone, Copy, Debug)]
pub enum Direction {
Incoming { source: Ipv4Addr },
Outgoing { destination: Ipv4Addr },
}
impl Direction {
pub fn try_into_incoming(self) -> CoreResult<Ipv4Addr, Self> {
if let Self::Incoming { source } = self {
Ok(source)
} else {
Err(self)
}
}
pub fn try_into_outgoing(self) -> CoreResult<Ipv4Addr, Self> {
if let Self::Outgoing { destination } = self {
Ok(destination)
} else {
Err(self)
}
}
}
#[derive(Deserialize)]
struct Entry {
_source: Source,
}
#[derive(Deserialize)]
struct Source {
layers: Layers,
}
#[derive(Deserialize)]
struct Layers {
ip: Ip,
dns: serde_json::Value,
}
#[serde_as]
#[derive(Debug, Deserialize)]
struct Ip {
#[serde(rename = "ip.src")]
#[serde_as(as = "DisplayFromStr")]
src: Ipv4Addr,
#[serde(rename = "ip.dst")]
#[serde_as(as = "DisplayFromStr")]
dst: Ipv4Addr,
}
#[cfg(test)]
mod tests {
use crate::client::{Client, DigSettings};
use crate::name_server::NameServer;
use crate::record::RecordType;
use crate::{Implementation, Network, Resolver, FQDN};
use super::*;
#[test]
fn nameserver() -> Result<()> {
let network = &Network::new()?;
let ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, network)?.start()?;
let mut tshark = ns.eavesdrop()?;
let client = Client::new(network)?;
let resp = client.dig(
DigSettings::default(),
ns.ipv4_addr(),
RecordType::SOA,
&FQDN::ROOT,
)?;
assert!(resp.status.is_noerror());
let captured = tshark.wait_for_capture()?;
assert_eq!(2, captured);
let messages = tshark.terminate()?;
let [first, second] = messages.try_into().expect("2 DNS messages");
assert_eq!(
client.ipv4_addr(),
first.direction.try_into_incoming().unwrap()
);
assert_eq!(
client.ipv4_addr(),
second.direction.try_into_outgoing().unwrap()
);
Ok(())
}
#[test]
fn resolver() -> Result<()> {
let network = &Network::new()?;
let mut root_ns = NameServer::new(&Implementation::Unbound, FQDN::ROOT, network)?;
let mut com_ns = NameServer::new(&Implementation::Unbound, FQDN::COM, network)?;
let mut nameservers_ns =
NameServer::new(&Implementation::Unbound, FQDN("nameservers.com.")?, network)?;
nameservers_ns.add(root_ns.a()).add(com_ns.a());
let nameservers_ns = nameservers_ns.start()?;
com_ns.referral_nameserver(&nameservers_ns);
let com_ns = com_ns.start()?;
root_ns.referral_nameserver(&com_ns);
let root_ns = root_ns.start()?;
let resolver =
Resolver::new(network, root_ns.root_hint()).start(&Implementation::Unbound)?;
let mut tshark = resolver.eavesdrop()?;
let resolver_addr = resolver.ipv4_addr();
let client = Client::new(network)?;
let settings = *DigSettings::default().recurse();
let output = client.dig(settings, dbg!(resolver_addr), RecordType::A, root_ns.fqdn())?;
assert!(output.status.is_noerror());
let count = tshark.wait_for_capture()?;
dbg!(count);
let messages = tshark.terminate()?;
assert!(messages.len() > 2);
let ns_addrs = dbg!([
root_ns.ipv4_addr(),
com_ns.ipv4_addr(),
nameservers_ns.ipv4_addr(),
]);
let client_addr = dbg!(client.ipv4_addr());
let mut from_client_count = 0;
let mut to_client_count = 0;
let mut to_ns_count = 0;
let mut from_ns_count = 0;
for message in messages {
match message.direction {
Direction::Incoming { source } => {
if source == client_addr {
from_client_count += 1;
} else if ns_addrs.contains(&source) {
from_ns_count += 1;
} else {
panic!(
"found packet coming from {source} which is outside the network graph"
)
}
}
Direction::Outgoing { destination } => {
if destination == client_addr {
to_client_count += 1;
} else if ns_addrs.contains(&destination) {
to_ns_count += 1;
} else {
panic!(
"found packet going to {destination} which is outside the network graph"
)
}
}
}
}
// query from client (dig)
assert_eq!(1, from_client_count);
// answer to client (dig)
assert_eq!(1, to_client_count);
// check that all queries sent to nameservers were answered
assert_eq!(to_ns_count, from_ns_count);
Ok(())
}
}

View File

@ -0,0 +1,226 @@
//! BIND-style zone files
//!
//! Note that
//! - the `@` syntax is not used to avoid relying on the order of the entries
//! - relative domain names are not used; all domain names must be in fully-qualified form
use core::fmt;
use std::array;
use std::net::Ipv4Addr;
use std::str::FromStr;
use crate::record::{self, Record, SOA};
use crate::{Error, Result, DEFAULT_TTL, FQDN};
pub struct ZoneFile {
origin: FQDN,
pub soa: SOA,
pub records: Vec<Record>,
}
impl ZoneFile {
/// Convenience constructor that uses "reasonable" defaults
pub fn new(soa: SOA) -> Self {
Self {
origin: soa.zone.clone(),
soa,
records: Vec::new(),
}
}
/// Adds the given `record` to the zone file
pub fn add(&mut self, record: impl Into<Record>) {
self.records.push(record.into())
}
/// Shortcut method for adding a referral (NS + A record pair)
pub fn referral(&mut self, zone: FQDN, nameserver: FQDN, ipv4_addr: Ipv4Addr) {
self.add(Record::ns(zone, nameserver.clone()));
self.add(Record::a(nameserver, ipv4_addr));
}
pub(crate) fn origin(&self) -> &FQDN {
&self.origin
}
}
impl fmt::Display for ZoneFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { soa, records, .. } = self;
writeln!(f, "{soa}")?;
for record in records {
writeln!(f, "{record}")?;
}
Ok(())
}
}
impl FromStr for ZoneFile {
type Err = Error;
fn from_str(input: &str) -> Result<Self> {
let mut records = vec![];
let mut maybe_soa = None;
for line in input.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let record: Record = line.parse()?;
if let Record::SOA(soa) = record {
if maybe_soa.is_some() {
return Err("found more than one SOA record".into());
}
maybe_soa = Some(soa);
} else {
records.push(record)
}
}
let soa = maybe_soa.ok_or("no SOA record found in zone file")?;
Ok(Self {
origin: soa.zone.clone(),
soa,
records,
})
}
}
/// A root (server) hint
#[derive(Clone)]
pub struct Root {
pub ipv4_addr: Ipv4Addr,
pub ns: FQDN,
pub ttl: u32,
}
impl Root {
/// Convenience constructor that uses "reasonable" defaults
pub fn new(ns: FQDN, ipv4_addr: Ipv4Addr) -> Self {
Self {
ipv4_addr,
ns,
ttl: DEFAULT_TTL,
}
}
}
impl fmt::Display for Root {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { ipv4_addr, ns, ttl } = self;
writeln!(f, ".\t{ttl}\tNS\t{ns}")?;
write!(f, "{ns}\t{ttl}\tA\t{ipv4_addr}")
}
}
// NOTE compared to `record::DNSKEY`, this zone file entry lacks the TTL field
#[allow(clippy::upper_case_acronyms)]
pub(crate) struct DNSKEY {
zone: FQDN,
flags: u16,
protocol: u8,
algorithm: u8,
public_key: String,
}
impl DNSKEY {
pub fn with_ttl(self, ttl: u32) -> record::DNSKEY {
let Self {
zone,
flags,
protocol,
algorithm,
public_key,
} = self;
record::DNSKEY {
zone,
ttl,
flags,
protocol,
algorithm,
public_key,
}
}
}
impl FromStr for DNSKEY {
type Err = Error;
fn from_str(mut input: &str) -> Result<Self> {
// discard trailing comment
if let Some((before, _after)) = input.split_once(';') {
input = before.trim();
}
let mut columns = input.split_whitespace();
let [Some(zone), Some(class), Some(record_type), Some(flags), Some(protocol), Some(algorithm), Some(public_key), None] =
array::from_fn(|_| columns.next())
else {
return Err("expected 7 columns".into());
};
if record_type != "DNSKEY" {
return Err(format!("tried to parse `{record_type}` record as a DNSKEY record").into());
}
if class != "IN" {
return Err(format!("unknown class: {class}").into());
}
Ok(Self {
zone: zone.parse()?,
flags: flags.parse()?,
protocol: protocol.parse()?,
algorithm: algorithm.parse()?,
public_key: public_key.to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn dnskey() -> Result<()> {
let input = ". IN DNSKEY 256 3 7 AwEAAaCUpg+5lH7vart4WiMw4lbbkTNKfkvoyXWsAj09Cc5lT1bFo6sS7o4evhzXU9+iDGZkWZnnkwWg2thXfGgNdfQNTKW/Owz9UMDGv5yjkANKI3fI4jHn7Xp1qIZAwZG0W3RU26s7vkKWVcmA3mrKlDIX9r4BRIZrBVOtNgiHydbB ;{id = 42933 (zsk), size = 1024b}";
let DNSKEY {
zone,
flags,
protocol,
algorithm,
public_key,
} = input.parse()?;
assert_eq!(FQDN::ROOT, zone);
assert_eq!(256, flags);
assert_eq!(3, protocol);
assert_eq!(7, algorithm);
let expected = "AwEAAaCUpg+5lH7vart4WiMw4lbbkTNKfkvoyXWsAj09Cc5lT1bFo6sS7o4evhzXU9+iDGZkWZnnkwWg2thXfGgNdfQNTKW/Owz9UMDGv5yjkANKI3fI4jHn7Xp1qIZAwZG0W3RU26s7vkKWVcmA3mrKlDIX9r4BRIZrBVOtNgiHydbB";
assert_eq!(expected, public_key);
Ok(())
}
#[test]
fn roundtrip() -> Result<()> {
// `ldns-signzone`'s output minus trailing comments; long trailing fields have been split as well
let input = include_str!("muster.zone");
let zone: ZoneFile = input.parse()?;
let output = zone.to_string();
assert_eq!(input, output);
Ok(())
}
}

View File

@ -0,0 +1,11 @@
. 86400 IN SOA primary0.nameservers.com. admin0.nameservers.com. 2024022028 1800 900 604800 86400
. 86400 IN RRSIG SOA 7 0 86400 20240319104519 20240220104519 11387 . Ks9b5tMyNxxrvw3JkgGkR2H5NPqTDwAwmwh3B7iNC0UHAYGU4B01ZJHj DIsJqDoJ2hsKG5oq0hQuwBSKv2nSBA1oSQcNrBDzOk105gu6tsXg2O8V ZCpAtEColco5ziOX8AWRqRMM5adSfA4xyj5H3NToMjRVDLpVpZsU4BAa 4dU=
. 86400 IN NS primary0.nameservers.com.
. 86400 IN RRSIG NS 7 0 86400 20240319104519 20240220104519 11387 . rZpACeVX3m2CwI/gY/rVYNOAs6ge4h+M74yV+CoAZYJaJLjeHd+jY0YV ixU3hap9bbFCZqhXKU5WSpJSsc/9PrgxEt2XycpbvAJwvIwdqWLUW741 /AOwnyrgv+7PLp4vkDdeLI9tcsY5V/ABpQrYW2i8Gtz90OEpvEEd5+4C LyU=
. 86400 IN DNSKEY 256 3 7 AwEAAbEzD/uB2WK89f+PJ1Lyg5xvdt9mXge/R5tiQl8SEAUh/kfbn8jQ iakH3HbBnBtdNXpjYrsmM7AxMmJLrp75dFMVnl5693/cY5k4dSk0BFJP QtBsZDn/7Q1rviQn0gqKNjaUfISuRpgCIWFKdRtTdq1VRDf3qIn7S/nu hfWE4w15
. 86400 IN DNSKEY 257 3 7 AwEAAco2Ck4XM5M4RO+QiwZhMFW9Hf8s0cOWH6QZ8OUQisjP6n+gYsbE pOOHhRiABN+QuVhRK9BN+Mt0LqMSBjSy53t5P3NerckqUTQ4HlZkn2QK bhc+TOgvHN5iDj0RBMkTaJ09y5vYmeNv5npFk6hV+VsbBoFRLXTuPSms 8LsH72W6y1HEHNzvAd5H3ro1d2awp66CXRTOcbXbFAIELpTgAU6ZJjEo RBMASZ3Ug4oZ96yvegy2OZnAyFsxBGdOvecs+zoYKeezqaq21YMpnZkf eE7RYexGPm1p8/7smQjBph/uoVDp5k5DuPkTmzpafVOn2YHGB395vT37 uLi9B5Oef9c=
. 86400 IN RRSIG DNSKEY 7 0 86400 20240319104519 20240220104519 11245 . yH/aEcWQhgfmf8RjByMYDDuglaquWsHECA+nRmedIA4Kz7Vc74f77JLi QrhvFFSIFkQNyixNsTugLmTZunphbLrbQNKTWw8gpgd/8u6Oc9OdTYJu T+ADL+Rrgge7mDkPjDRKNhQ6VkIiRzwLBFhoYTA1LZF98CAnJGQcpw4W 1YCkqPbXIzsa3hq2OajC8NzZMEgeI95N1CJ/o5AmhwLtWVuv04q+seGX roSiTlWIQRKGsbCR2v97UjMG4l9XIbijzZbY4dK2/4WrCIw9mjp/cSE8 r/AdfegTi1oqOM9i4QebKvyU9c3rnJRVbFMhEXL1e0M/5bZNytXp43ex VTTHcA==
. 3600 IN NSEC3PARAM 1 0 1 -
. 3600 IN RRSIG NSEC3PARAM 7 0 3600 20240319104519 20240220104519 11387 . IhM+g5s6DwlFKbj6+zd+f/CqN1I4/QtF0aTOMvf0c+s5l+emx/yZEVCT 8LdX4cmz72eYeC4w/dM2btrhhHohhb/hdK1v7ukxtBVgvk6pOmuye2/E cuGkll7B59l+wlRaSmeXAQjiCUX6gyg9tlvmtcnomWVgtjIgMKJpggy8 B6k=
fasdp12mo9fh69ahu5bseugoh3np33tc. 86400 IN NSEC3 1 1 1 - fasdp12mo9fh69ahu5bseugoh3np33tc NS SOA RRSIG DNSKEY NSEC3PARAM
fasdp12mo9fh69ahu5bseugoh3np33tc. 86400 IN RRSIG NSEC3 7 1 86400 20240319104519 20240220104519 11387 . dsdwsTOGL5BvrC1v/5bmDy5Bz8wnN/IG3XRAg6RqKVMK0fLPMsd5uhXm U2gPJ5xUg1RkBQ5+etlBRm2p7vSDjbMa/hjRbvUJgP+c4dL68g+FcHv4 v9fb1Jaao9Goy/ZxZ1dbwXAdxhi+pyvikCdNcKsdiCtFD9pX7V5Nh2Cc GQQ=