From 08e24e5d40f1bd026219464b6f7f217a0ea9afb6 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:17:29 +0100 Subject: [PATCH] [tests] Fuzz: cargo-fuzz targets for route files, header rules, share tokens, path_within and the CA's PEM/CSR parsing (tests/fuzz), a bounded run script that saves any crash as a hex regression, and every seed and saved crash replayed in cargo test --- Cargo.lock | 9 + Cargo.toml | 11 +- tests/fuzz/Cargo.toml | 16 ++ tests/fuzz/fuzz/Cargo.toml | 58 ++++ tests/fuzz/fuzz/fuzz_targets/header_rules.rs | 9 + tests/fuzz/fuzz/fuzz_targets/path_within.rs | 9 + tests/fuzz/fuzz/fuzz_targets/pki_pem.rs | 9 + tests/fuzz/fuzz/fuzz_targets/routes.rs | 9 + tests/fuzz/fuzz/fuzz_targets/share_token.rs | 9 + tests/fuzz/run.sh | 66 +++++ tests/fuzz/seeds/header_rules/proof | 5 + tests/fuzz/seeds/header_rules/set-and-remove | 7 + tests/fuzz/seeds/header_rules/values | 8 + tests/fuzz/seeds/path_within/dots | 1 + tests/fuzz/seeds/path_within/encoded | 1 + tests/fuzz/seeds/path_within/lookalike | 1 + tests/fuzz/seeds/path_within/plain | 1 + tests/fuzz/seeds/pki_pem/cert | 11 + tests/fuzz/seeds/pki_pem/csr | 7 + tests/fuzz/seeds/pki_pem/truncated | 4 + tests/fuzz/seeds/pki_pem/two-certs | 22 ++ tests/fuzz/seeds/routes/bad-path | 2 + tests/fuzz/seeds/routes/everything | 18 ++ tests/fuzz/seeds/routes/forward-auth | 11 + tests/fuzz/seeds/routes/plain | 4 + tests/fuzz/seeds/share_token/garbage-token | 1 + .../seeds/share_token/prefix-and-password | 1 + tests/fuzz/seeds/share_token/root | 1 + tests/fuzz/src/lib.rs | 263 ++++++++++++++++++ tests/fuzz/tests/regressions.rs | 100 +++++++ 30 files changed, 673 insertions(+), 1 deletion(-) create mode 100644 tests/fuzz/Cargo.toml create mode 100644 tests/fuzz/fuzz/Cargo.toml create mode 100644 tests/fuzz/fuzz/fuzz_targets/header_rules.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/path_within.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/pki_pem.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/routes.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/share_token.rs create mode 100755 tests/fuzz/run.sh create mode 100644 tests/fuzz/seeds/header_rules/proof create mode 100644 tests/fuzz/seeds/header_rules/set-and-remove create mode 100644 tests/fuzz/seeds/header_rules/values create mode 100644 tests/fuzz/seeds/path_within/dots create mode 100644 tests/fuzz/seeds/path_within/encoded create mode 100644 tests/fuzz/seeds/path_within/lookalike create mode 100644 tests/fuzz/seeds/path_within/plain create mode 100644 tests/fuzz/seeds/pki_pem/cert create mode 100644 tests/fuzz/seeds/pki_pem/csr create mode 100644 tests/fuzz/seeds/pki_pem/truncated create mode 100644 tests/fuzz/seeds/pki_pem/two-certs create mode 100644 tests/fuzz/seeds/routes/bad-path create mode 100644 tests/fuzz/seeds/routes/everything create mode 100644 tests/fuzz/seeds/routes/forward-auth create mode 100644 tests/fuzz/seeds/routes/plain create mode 100644 tests/fuzz/seeds/share_token/garbage-token create mode 100644 tests/fuzz/seeds/share_token/prefix-and-password create mode 100644 tests/fuzz/seeds/share_token/root create mode 100644 tests/fuzz/src/lib.rs create mode 100644 tests/fuzz/tests/regressions.rs diff --git a/Cargo.lock b/Cargo.lock index cabd477..6f37130 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1375,6 +1375,15 @@ dependencies = [ "x509-parser 0.18.1", ] +[[package]] +name = "ianitor-fuzz" +version = "0.1.0" +dependencies = [ + "ianitor-core", + "ianitor-edge", + "serde_json", +] + [[package]] name = "ianitor-testkit" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 2df601d..e479f4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,15 @@ [workspace] resolver = "3" -members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"] +members = [ + "crates/core", + "crates/edge", + "crates/control", + "tests/diff", + "tests/fuzz", + "tests/support", +] +# cargo-fuzz's own workspace (libFuzzer flags): tests/fuzz/fuzz. +exclude = ["tests/fuzz/fuzz"] [workspace.package] version = "0.1.0" diff --git a/tests/fuzz/Cargo.toml b/tests/fuzz/Cargo.toml new file mode 100644 index 0000000..6a71e8b --- /dev/null +++ b/tests/fuzz/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "ianitor-fuzz" +description = "Fuzz target bodies (cargo-fuzz in fuzz/) and the replay of every saved input as a regression test." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +ianitor-core.workspace = true +ianitor-edge.workspace = true +serde_json.workspace = true + +[lints] +workspace = true diff --git a/tests/fuzz/fuzz/Cargo.toml b/tests/fuzz/fuzz/Cargo.toml new file mode 100644 index 0000000..52aa028 --- /dev/null +++ b/tests/fuzz/fuzz/Cargo.toml @@ -0,0 +1,58 @@ +# cargo-fuzz project (libFuzzer). Its own workspace: libfuzzer-sys needs the fuzzer flags, which +# the main workspace must not get. The target bodies live in ../src/lib.rs (crate ianitor-fuzz). +# Run: tests/fuzz/run.sh (bounded; any crash fails and is saved as a regression). +[package] +name = "ianitor-fuzz-targets" +version = "0.0.0" +publish = false +edition = "2024" +license = "MPL-2.0" + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" +ianitor-fuzz = { path = ".." } + +[workspace] +members = ["."] + +[profile.release] +debug = 1 + +[[bin]] +name = "routes" +path = "fuzz_targets/routes.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "header_rules" +path = "fuzz_targets/header_rules.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "share_token" +path = "fuzz_targets/share_token.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "path_within" +path = "fuzz_targets/path_within.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "pki_pem" +path = "fuzz_targets/pki_pem.rs" +test = false +doc = false +bench = false + diff --git a/tests/fuzz/fuzz/fuzz_targets/header_rules.rs b/tests/fuzz/fuzz/fuzz_targets/header_rules.rs new file mode 100644 index 0000000..e631326 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/header_rules.rs @@ -0,0 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::header_rules(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/path_within.rs b/tests/fuzz/fuzz/fuzz_targets/path_within.rs new file mode 100644 index 0000000..d3966e1 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/path_within.rs @@ -0,0 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::path_within(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/pki_pem.rs b/tests/fuzz/fuzz/fuzz_targets/pki_pem.rs new file mode 100644 index 0000000..1f4e7e8 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/pki_pem.rs @@ -0,0 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::pki_pem(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/routes.rs b/tests/fuzz/fuzz/fuzz_targets/routes.rs new file mode 100644 index 0000000..ef51296 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/routes.rs @@ -0,0 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::routes_toml(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/share_token.rs b/tests/fuzz/fuzz/fuzz_targets/share_token.rs new file mode 100644 index 0000000..d6415ce --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/share_token.rs @@ -0,0 +1,9 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::share_token(data)); diff --git a/tests/fuzz/run.sh b/tests/fuzz/run.sh new file mode 100755 index 0000000..ef7451d --- /dev/null +++ b/tests/fuzz/run.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# +# ROADMAP §5 layer 3: a bounded cargo-fuzz run of every target. Any crash fails the run, and the +# crashing input is copied to tests/fuzz/regressions//, where `cargo test` replays it +# (tests/fuzz/tests/regressions.rs) until it is fixed; commit it with the fix. +# +# tests/fuzz/run.sh [seconds per target, default 60] [target ...] +# +# Needs cargo-fuzz (`cargo install cargo-fuzz`, or nixpkgs#cargo-fuzz). With no nightly toolchain, +# RUSTC_BOOTSTRAP=1 lets a stable rustc take cargo-fuzz's flags. SANITIZER=address (default none) +# turns on ASan where the toolchain ships its runtime (rustup's x86_64 Linux does). The growing +# corpus lives outside the repository: $IANITOR_FUZZ_CORPUS (default ~/.cache/ianitor-fuzz). +# Linux only (libFuzzer); output and logs go to $CARGO_TARGET_DIR or tests/fuzz/fuzz/target. +set -euo pipefail + +secs=${1:-60} +shift || true +here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +targets=("$@") +if [ ${#targets[@]} -eq 0 ]; then + targets=(routes header_rules share_token path_within pki_pem) +fi +corpus_root=${IANITOR_FUZZ_CORPUS:-$HOME/.cache/ianitor-fuzz} +sanitizer=${SANITIZER:-none} +logs=${CARGO_TARGET_DIR:-$here/fuzz/target}/fuzz-logs +mkdir -p "$logs" + +toolchain=() +if cargo +nightly --version >/dev/null 2>&1; then + toolchain=(+nightly) +else + export RUSTC_BOOTSTRAP=1 +fi +cargo "${toolchain[@]}" fuzz --version >/dev/null + +cd "$here/fuzz" +status=0 +printf '%-14s %10s %8s %s\n' target runs seconds result +for t in "${targets[@]}"; do + corpus="$corpus_root/$t" + artifacts="$logs/artifacts/$t/" + mkdir -p "$corpus" "$artifacts" + log="$logs/$t.log" + if cargo "${toolchain[@]}" fuzz run --sanitizer "$sanitizer" "$t" "$corpus" "$here/seeds/$t" -- \ + -max_total_time="$secs" -timeout=10 -rss_limit_mb=2048 -print_final_stats=1 \ + -artifact_prefix="$artifacts" >"$log" 2>&1; then + result=ok + else + result=CRASH + status=1 + mkdir -p "$here/regressions/$t" + for a in "$artifacts"*; do + [ -f "$a" ] || continue + # Hex text: a crash input may hold NUL bytes, which the pre-commit hook refuses. + od -An -tx1 -v "$a" | tr -d ' \n' >"$here/regressions/$t/$(basename "$a").hex" + echo " saved $(basename "$a").hex to tests/fuzz/regressions/$t/" >&2 + done + tail -40 "$log" >&2 + fi + runs=$(grep -Eo 'stat::number_of_executed_units: *[0-9]+' "$log" | grep -Eo '[0-9]+$' | tail -1 || true) + printf '%-14s %10s %8s %s\n' "$t" "${runs:-?}" "$secs" "$result" +done +exit $status diff --git a/tests/fuzz/seeds/header_rules/proof b/tests/fuzz/seeds/header_rules/proof new file mode 100644 index 0000000..1827ce1 --- /dev/null +++ b/tests/fuzz/seeds/header_rules/proof @@ -0,0 +1,5 @@ +auth = "forward-auth" +[[request_headers]] +action = "set" +name = "X-Ianitor-Proof" +secret = "ui-proof" diff --git a/tests/fuzz/seeds/header_rules/set-and-remove b/tests/fuzz/seeds/header_rules/set-and-remove new file mode 100644 index 0000000..886aba1 --- /dev/null +++ b/tests/fuzz/seeds/header_rules/set-and-remove @@ -0,0 +1,7 @@ +[[request_headers]] +action = "set" +name = "X-Api-Key" +secret = "api_key" +[[response_headers]] +action = "remove" +name = "X-Powered-By" diff --git a/tests/fuzz/seeds/header_rules/values b/tests/fuzz/seeds/header_rules/values new file mode 100644 index 0000000..e5ab83f --- /dev/null +++ b/tests/fuzz/seeds/header_rules/values @@ -0,0 +1,8 @@ +[[request_headers]] +action = "set" +name = "X-A" +value = "a b\tc" +[[request_headers]] +action = "set" +name = "Host" +value = "x" diff --git a/tests/fuzz/seeds/path_within/dots b/tests/fuzz/seeds/path_within/dots new file mode 100644 index 0000000..56b571b --- /dev/null +++ b/tests/fuzz/seeds/path_within/dots @@ -0,0 +1 @@ +/docs/docs/../secret \ No newline at end of file diff --git a/tests/fuzz/seeds/path_within/encoded b/tests/fuzz/seeds/path_within/encoded new file mode 100644 index 0000000..2a4ae8a --- /dev/null +++ b/tests/fuzz/seeds/path_within/encoded @@ -0,0 +1 @@ +/a/a/%2e%2e/b \ No newline at end of file diff --git a/tests/fuzz/seeds/path_within/lookalike b/tests/fuzz/seeds/path_within/lookalike new file mode 100644 index 0000000..8ba2661 --- /dev/null +++ b/tests/fuzz/seeds/path_within/lookalike @@ -0,0 +1 @@ +/a/a/‥/b \ No newline at end of file diff --git a/tests/fuzz/seeds/path_within/plain b/tests/fuzz/seeds/path_within/plain new file mode 100644 index 0000000..65ed1c8 --- /dev/null +++ b/tests/fuzz/seeds/path_within/plain @@ -0,0 +1 @@ +/a/b/a/b/c.pdf \ No newline at end of file diff --git a/tests/fuzz/seeds/pki_pem/cert b/tests/fuzz/seeds/pki_pem/cert new file mode 100644 index 0000000..46df837 --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/cert @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBljCCAT2gAwIBAgIUX1lbpmyTvnNF1T88oCzWlkJjimowCgYIKoZIzj0EAwIw +ITEfMB0GA1UEAwwWRnV6eiBTZWVkIEludGVybWVkaWF0ZTAeFw0yNjExMTAyMDE2 +NDZaFw0yNjEyMTAyMDE2NDZaMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1l +ZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANE +opzcnaKpjZLi2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8 +o1MwUTAdBgNVHQ4EFgQUiDYADaKex6pvmQqH2pZPzFQL1IQwHwYDVR0jBBgwFoAU +iDYADaKex6pvmQqH2pZPzFQL1IQwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AgNHADBEAiBsBb9NFAx5zJr/3DKmNqRnYInjf3NNpFxaQQX+bt8cxQIgIMr3auAS +Y4cr/K5PatZGUTXY6Yx8ljbAD6JEh9wnQ50= +-----END CERTIFICATE----- diff --git a/tests/fuzz/seeds/pki_pem/csr b/tests/fuzz/seeds/pki_pem/csr new file mode 100644 index 0000000..8cc83ec --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/csr @@ -0,0 +1,7 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHbMIGDAgEAMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1lZGlhdGUwWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANEopzcnaKpjZLi +2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8oAAwCgYIKoZI +zj0EAwIDRwAwRAIgOeNFc5Gs6sKwxgorIKYWPGiZggG/n1FMBHPbOvL/M8ECIDJB +ThJT2HWLs3qCmMJ5ElwMb8vh21I7AO0V4peZEx1d +-----END CERTIFICATE REQUEST----- diff --git a/tests/fuzz/seeds/pki_pem/truncated b/tests/fuzz/seeds/pki_pem/truncated new file mode 100644 index 0000000..4cf05c7 --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/truncated @@ -0,0 +1,4 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHbMIGDAgEAMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1lZGlhdGUwWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANEopzcnaKpjZLi +2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9 \ No newline at end of file diff --git a/tests/fuzz/seeds/pki_pem/two-certs b/tests/fuzz/seeds/pki_pem/two-certs new file mode 100644 index 0000000..7f7bed6 --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/two-certs @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIBljCCAT2gAwIBAgIUX1lbpmyTvnNF1T88oCzWlkJjimowCgYIKoZIzj0EAwIw +ITEfMB0GA1UEAwwWRnV6eiBTZWVkIEludGVybWVkaWF0ZTAeFw0yNjExMTAyMDE2 +NDZaFw0yNjEyMTAyMDE2NDZaMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1l +ZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANE +opzcnaKpjZLi2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8 +o1MwUTAdBgNVHQ4EFgQUiDYADaKex6pvmQqH2pZPzFQL1IQwHwYDVR0jBBgwFoAU +iDYADaKex6pvmQqH2pZPzFQL1IQwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AgNHADBEAiBsBb9NFAx5zJr/3DKmNqRnYInjf3NNpFxaQQX+bt8cxQIgIMr3auAS +Y4cr/K5PatZGUTXY6Yx8ljbAD6JEh9wnQ50= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIBljCCAT2gAwIBAgIUX1lbpmyTvnNF1T88oCzWlkJjimowCgYIKoZIzj0EAwIw +ITEfMB0GA1UEAwwWRnV6eiBTZWVkIEludGVybWVkaWF0ZTAeFw0yNjExMTAyMDE2 +NDZaFw0yNjEyMTAyMDE2NDZaMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1l +ZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANE +opzcnaKpjZLi2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8 +o1MwUTAdBgNVHQ4EFgQUiDYADaKex6pvmQqH2pZPzFQL1IQwHwYDVR0jBBgwFoAU +iDYADaKex6pvmQqH2pZPzFQL1IQwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AgNHADBEAiBsBb9NFAx5zJr/3DKmNqRnYInjf3NNpFxaQQX+bt8cxQIgIMr3auAS +Y4cr/K5PatZGUTXY6Yx8ljbAD6JEh9wnQ50= +-----END CERTIFICATE----- diff --git a/tests/fuzz/seeds/routes/bad-path b/tests/fuzz/seeds/routes/bad-path new file mode 100644 index 0000000..1550587 --- /dev/null +++ b/tests/fuzz/seeds/routes/bad-path @@ -0,0 +1,2 @@ +hosts/../x.tomlhostname = "A..test" +upstreams = ["ftp://x"] diff --git a/tests/fuzz/seeds/routes/everything b/tests/fuzz/seeds/routes/everything new file mode 100644 index 0000000..272406a --- /dev/null +++ b/tests/fuzz/seeds/routes/everything @@ -0,0 +1,18 @@ +secrets = ["api_key", "ui-proof"] +[forward_auth] +url = "http://127.0.0.1:9091/api/authz/forward-auth" +[acme] +directory = "https://acme.test/dir" +email = "a@b.test" +hostname = "b.test" +upstreams = ["https://[::1]:8443", "https://app.test:8443"] +tls = "letsencrypt" +websockets = true +share_links = true +access_log = "truncated" +[health_check] +path = "/healthz" +interval_secs = 5 +[[response_headers]] +action = "remove" +name = "Server" diff --git a/tests/fuzz/seeds/routes/forward-auth b/tests/fuzz/seeds/routes/forward-auth new file mode 100644 index 0000000..afd7b73 --- /dev/null +++ b/tests/fuzz/seeds/routes/forward-auth @@ -0,0 +1,11 @@ +secrets = ["api_key", "ui-proof"] +[forward_auth] +url = "http://127.0.0.1:9091/api/authz/forward-auth" +hostname = "ui.test" +upstreams = ["unix:/run/ianitor-control/ui.sock"] +tls = "domi" +auth = "forward-auth" +[[request_headers]] +action = "set" +name = "X-Ianitor-Proof" +secret = "ui-proof" diff --git a/tests/fuzz/seeds/routes/plain b/tests/fuzz/seeds/routes/plain new file mode 100644 index 0000000..ca54602 --- /dev/null +++ b/tests/fuzz/seeds/routes/plain @@ -0,0 +1,4 @@ +secrets = [] +hostname = "a.test" +upstreams = ["http://127.0.0.1:3000"] +tls = "domi" diff --git a/tests/fuzz/seeds/share_token/garbage-token b/tests/fuzz/seeds/share_token/garbage-token new file mode 100644 index 0000000..02fcc19 --- /dev/null +++ b/tests/fuzz/seeds/share_token/garbage-token @@ -0,0 +1 @@ +isl1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \ No newline at end of file diff --git a/tests/fuzz/seeds/share_token/prefix-and-password b/tests/fuzz/seeds/share_token/prefix-and-password new file mode 100644 index 0000000..ce59616 --- /dev/null +++ b/tests/fuzz/seeds/share_token/prefix-and-password @@ -0,0 +1 @@ +/docs/reporthunter2 \ No newline at end of file diff --git a/tests/fuzz/seeds/share_token/root b/tests/fuzz/seeds/share_token/root new file mode 100644 index 0000000..3b8f576 --- /dev/null +++ b/tests/fuzz/seeds/share_token/root @@ -0,0 +1 @@ +/ \ No newline at end of file diff --git a/tests/fuzz/src/lib.rs b/tests/fuzz/src/lib.rs new file mode 100644 index 0000000..912b4d6 --- /dev/null +++ b/tests/fuzz/src/lib.rs @@ -0,0 +1,263 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The fuzz targets' bodies (ROADMAP §5 layer 3), as plain functions: cargo-fuzz calls them +//! from `fuzz/fuzz_targets/*` (libFuzzer), and `tests/regressions.rs` replays every saved input +//! under `regressions//` in the ordinary `cargo test`, so a crash once found stays a +//! test. A target must never panic on any input; where a property is cheap, it is asserted +//! (a panic is how libFuzzer learns about it). +//! +//! Everything here is hostile input in production: route files (the routes repository), the +//! header rules in them, share tokens and paths from visitors, CSRs and PEM files handed to the +//! CA. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; +use std::sync::OnceLock; + +use ianitor_core::compile::{self, CompileOptions}; +use ianitor_core::edge_config::{EdgeConfig, EdgeTls}; +use ianitor_core::share::{self, LinkSpec, Revocations, ShareId, ShareKey}; +use ianitor_core::{SourceFile, load, pki, routes}; + +/// Every target, by the name its directories use. +pub const TARGETS: &[(&str, fn(&[u8]))] = &[ + ("routes", routes_toml), + ("header_rules", header_rules), + ("share_token", share_token), + ("path_within", path_within), + ("pki_pem", pki_pem), +]; + +fn text(data: &[u8]) -> String { + String::from_utf8_lossy(data).into_owned() +} + +/// The byte that splits one input into two (ASCII unit separator; not NUL, so seeds stay text +/// files the pre-commit hook accepts). +pub const SEP: u8 = 0x1f; + +/// Split at the first [`SEP`]: two independent inputs from one. +fn split2(data: &[u8]) -> (&[u8], &[u8]) { + match data.iter().position(|b| *b == SEP) { + Some(i) => (&data[..i], &data[i + 1..]), + None => (data, &[]), + } +} + +fn options() -> CompileOptions { + CompileOptions { + http_listen: "127.0.0.1:8080".parse().unwrap(), + https_listen: "127.0.0.1:8443".parse().unwrap(), + cert_dir: "/var/lib/ianitor/certs".into(), + state_dir: "/var/lib/ianitor/state".into(), + access_log: "/var/log/ianitor/access.log".into(), + caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), + caddy_admin: None, + caddy_admin_socket: Some("/run/caddy-fallback/admin.sock".into()), + trusted_proxies: vec!["127.0.0.1".parse().unwrap()], + proxy_socket: Some("/run/ianitor-proxy/edge.sock".into()), + } +} + +/// Load, then: both compilers succeed, are deterministic, and the edge config reads back. +fn compile_checked(site: &str, hosts: &[(String, String)]) { + let sources: Vec> = hosts + .iter() + .map(|(n, c)| SourceFile { + name: n, + contents: c, + }) + .collect(); + let Ok(model) = load( + &SourceFile { + name: "ianitor.toml", + contents: site, + }, + &sources, + ) else { + return; + }; + let o = options(); + let edge = compile::edge(&model, &o).expect("a valid model compiles for edge"); + let caddy = compile::caddy(&model, &o).expect("a valid model compiles for Caddy"); + assert_eq!( + edge, + compile::edge(&model, &o).unwrap(), + "edge output is deterministic" + ); + assert_eq!( + caddy, + compile::caddy(&model, &o).unwrap(), + "Caddy output is deterministic" + ); + let cfg: EdgeConfig = serde_json::from_str(&edge).expect("edge reads what core writes"); + let _: serde_json::Value = serde_json::from_str(&caddy).expect("the Caddy JSON is JSON"); + build_edge_runtime(cfg); +} + +/// The credentials directory the edge runtime reads secrets from (fixed test values). +fn creds_dir() -> &'static PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + let d = std::env::temp_dir().join(format!("ianitor-fuzz-creds-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("api_key"), b"fuzz-secret-value\n").unwrap(); + std::fs::write(d.join("ui-proof"), b"fuzz-proof-value\n").unwrap(); + std::fs::write( + d.join("share-link-key"), + b"fuzz-share-link-key-0123456789abcdef0123456789", + ) + .unwrap(); + d + }) +} + +/// Edge builds its runtime (header names and values, upstream addresses) from a compiled +/// config. Files are kept out of it: no certificates to read, no access log to open, no device +/// lists; what is left must build, since core validated it. +fn build_edge_runtime(mut cfg: EdgeConfig) { + cfg.device_certs = None; + for h in &mut cfg.hosts { + h.tls = EdgeTls::Acme; + h.access_log = false; + h.device_certs = false; + } + if let Err(e) = ianitor_edge::runtime::build(cfg, Some(creds_dir())) { + panic!("edge refused a config core compiled: {e}"); + } +} + +/// Route files: a site file and one host file, split at the first SEP. Also the repository +/// path check on the host file's first line. +pub fn routes_toml(data: &[u8]) { + let (site, host) = split2(data); + let (site, host) = (text(site), text(host)); + let path = host.lines().next().unwrap_or_default(); + let _ = routes::check_path(path, routes::EntryKind::File); + // Name the host file after the hostname it claims, so a valid file can get through. + let name = host + .lines() + .find_map(|l| l.trim().strip_prefix("hostname")) + .and_then(|r| r.split('"').nth(1)) + .unwrap_or("x.test") + .to_owned(); + compile_checked(&site, &[(format!("hosts/{name}.toml"), host)]); +} + +/// Header rules: the input is appended to a host file that is otherwise valid, so the fuzzer +/// spends its time on `[[request_headers]]` / `[[response_headers]]` (names, values, secrets, +/// the protected list), through both compilers and edge's runtime. +pub fn header_rules(data: &[u8]) { + let site = "secrets = [\"api_key\", \"ui-proof\"]\n"; + let host = format!( + "hostname = \"h.test\"\nupstreams = [\"http://127.0.0.1:9000\"]\ntls = \"domi\"\n{}", + text(data) + ); + compile_checked(site, &[("hosts/h.test.toml".to_owned(), host)]); +} + +fn key() -> &'static ShareKey { + static KEY: OnceLock = OnceLock::new(); + KEY.get_or_init(|| ShareKey::new(b"fuzz-share-link-key-0123456789abcdef0123456789").unwrap()) +} + +/// Share tokens from visitors: a token and a password (split at SEP) checked as a link and as +/// a session; then a link minted from the input's bytes verifies for its own host and password +/// only. +pub fn share_token(data: &[u8]) { + let (token, password) = split2(data); + let (token, password) = (text(token), text(password)); + let revs = Revocations::default(); + let _ = share::peek(&token); + let pw = (!password.is_empty()).then_some(password.as_str()); + let _ = share::verify_link(key(), "h.test", &token, pw, 1_000, &revs); + let _ = share::verify_session(key(), "h.test", &token, 1_000, &revs); + + // Round trip with input-derived claims. + let Ok(prefix) = share::check_prefix(&token) else { + return; + }; + let mut id = [0u8; 16]; + for (i, b) in data.iter().take(16).enumerate() { + id[i] = *b; + } + let spec = LinkSpec { + id: ShareId(id), + epoch: u32::from(data.first().copied().unwrap_or(0)), + expires_at: 2_000, + prefix: &prefix, + password: pw, + }; + let Ok(t) = share::mint(key(), "h.test", &spec) else { + return; + }; + let c = share::verify_link(key(), "h.test", &t, pw, 1_000, &revs) + .expect("a minted link verifies for its host"); + assert_eq!(c.prefix, prefix); + assert!( + share::path_within(&prefix, &prefix), + "a prefix covers itself" + ); + assert!( + share::verify_link(key(), "other.test", &t, pw, 1_000, &revs).is_err(), + "a link is bound to its host" + ); + if pw.is_some() { + assert!( + share::verify_link(key(), "h.test", &t, Some("not the password"), 1_000, &revs) + .is_err() + || password == "not the password", + "a password link needs its password" + ); + } + let s = share::session_value(key(), "h.test", &c); + assert!(share::verify_session(key(), "h.test", &s, 1_000, &revs).is_ok()); + assert!( + share::verify_link(key(), "h.test", &t, pw, 2_000, &revs).is_err(), + "expired" + ); +} + +/// Visitor paths against a share link's prefix: never a panic; a checked prefix covers itself; +/// a dot segment never escapes it. +pub fn path_within(data: &[u8]) { + let (prefix, path) = split2(data); + let (prefix, path) = (text(prefix), text(path)); + let _ = share::path_within(&prefix, &path); + if let Ok(p) = share::check_prefix(&prefix) { + assert!(share::path_within(&p, &p)); + let escape = format!("{}/../outside", p.trim_end_matches('/')); + assert!(!share::path_within(&p, &escape), "{escape} escaped {p}"); + } +} + +/// The root the CA target signs with (made once; the fuzzer never sees its key). +fn test_root() -> &'static (String, pki::KeyPair) { + static ROOT: OnceLock<(String, pki::KeyPair)> = OnceLock::new(); + ROOT.get_or_init(|| pki::create_root(1_700_000_000).unwrap()) +} + +/// PEM and CSRs handed to the CA: parsers never panic, and a CSR the root signs gives an +/// intermediate the root issued. +pub fn pki_pem(data: &[u8]) { + let (a, _) = split2(data); + let pem = text(a); + let _ = pki::inspect(&pem); + let _ = pki::inspect_der(a); + let _ = pki::chain_der(&pem); + let _ = pki::first_pem(&pem); + let _ = pki::public_key_der(&pem); + let _ = pki::csr_der(&pem); + let _ = pki::csr_public_key_der(&pem); + let _ = pki::KeyPair::from_pem(&pem); + let _ = pki::KeyPair::from_der(a); + let (root_pem, root_key) = test_root(); + let _ = pki::intermediate_problem(&pem, root_pem, 1_700_000_100); + let _ = pki::issued_by(&pem, root_pem); + if let Ok(cert) = pki::sign_intermediate(root_pem, root_key, &pem, 1_700_000_100) { + assert_eq!(pki::issued_by(&cert, root_pem).ok(), Some(true)); + } +} diff --git a/tests/fuzz/tests/regressions.rs b/tests/fuzz/tests/regressions.rs new file mode 100644 index 0000000..27dfbd3 --- /dev/null +++ b/tests/fuzz/tests/regressions.rs @@ -0,0 +1,100 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Every saved fuzz input, replayed in the ordinary `cargo test`: the seeds (`seeds//`, +//! the starting corpus) and every input that once crashed a target (`regressions//`, +//! copied there by `tests/fuzz/run.sh` as `.hex`, hex text, since a crash input may hold +//! NUL bytes the pre-commit hook refuses). A crash found once stays a failing test until fixed. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::Path; + +fn from_hex(raw: &[u8]) -> Option> { + let digits: Vec = raw + .iter() + .copied() + .filter(|c| !c.is_ascii_whitespace()) + .collect(); + if digits.len() % 2 != 0 { + return None; + } + digits + .chunks(2) + .map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok()) + .collect() +} + +fn replay(dir: &str) -> usize { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(dir); + let mut n = 0; + for (name, target) in ianitor_fuzz::TARGETS { + let d = root.join(name); + let Ok(entries) = std::fs::read_dir(&d) else { + continue; + }; + let mut files: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).collect(); + files.sort(); + for f in files.iter().filter(|f| f.is_file()) { + let raw = std::fs::read(f).unwrap(); + let data = if f.extension().is_some_and(|e| e == "hex") { + from_hex(&raw).unwrap_or_else(|| panic!("{}: not hex", f.display())) + } else { + raw + }; + let r = std::panic::catch_unwind(|| target(&data)); + assert!(r.is_ok(), "{name}: {} panics", f.display()); + n += 1; + } + } + n +} + +#[test] +fn every_seed_runs_clean() { + let n = replay("seeds"); + assert!(n >= 10, "the seed corpus has inputs for every target ({n})"); +} + +#[test] +fn every_saved_crash_stays_fixed() { + replay("regressions"); +} + +#[test] +fn every_target_has_seeds() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("seeds"); + for (name, _) in ianitor_fuzz::TARGETS { + let n = std::fs::read_dir(root.join(name)) + .map(|d| d.count()) + .unwrap_or(0); + assert!(n > 0, "no seeds for {name}"); + } +} + +/// The route seeds meant to be valid are: otherwise the fuzzer would start from refusals only +/// and seldom reach the compilers and edge's runtime. +#[test] +fn the_valid_route_seeds_load() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("seeds/routes"); + for name in ["plain", "forward-auth", "everything"] { + let data = std::fs::read(root.join(name)).unwrap(); + let i = data.iter().position(|b| *b == ianitor_fuzz::SEP).unwrap(); + let site = String::from_utf8(data[..i].to_vec()).unwrap(); + let host = String::from_utf8(data[i + 1..].to_vec()).unwrap(); + let hostname = host.lines().next().unwrap().split('"').nth(1).unwrap(); + let file = format!("hosts/{hostname}.toml"); + let r = ianitor_core::load( + &ianitor_core::SourceFile { + name: "ianitor.toml", + contents: &site, + }, + &[ianitor_core::SourceFile { + name: &file, + contents: &host, + }], + ); + assert!(r.is_ok(), "{name}: {:?}", r.err()); + } +}