From a1e932a192de6837796e2db5ba830957d54bb83e Mon Sep 17 00:00:00 2001 From: CI Test Date: Tue, 17 Nov 2026 13:03:09 +0000 Subject: [PATCH 1/2] security: close 2026-11-16 audit corrective program Implement and verify S1-S6 from plans/subsystems/security-hardening-roadmap.md: - S1: rustls 0.23.46, rustls-webpki 0.103.17, webpki-roots 1.0.12, rustls-platform-verifier 0.7.1, quinn 0.11.12/0.11.19/0.5.16, tokio 1.54.1; bundled-root wording corrected; insecure-hop warning; TLS private-key Debug redaction. - S2: russh 0.65.2 migration preserving known-hosts policy; certificate host keys rejected; crypto-bigint/ctutils moved to fixed versions. - S3: SOCKS4 full user:pass enforcement and no cache seeding on failure; UDP private-egress policy applied after DNS on all locally resolving paths; CGNAT/NAT64/6to4/Teredo/ORCHID classification; auth-without-TLS warning. - S4: IPv4-mapped IPv6 canonicalization for CIDR matching; literal-only CIDR warning and docs; admin Host/Origin/JSON Content-Type validation with allowed_hosts; non-loopback plaintext admin warning. - S5: updater fixture gating, in-process SHA-256, trusted absolute curl, private create-new staging with pre-extraction re-hash, system-proxy JSON redaction, and cargo deny --workspace check in CI/release preflight with a narrow tracked zip exception. - S6: pproxy auth-reuse documentation and startup warning; compat UDP error, translate --annotate, and reverse IR Debug redaction; manifest claim unchanged. Verification: cargo fmt --all --check; workspace clippy -D warnings; workspace tests 3097 passed / 0 failed; CLI and embed feature slices; embed OpenSSH 6/6; cargo deny --workspace check; cargo audit reports only the four tracked zip 6.0.0 advisories. No version bump, tag, or publication. --- .github/workflows/ci.yml | 22 + .github/workflows/release-binaries.yml | 16 +- Cargo.lock | 127 +++--- Cargo.toml | 2 +- architecture/admin.md | 23 +- architecture/protocols-socks.md | 18 +- architecture/routing.md | 24 +- architecture/transports-ssh-quic-h3.md | 71 +-- architecture/transports-tls.md | 18 +- architecture/udp.md | 39 +- crates/eggress-admin/src/client.rs | 1 + crates/eggress-admin/src/lib.rs | 274 ++++++++++++ crates/eggress-admin/src/routes.rs | 20 +- crates/eggress-admin/src/server.rs | 129 +++++- crates/eggress-cli/Cargo.toml | 9 +- crates/eggress-cli/src/cli.rs | 3 +- crates/eggress-cli/src/commands/pproxy.rs | 5 +- crates/eggress-cli/src/pproxy_exec.rs | 51 +++ crates/eggress-cli/src/update/download.rs | 359 ++++++++++++--- crates/eggress-cli/src/update/mod.rs | 253 +++++++++-- crates/eggress-cli/src/update/verify.rs | 114 ++++- crates/eggress-cli/tests/pproxy_cli.rs | 103 +++++ .../eggress-cli/tests/system_proxy_inspect.rs | 58 +++ crates/eggress-cli/tests/updater_trust.rs | 102 +++++ crates/eggress-config/Cargo.toml | 1 + .../eggress-config/src/compile/admin_hosts.rs | 235 ++++++++++ crates/eggress-config/src/compile/mod.rs | 3 + crates/eggress-config/src/compile/model.rs | 100 ++++- crates/eggress-config/src/compile/process.rs | 15 +- .../eggress-config/src/compile/upstreams.rs | 198 +++++++++ crates/eggress-config/src/lib.rs | 60 +++ crates/eggress-config/src/model.rs | 5 + crates/eggress-config/src/validate/core.rs | 14 + .../eggress-config/src/validate/security.rs | 182 +++++++- crates/eggress-config/src/validate/tests.rs | 389 ++++++++++++++++ crates/eggress-core/src/connector.rs | 151 ++++++- crates/eggress-pproxy-compat/src/args.rs | 67 +++ crates/eggress-pproxy-compat/src/lib.rs | 2 +- .../src/translate/intermediates.rs | 10 +- .../src/translate/model.rs | 58 ++- .../src/translate/native.rs | 1 + .../src/translate/tests.rs | 96 ++++ crates/eggress-pproxy-compat/src/uri.rs | 196 +++++++- crates/eggress-routing/src/lib.rs | 104 +++++ crates/eggress-routing/src/matcher.rs | 23 +- crates/eggress-runtime/src/supervisor.rs | 47 ++ .../eggress-runtime/src/supervisor/reload.rs | 27 +- .../src/supervisor/services.rs | 4 + crates/eggress-runtime/tests/admin.rs | 159 ++++++- crates/eggress-runtime/tests/observability.rs | 2 +- crates/eggress-server/src/accept/handlers.rs | 49 +- crates/eggress-server/src/accept/tests.rs | 175 ++++++++ crates/eggress-system-proxy/src/inspection.rs | 148 ++++++- crates/eggress-transport-ssh/src/lib.rs | 243 ++++++++-- crates/eggress-transport-tls/src/client.rs | 70 ++- crates/eggress-udp/src/direct.rs | 172 +++++++- crates/eggress-udp/src/error.rs | 2 + crates/eggress-udp/src/relay.rs | 136 +++++- crates/eggress-udp/src/security.rs | 118 +++-- crates/eggress-udp/src/standalone.rs | 7 +- .../eggress-udp/src/standalone_shadowsocks.rs | 85 +++- crates/eggress-udp/tests/standalone_udp.rs | 107 +++++ crates/eggress-udp/tests/udp_integration.rs | 3 + deny.toml | 45 +- docs/CI_STATUS.md | 8 +- docs/CONFIG_REFERENCE.md | 35 +- docs/INSTALLATION.md | 22 + docs/PPROXY_MIGRATION.md | 29 +- docs/ROADMAP.md | 53 ++- docs/SECURITY_REVIEW.md | 53 ++- docs/URI_GRAMMAR.md | 17 + docs/cli/PPROXY_CLI_INVENTORY.md | 11 +- docs/release/RELEASE_PROCESS.md | 9 +- docs/security/OPEN_PROXY_PREVENTION.md | 38 +- .../PPROXY_COMPAT_SECURITY_DIFFERENCES.md | 40 +- docs/security/SECURE_CONFIGURATION.md | 108 ++++- docs/security/THREAT_MODEL.md | 47 +- plans/closure/README.md | 10 +- plans/closure/delivery/004-status.md | 316 +++++++++++++ plans/closure/parity-compat/003-status.md | 320 ++++++++++++++ plans/closure/protocols-edge/003-status.md | 308 +++++++++++++ .../003-status.md | 303 +++++++++++++ plans/closure/transports/004-status.md | 329 ++++++++++++++ plans/closure/transports/005-status.md | 334 ++++++++++++++ plans/implementation/README.md | 11 +- .../004-updater-trust-and-advisory-gate.md | 357 +++++++++++++++ .../003-auth-reuse-and-compat-redaction.md | 343 ++++++++++++++ .../003-socks4-auth-and-udp-private-egress.md | 391 ++++++++++++++++ ...idr-canonicalization-and-admin-exposure.md | 321 ++++++++++++++ ...ust-and-dependency-advisory-remediation.md | 321 ++++++++++++++ .../005-russh-065-advisory-migration.md | 286 ++++++++++++ plans/registry.md | 28 +- plans/subsystems/README.md | 5 + plans/subsystems/delivery-roadmap.md | 24 +- plans/subsystems/parity-compat-roadmap.md | 27 +- plans/subsystems/protocols-edge-roadmap.md | 26 +- .../routing-health-observability-roadmap.md | 25 +- .../subsystems/security-hardening-roadmap.md | 417 ++++++++++++++++++ .../server-runtime-config-roadmap.md | 6 + plans/subsystems/transports-roadmap.md | 40 +- scripts/release-preflight.sh | 5 + 101 files changed, 9907 insertions(+), 466 deletions(-) create mode 100644 crates/eggress-cli/tests/system_proxy_inspect.rs create mode 100644 crates/eggress-cli/tests/updater_trust.rs create mode 100644 crates/eggress-config/src/compile/admin_hosts.rs create mode 100644 plans/closure/delivery/004-status.md create mode 100644 plans/closure/parity-compat/003-status.md create mode 100644 plans/closure/protocols-edge/003-status.md create mode 100644 plans/closure/routing-health-observability/003-status.md create mode 100644 plans/closure/transports/004-status.md create mode 100644 plans/closure/transports/005-status.md create mode 100644 plans/implementation/delivery/004-updater-trust-and-advisory-gate.md create mode 100644 plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md create mode 100644 plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md create mode 100644 plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md create mode 100644 plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md create mode 100644 plans/implementation/transports/005-russh-065-advisory-migration.md create mode 100644 plans/subsystems/security-hardening-roadmap.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb42dde3..13960693 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,6 +73,28 @@ jobs: - name: Check fuzz targets run: cargo check --manifest-path fuzz/Cargo.toml --bins + advisories: + # Dependency advisory gate (Delivery M004 / Security S5). + # + # `cargo deny` is pinned and installed from source (no third-party action + # runs in this job). `--workspace` is required: the root manifest is the + # `eggress-bench` package, so without it cargo-deny roots the graph at + # that crate and silently skips `eggress-cli` -> `eggup-archive` -> `zip`. + # `deny.toml` sets `[graph] all-features = true` so optional-only + # dependencies are scanned as well. The only ignores are the four tracked + # `zip 6.0.0` advisories (upstream-blocked on `eggup-archive`). + name: Dependency advisories + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install pinned cargo-deny + run: cargo install cargo-deny --locked --version 0.19.0 + - name: cargo deny --workspace check + run: cargo deny --workspace check + updater-matrix: # Delivery M003 evidence: the updater/archive path must execute (not # merely compile) on Linux, macOS, and Windows. Shell-candidate flow diff --git a/.github/workflows/release-binaries.yml b/.github/workflows/release-binaries.yml index 25b8a4ba..f4f2ad6f 100644 --- a/.github/workflows/release-binaries.yml +++ b/.github/workflows/release-binaries.yml @@ -45,7 +45,7 @@ jobs: preflight: name: Release preflight runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 20 outputs: tag: ${{ steps.resolve.outputs.tag }} version: ${{ steps.resolve.outputs.version }} @@ -79,6 +79,20 @@ jobs: git fetch --tags --force ./scripts/release-preflight.sh --tag "${{ steps.resolve.outputs.tag }}" + # Dependency advisory gate (Delivery M004): a tag cannot ship with an + # unreviewed advisory. `--workspace` includes every member (notably + # `eggress-cli` -> `eggup-archive` -> `zip`, which the default root-only + # graph omits); `deny.toml` audits the all-features graph and carries + # only the four tracked `zip 6.0.0` ignores. + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install pinned cargo-deny + shell: bash + run: cargo install cargo-deny --locked --version 0.19.0 + - name: Dependency advisory gate + shell: bash + run: cargo deny --workspace check + - name: Check installer syntax shell: bash run: | diff --git a/Cargo.lock b/Cargo.lock index 33152bdf..269ba7d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -183,9 +183,9 @@ dependencies = [ [[package]] name = "argon2" -version = "0.6.0-rc.8" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7af50940b73bf4e16c15c448a2b121c63f2d68e3e54b6a8731673cb4aa0cdff5" +checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" dependencies = [ "base64ct", "blake2", @@ -287,9 +287,9 @@ checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" [[package]] name = "blake2" -version = "0.11.0-rc.6" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "061f1a09225e328e1ffbb378d2d49923c0ca5fee19fb5ac1cc9c1e9d52b93690" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" dependencies = [ "digest 0.11.3", ] @@ -694,9 +694,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.7.5" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" dependencies = [ "cpubits", "ctutils", @@ -761,9 +761,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", "subtle", @@ -825,9 +825,9 @@ dependencies = [ [[package]] name = "der" -version = "0.8.0" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71fd89660b2dc699704064e59e9dba0147b903e85319429e131620d022be411b" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid", "pem-rfc7468", @@ -899,6 +899,7 @@ dependencies = [ "const-oid", "crypto-common 0.2.2", "ctutils", + "zeroize", ] [[package]] @@ -1043,6 +1044,7 @@ dependencies = [ "rustls", "serde", "serde_json", + "sha2 0.10.9", "tar", "tempfile", "tokio", @@ -1071,6 +1073,7 @@ dependencies = [ "tempfile", "thiserror", "toml", + "tracing", "zeroize", ] @@ -1638,7 +1641,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1843,7 +1846,6 @@ version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "337d46834ee672ab3e48caca2cb0c78cc174fb12b3a68d0d88f99a0519a5e36e" dependencies = [ - "generic-array 0.14.7", "rustversion", "typenum", ] @@ -2216,18 +2218,6 @@ dependencies = [ "hybrid-array", ] -[[package]] -name = "internal-russh-num-bigint" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8e22120c32fb4d19ec55fba35015f57095cd95a2e3b732e44457f5915b2ee8" -dependencies = [ - "num-integer", - "num-traits", - "rand 0.10.2", - "rand_core 0.10.1", -] - [[package]] name = "ipnet" version = "2.12.0" @@ -2242,7 +2232,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2503,12 +2493,14 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.8" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" dependencies = [ "num-integer", "num-traits", + "rand 0.10.2", + "rand_core 0.10.1", ] [[package]] @@ -2711,9 +2703,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pkcs1" -version = "0.8.0-rc.4" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e" +checksum = "6250dd7321adbe93d12b750aee0ced159fd13e77f625edcdf1cb6f83cd99f650" dependencies = [ "der", "spki", @@ -3015,9 +3007,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -3036,9 +3028,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.3", @@ -3059,16 +3051,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2 0.6.4", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3283,14 +3275,16 @@ dependencies = [ [[package]] name = "rsa" -version = "0.10.0-rc.18" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf" +checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" dependencies = [ "const-oid", "crypto-bigint", + "crypto-common 0.2.2", "crypto-primes", "digest 0.11.3", + "hmac 0.13.0", "pkcs1", "pkcs8", "rand_core 0.10.1", @@ -3302,9 +3296,9 @@ dependencies = [ [[package]] name = "russh" -version = "0.62.6" +version = "0.65.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b41043523e0edcbd4e31d00903e26f12994f63b21bae9904f7405c1ed92752a5" +checksum = "78229f06e4d96d83bea5f5133ad3b6e4b5f0ce22d8e31c1ff7243ec8e18d5ba1" dependencies = [ "aes 0.9.2", "bitflags", @@ -3332,7 +3326,6 @@ dependencies = [ "hex-literal", "hmac 0.13.0", "inout 0.2.2", - "internal-russh-num-bigint", "keccak", "log", "md5", @@ -3413,22 +3406,22 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -3462,9 +3455,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation", "core-foundation-sys", @@ -3478,20 +3471,20 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] name = "rustls-platform-verifier-android" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -3823,9 +3816,9 @@ dependencies = [ [[package]] name = "spki" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" dependencies = [ "base64ct", "der", @@ -3872,9 +3865,9 @@ dependencies = [ [[package]] name = "ssh-key" -version = "0.7.0-rc.11" +version = "0.7.0-rc.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a32fae177b74a22aa9c5b01bf7e68b33545be32d9e381e248058d2adc15ce3" +checksum = "0701b552e6bd8f13a6e07bde25307c32d7daad80a79b65832d110c0416e7b638" dependencies = [ "argon2", "bcrypt-pbkdf", @@ -3948,10 +3941,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4035,9 +4028,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.52.3" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -4478,9 +4471,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -4491,14 +4484,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.8", + "webpki-roots 1.0.12", ] [[package]] name = "webpki-roots" -version = "1.0.8" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -4509,7 +4502,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 045e7880..e26ecc32 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,7 +90,7 @@ webpki-roots = "0.26" pkcs8 = "0.11" rcgen = "0.13" criterion = { version = "0.5", features = ["html_reports"] } -russh = { version = "0.62.6", default-features = false, features = ["ring", "flate2", "rsa"] } +russh = { version = "0.65.2", default-features = false, features = ["ring", "flate2", "rsa"] } quinn = { version = "0.11.11", default-features = false, features = ["runtime-tokio", "rustls-ring", "platform-verifier"] } h3 = { version = "0.0.8", default-features = false } h3-quinn = { version = "0.0.10", default-features = false } diff --git a/architecture/admin.md b/architecture/admin.md index 1e6a676b..40e5e3f9 100644 --- a/architecture/admin.md +++ b/architecture/admin.md @@ -31,6 +31,9 @@ pub struct AdminState { pub reverse_registry: Arc, pub metrics_enabled: bool, pub auth: Option, + /// Accepted `Host` values (normalized: lowercase, no brackets or port). + /// Empty means "derive from the bound address at serve time". + pub allowed_hosts: Vec, } pub trait AdminSnapshotProvider: Send + Sync + 'static { @@ -70,14 +73,15 @@ pub struct StaticAdminSnapshot { pub snapshot: AdminSnapshot } ## How it works — request handling pipeline 1. **Accept** — `AdminServer::run()` loops on `self.listener.accept()`. Each connection acquires a semaphore permit from a pool of 64 (`server.rs:176-187`). If no permit is available, the connection is dropped immediately. -2. **Auth check** — before dispatching, `authorized()` (`server.rs:111`) checks `AdminState.auth`: +2. **Host validation** — `host_allowed()` runs before auth and before any body is read. The `Host` header is normalized (lowercase, port and IPv6 brackets stripped) and compared against `AdminState.allowed_hosts`; `X-Forwarded-Host` is ignored. A missing, unparseable, or unlisted host returns a generic `400 "bad request"` with no echo of the value. An empty `allowed_hosts` is replaced at startup with bind-derived defaults (`derive_allowed_hosts`), so loopback clients keep working. +3. **Auth check** — before dispatching, `authorized()` (`server.rs:111`) checks `AdminState.auth`: - **Bearer**: `Authorization: Bearer ` compared via `subtle::ConstantTimeEq` - **Basic**: `Authorization: Basic ` decoded, split on `:`, CT-compared - On failure: `401 "unauthorized"` with `WWW-Authenticate: Bearer, Basic` header; once an IP trips the failure limiter (5 fails/60 s → 30 s block), further attempts get `429 "too many authentication failures"` with a `Retry-After` header until the block lapses -3. **Timeout** — each HTTP/1.1 connection is wrapped in `tokio::time::timeout(Duration::from_secs(30), conn)` (`server.rs:243`). -4. **Snapshot** — handlers call `state.snapshot()` which delegates to `AdminSnapshotProvider::snapshot()`. A fresh snapshot is fetched per request, so reloads are immediately visible without restarting admin. -5. **Dispatch** — `handle_request()` (`routes.rs:15`) pattern-matches on path. Body-consuming endpoints (`/-/route-explain`) use `collect_limited()` to enforce the 16 KiB limit. -6. **Non-loopback warning** — `AdminServer::new()` logs a warning when bound to a non-loopback address (`server.rs:157-170`). +4. **Timeout** — each HTTP/1.1 connection is wrapped in `tokio::time::timeout(Duration::from_secs(30), conn)` (`server.rs:243`). +5. **Snapshot** — handlers call `state.snapshot()` which delegates to `AdminSnapshotProvider::snapshot()`. A fresh snapshot is fetched per request, so reloads are immediately visible without restarting admin. +6. **Dispatch** — `handle_request()` (`routes.rs:15`) pattern-matches on path. `/-/route-explain` requires `Content-Type: application/json` (`415` otherwise) and, when `Origin` is present, an allowlisted origin host (`403` otherwise, including `Origin: null` unless the literal entry `null` is configured); both checks precede body collection. Body-consuming endpoints use `collect_limited()` to enforce the 16 KiB limit. +7. **Non-loopback warning** — `AdminServer::new()` logs a plaintext-HTTP exposure warning when bound to a non-loopback address (`server.rs:159-173`); `validate_config_security` emits the same warning at config load, alongside the existing no-auth warning. ## Limits @@ -112,11 +116,15 @@ Thread-safe registry (`RwLock>`). R - **Auth per-request**: auth is checked inside the service_fn closure per request, not per-connection, so keep-alive connections are still gated. - **Body limit streaming**: `collect_limited()` rejects bodies exceeding 16 KiB chunk-by-chunk, avoiding unbounded memory allocation (`routes.rs:387`). - **Auth rate-limit**: the Nth failure that trips the per-IP limiter is itself a `429` (record-then-check); successes clear the IP's failure count. +- **Host allowlist**: the effective set is the compiled `admin.allowed_hosts` (bind-derived defaults plus configured entries) and is fixed for the server lifetime, because `admin.bind` is not hot-reloaded; `classify_reload_config` rejects a change to it with `restart required` for the same reason. Only the actual `Host` header counts; `X-Forwarded-Host` is ignored. +- **Origin/content-type gate**: `POST /-/route-explain` rejects a non-JSON `Content-Type` (`415`) and a disallowed `Origin` (`403`) before reading the body. Rejections never echo the rejected value, credentials, or topology. - **Identity validation**: empty identity rejected; identity over 256 bytes rejected; non-`None` identity wrapped as `ClientIdentity::Username` (`routes.rs:316-335`). ## Security notes - Admin is an operator surface; exposing it to the network without auth leaks topology, metrics, and routing state. Prefer loopback bind or configure auth. +- Admin speaks plaintext HTTP only (no native TLS; the CLI admin client rejects `https://`). A non-loopback bind emits a warning at config load and at runtime: use loopback with a VPN/SSH tunnel, or a TLS-terminating reverse proxy whose host name is listed in `admin.allowed_hosts`. +- `Host` validation is the DNS-rebinding defense: a browser page on an attacker origin can resolve its own name to `127.0.0.1`, so the header — not the socket address — decides whether the request is acceptable. A reverse-proxy or DNS-name deployment must list that host explicitly. - Auth is checked per-request (not per-connection), so keep-alive connections are still gated. - Bearer and Basic auth are both supported; configure one or the other via `AdminAuthConfig`. - The 16 KiB body limit prevents memory-exhaustion from oversized POST bodies. @@ -138,7 +146,9 @@ Thread-safe registry (`RwLock>`). R | Upstreams | JSON array of groups | | Config | JSON summary counts + listener names | | UDP | JSON association/target-flow/upstream-flow gauges, per-listener counts | -| Route-explain | POST-only (GET → 405); dry-run routing decision for `{target, listener, protocol, source?, identity?}` | +| Route-explain | POST-only (GET → 405); dry-run routing decision for `{target, listener, protocol, source?, identity?}`; `415` without a JSON content type; `403` for a disallowed `Origin` or `Origin: null` | +| Host validation | `Host: attacker.example` → `400 "bad request"`; `localhost`, `127.0.0.1`, `[::1]:port` accepted with no configuration; `X-Forwarded-Host` ignored; bad Host precedes `401` | +| Config `allowed_hosts` | Configured host accepted (port-insensitive), bind-derived defaults replaced by an explicit list, invalid/wildcard entry rejected at validation | | Reverse | Empty when no servers; reports registered server state (active_control, active_streams, denied_bind, dropped counters) | | PAC | Generated when configured, 404 when not; escaping of quotes, backslashes, line separators, C0 controls; host sorting; no-fallback mode | | Static content | Correct content type and body | @@ -158,6 +168,7 @@ Run: `cargo test -p eggress-admin` 8. `AdminState::generation()` (`server.rs:343`) calls `provider.snapshot().generation` — a convenience method that allocates a full snapshot just to read one field. 9. `build_response()` (`server.rs:369`) never emits an invalid status or injectable content type: out-of-range status falls back to 500, unparseable content type to `application/octet-stream`. 10. The `client.rs` route-explain client is HTTP/1.1-only: `https://` admin URLs are rejected, the default port is 9090, and responses over 1 MiB (`MAX_ADMIN_RESPONSE`) fail as transport errors. +11. `AdminState.allowed_hosts` is a plain `Vec`: construct it from the compiled `eggress_config::compile::AdminConfig` in production. Leaving it empty is supported — `run()` derives the bind-address defaults — but an embedder that sets it explicitly replaces those defaults, so a non-loopback or reverse-proxy deployment must include every `Host` clients send. ## See also diff --git a/architecture/protocols-socks.md b/architecture/protocols-socks.md index b637f91e..8f111f2c 100644 --- a/architecture/protocols-socks.md +++ b/architecture/protocols-socks.md @@ -152,7 +152,19 @@ version/cmd/atyp in hex. `From for io::Error` (:50). | UDP datagram | 65535 B | `udp_codec.rs:37` | **Constant-time compare**: SOCKS5 password via `subtle::ConstantTimeEq` -(:server.rs:338-346). SOCKS4 user_id is clear-text, not a credential. +(:server.rs:338-346). + +**SOCKS4 user ID as credential carrier**: SOCKS4 has no password field, and the +pinned pproxy 2.7.9 oracle matches `userid in users` where `users` holds full +`user:pass` strings. The listener-side enforcement therefore lives in +`eggress-server::accept` (`accept_socks4`), not in this protocol crate: +`read_socks4_request` only bounds and decodes the user ID (255 B, UTF-8). When +the listener has `[listeners.auth]`, the accept path compares the raw user ID +against `username:password` with `subtle::ConstantTimeEq`, returns a generic +authentication failure on any mismatch (no credential echo), derives the session +identity from the authenticated username, and seeds the IP-reuse cache only on +that full-credential success — a username-only user ID can never authenticate or +cache an identity. **Validation**: RSV must be 0x00 in CONNECT and UDP. FRAG must be 0x00. Empty SOCKS4a domain rejected (:server.rs:119). `send_method_selection` @@ -173,6 +185,10 @@ never downgrades password-required to no-auth (:server.rs:285-288). - `socks5/client.rs`: auth, CONNECT request, reply parsing. - `socks5/udp_codec.rs`: encode/decode roundtrip, RSV/FRAG rejection, short/oversized/zero-domain, payload preservation. +- `eggress-server` accept tests (`crates/eggress-server/src/accept/tests.rs`): + SOCKS4 full `user:pass` accepted with a `Username` identity, username-only / + wrong-password / empty user ID rejected with a generic error, no cache seeding + on failure, and peer-scoped reuse after a full-credential success. **Fuzz targets**: `socks5_handshake` exercises `parse_method_negotiation`, `parse_connect_request`, `parse_socks5_request`. diff --git a/architecture/routing.md b/architecture/routing.md index 5af57b5d..f7e070a4 100644 --- a/architecture/routing.md +++ b/architecture/routing.md @@ -85,6 +85,27 @@ fn route(&self, request: &RouteRequest) -> Result { `HostRegex` tests against the raw host string (no normalization). +### CIDR matching rules + +`DestinationCidr` and `SourceCidr` compare a canonicalized address via +`canonical_ip()` at `src/matcher.rs`: + +- `Ipv6Addr::to_ipv4_mapped()` converts an IPv4-mapped literal (`::ffff:a.b.c.d`) + to its IPv4 form before `ipnet::IpNet::contains`. `ipnet` refuses + cross-family comparisons, so without this step a dual-stack client could + bypass an IPv4 private-range rule by sending the mapped form. The mapped form + also cannot satisfy a `not { destination_cidr = … }` rule. +- Native IPv6 addresses keep their family, so an IPv4 CIDR does not match an + unrelated native IPv6 address and vice versa. +- Canonicalization is local to the comparison: the `TargetAddr`/`Source` in the + `RouteRequest` is never rewritten, so `route explain` reports exactly the + literal the client supplied. +- Matching stays literal-IP-only and synchronous: a `TargetHost::Domain` never + matches a CIDR and route evaluation performs no DNS resolution. Domain + private-egress protection belongs to the resolved-target guard, not to CIDR + rules; `validate_config_security` warns when a `reject` rule relies on a + private/reserved `destination_cidr` without a host condition. + ### Health state machine Six states in `HealthState` (`src/health.rs:12-19`): @@ -157,6 +178,7 @@ No Cargo features gate routing functionality (all routing code is always compile ## Security notes - `SourceCidr` / `SourcePort` match against `request.source` which is the peer socket address. Spoofable at the transport layer if the listener does not enforce real peer addresses (e.g. transparent proxy with netfilter). +- CIDR match inputs are canonicalized for address-family correctness (`canonical_ip()` in `src/matcher.rs`), but CIDR rules remain literal-IP-only: no DNS resolution is added to route evaluation, and the config validator warns when a `reject` rule treats a private `destination_cidr` as a complete private-network ACL. - `CompatRegexRule` compiles user-supplied regex. Regexes are bounded by `regex::Regex` complexity limits (DFA size). No user-controlled regex can cause exponential backtracking due to the regex crate's guarantees. - Credentials and secret-bearing URIs are redacted before logging; `RouteExplanation::chain` uses `RedactedUri::new()` (`src/explain.rs`). - `validate_upstream_id()` at `src/upstream.rs:21-28` enforces `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$` to prevent label injection. @@ -174,7 +196,7 @@ No Cargo features gate routing functionality (all routing code is always compile | Area | Files / tests | What is covered | |---|---|---| -| MatchExpr | `src/matcher.rs` (unit-test-free; covered by `src/lib.rs` tests) | 30+ tests: host exact/suffix/regex, CIDR IPv4/v6, port exact/range/set, source CIDR/port, listener, protocol, identity, composite All/AnyOf/Not, empty All/AnyOf | +| MatchExpr | `src/matcher.rs` (unit-test-free; covered by `src/lib.rs` tests) | 40+ tests: host exact/suffix/regex, CIDR IPv4/v6, IPv4-mapped IPv6 canonicalization for destination/source CIDR (including negation and an unchanged `route explain` target), port exact/range/set, source CIDR/port, listener, protocol, identity, composite All/AnyOf/Not, empty All/AnyOf | | Router decide/select | `src/router.rs` (unit-test-free; covered by `src/lib.rs` tests) | first-match-wins, default action, upstream group, reject, accessor methods | | Health state machine | `src/health.rs:366-710` | 15+ tests: every state transition, thread safety (100 threads), eligibility, timestamps, failure resets counter, Disabled terminal | | Jitter | `src/health.rs:678` | 1000 iterations, validates +/- 20% range | diff --git a/architecture/transports-ssh-quic-h3.md b/architecture/transports-ssh-quic-h3.md index a846ea4a..45ece00e 100644 --- a/architecture/transports-ssh-quic-h3.md +++ b/architecture/transports-ssh-quic-h3.md @@ -11,7 +11,7 @@ transport-agnostic. | Crate | Root file | Lines | Role | |---|---|---|---| -| `eggress-transport-ssh` | `src/lib.rs` | 572 | SSH client session cache, channel open, remote forward | +| `eggress-transport-ssh` | `src/lib.rs` | 749 | SSH client session cache, channel open, remote forward | | `eggress-transport-quic` | `src/lib.rs` | 609 | QUIC client/listener/connection/stream over quinn | | `eggress-protocol-h3` | `src/lib.rs` | 492 | HTTP/3 CONNECT client and server over QUIC | @@ -25,46 +25,54 @@ Single-file crate. All types and logic live in `src/lib.rs`. | Item | Line | Description | |---|---|---| -| `SshSessionCache` | :250 | `Arc>>>` cache | -| `::new()` / `::new_compatibility()` / `::with_known_hosts(path)` | :262/:279/:287 | Constructor variants | -| `::policy()` | :270 | Return the cache's `SshHostKeyPolicy` | -| `::open_tcp_channel()` | :295 | Direct TCP channel; validates port != 0 | -| `::open_tcp_channel_fresh()` | :315 | Unpooled TCP channel for nested hops (fresh session over the supplied prefix stream) | -| `::open_unix_channel()` | :362 | Unix domain socket channel; validates non-empty path | -| `::open_unix_channel_fresh()` | :338 | Unpooled Unix channel for nested hops | -| `::start_remote_tcp_forward()` | :386 | Server-side TCP forwarding (pproxy compat) | -| `::shutdown()` / `::invalidate(key)` | :473/:478 | Bulk clear / single session eviction | +| `SshSessionCache` | :284 | `Arc>>>` cache | +| `::new()` / `::new_compatibility()` / `::with_known_hosts(path)` | :296/:313/:321 | Constructor variants | +| `::policy()` | :304 | Return the cache's `SshHostKeyPolicy` | +| `::open_tcp_channel()` | :329 | Direct TCP channel; validates port != 0 | +| `::open_tcp_channel_fresh()` | :349 | Unpooled TCP channel for nested hops (fresh session over the supplied prefix stream) | +| `::open_unix_channel()` | :396 | Unix domain socket channel; validates non-empty path | +| `::open_unix_channel_fresh()` | :372 | Unpooled Unix channel for nested hops | +| `::start_remote_tcp_forward()` | :420 | Server-side TCP forwarding (pproxy compat) | +| `::shutdown()` / `::invalidate(key)` | :507/:512 | Bulk clear / single session eviction | | `SshStream` | :15 | Boxed SSH channel stream alias | | `SshTransportError` | — | Transport error taxonomy | -| `SshRemoteForward::address()` / `::port()` | :218/:223 | Bound forward address introspection | +| `SshRemoteForward::address()` / `::port()` | :252/:257 | Bound forward address introspection | | `SshAuth` | :44 | `Password(String)` or `PrivateKey(String)` — the latter is a filesystem *path* loaded via `russh::keys::load_secret_key`; debug redacts both | | `SshHostKeyPolicy` | :120 | `KnownHosts` / `KnownHostsFile(PathBuf)` / `InsecureCompatibility` | | `SshSessionKey` | :64 | Cache key: `host`, `port`, `username`, `auth`, `hop_index`, `policy` | -| `SshRemoteForward` | :209 | Session handle + `mpsc::Receiver` for forwarded channels | -| `SshRemoteForward::accept()` | :228 | Wait for next incoming connection | -| `SshRemoteForward::cancel()` | :236 | Cancel forward while retaining session | +| `SshRemoteForward` | :243 | Session handle + `mpsc::Receiver` for forwarded channels | +| `SshRemoteForward::accept()` | :262 | Wait for next incoming connection | +| `SshRemoteForward::cancel()` | :270 | Cancel forward while retaining session | ### How it works -1. `get_or_connect()` (:423) locks cache, checks `!session.is_closed()`, +1. `get_or_connect()` (:457) locks cache, checks `!session.is_closed()`, removes dead entries, then calls `connect_authenticated_with_config()`. -2. Auth (:554-569): `Password` → `authenticate_password`; `PrivateKey` → +2. Auth (:576-604): `Password` → `authenticate_password`; `PrivateKey` → `russh::keys::load_secret_key` → `PrivateKeyWithHashAlg` → `authenticate_publickey`. 3. Keepalive hardcoded: `keepalive_interval = 60s`, `keepalive_max = 3` - (:450-451). -4. Host key verification (:137-171): `KnownHosts` → `check_known_hosts`, + (:484-485; the fresh-session helper repeats it at :569-570). +4. Host key verification is `verify_host_key()` (:135-175), called from the + `check_server_key` handler (:181): `KnownHosts` → `check_known_hosts`, `KnownHostsFile` → `check_known_hosts_path`, `InsecureCompatibility` → `true`. -5. `CompatClient` (:87) is a private `russh::client::Handler`. Its - `forwarded_channels` field enables `server_channel_open_forwarded_tcpip` - (:176) for reverse-forwarded channels. -6. Remote forward (:386+) bypasses cache — always creates a fresh + A known_hosts lookup error is logged and rejected, never downgraded. +5. `CompatClient` (:87) is a private `russh::client::Handler` for + `russh` 0.65. `check_server_key` takes + `&russh::keys::PublicKeyOrCertificate` and rejects the `Certificate` variant + outright (:192-200), so `verify_host_key` only ever sees a plain key; this + matches pre-0.65 behaviour, where a certificate host key failed key parsing. + Its `forwarded_channels` field enables `server_channel_open_forwarded_tcpip` + (:210) for reverse-forwarded channels. +6. Remote forward (:420+) bypasses cache — always creates a fresh session (mpsc channel depth 128). Non-loopback bind emits `tracing::warn` - (:394-397). + (:428-433). ### Security notes -- `InsecureCompatibility` exists solely for pproxy parity (:125); - disables host-key verification, emits `tracing::warn` per connection. +- `InsecureCompatibility` exists solely for pproxy parity (:126); + disables host-key verification, emits `tracing::warn` per connection. It is + constructed only by `SshSessionCache::new_compatibility()`, which is gated + behind the `pproxy-compat` feature. - `SshSessionCache::new()` retains verified native known-hosts behavior; `eggress-embed::outbound::OutboundConnector` selects it for TOML chains and selects `new_compatibility()` only for its explicitly pproxy-compatible @@ -74,8 +82,14 @@ Single-file crate. All types and logic live in `src/lib.rs`. retained by the returned channel until it closes. - An explicit hop-zero `local_bind` uses a fresh SSH session so a cached transport cannot bypass its source-address policy. -- Both `SshAuth::Debug` (:49) and `SshSessionKey::Debug` (:68) redact +- Both `SshAuth::Debug` (:49) and `SshSessionKey::Debug` (:73) redact secrets with `****`. +- SSH certificate host keys are unsupported under every policy, including + insecure compatibility; they are rejected rather than mapped onto the + certified plain key. +- The crate pins `russh` 0.65.x with `default-features = false` and the `ring` + feature set (RUSTSEC-2026-0492/-0495 and the `crypto-bigint`/`ctutils` timing + advisories are fixed there). `aws-lc-rs` must never be enabled. ### Reviewer gotchas @@ -83,7 +97,7 @@ Single-file crate. All types and logic live in `src/lib.rs`. - `SshSessionKey` equality includes `hop_index`, but position does not identify an arbitrary route prefix. Nested outbound hops bypass the cache instead of relying on that field for cross-chain isolation. -- Auth failure (:569) returns `AuthenticationFailed`; the handle is not +- Auth failure (:603) returns `AuthenticationFailed`; the handle is not yet in cache at that point. --- @@ -193,7 +207,8 @@ HTTP/3 CONNECT protocol layer over the QUIC transport. ## Review entry points -- SSH: `cargo test -p eggress-transport-ssh --test openssh` +- SSH policy/redaction unit tests: `cargo test -p eggress-transport-ssh` +- SSH OpenSSH interop: `cargo test -p eggress-transport-ssh --features pproxy-compat --test openssh` - QUIC: `cargo test -p eggress-transport-quic --features insecure-quic` (round-trip tests are `#[cfg(all(test, feature = "insecure-quic"))]`; plain `cargo test` runs unit/config tests only) - H3: `cargo test -p eggress-protocol-h3 --features insecure-quic` (same gating as QUIC) diff --git a/architecture/transports-tls.md b/architecture/transports-tls.md index d66320a6..b0bbc889 100644 --- a/architecture/transports-tls.md +++ b/architecture/transports-tls.md @@ -7,9 +7,9 @@ The only TLS implementation in the workspace (no OpenSSL anywhere). Wraps | File | Role | |---|---| -| `src/client.rs` | `TlsClientConfigBuilder`: system/custom CA PEM, ALPN, insecure mode, server-name override, `InsecureVerifier` (test/feature-gated), process-shared default verified/H2 accessors | +| `src/client.rs` | `TlsClientConfigBuilder`: bundled-Mozilla/custom CA PEM, ALPN, insecure mode, server-name override, `InsecureVerifier` (test/feature-gated), process-shared default verified/H2 accessors | | `src/server.rs` | `TlsServerConfigBuilder`: cert chain + key PEM (PKCS#8), ALPN (PEM loaders are private helpers, not exported) | -| `src/roots.rs` | `load_system_roots` (webpki-roots), `load_pem_roots` (PEM -> RootCertStore), `load_pem_certs` (PEM -> Vec). Empty PEM is an error in `load_pem_roots` | +| `src/roots.rs` | `load_system_roots` (bundled `webpki-roots`), `load_pem_roots` (PEM -> RootCertStore), `load_pem_certs` (PEM -> Vec). Empty PEM is an error in `load_pem_roots` | | `src/transport.rs` | `tls_connect(stream, config, server_name)` / `tls_accept(stream, config)`: BoxStream in, TLS-wrapped BoxStream out | | `src/lib.rs` | Re-exports, `install_default_crypto_provider()` (ring, once), test-only crate-private `self_signed_cert()` (`#[cfg(test)] pub(crate)`) | | `src/error.rs` | `TlsError` enum | @@ -21,7 +21,7 @@ The only TLS implementation in the workspace (no OpenSSL anywhere). Wraps | Method | Notes | |---|---| | `new()` | Empty root store, no ALPN, no override, not insecure | -| `with_system_roots()` | Extends root store from `webpki_roots::TLS_SERVER_ROOTS` | +| `with_system_roots()` | Extends root store from `webpki_roots::TLS_SERVER_ROOTS`. The name is historical: this is the **bundled Mozilla root set compiled into the binary**, not the operating-system trust store. It changes only when the `webpki-roots` dependency is updated | | `with_custom_ca_pem(pem_bytes)` | Replaces root store with parsed PEM CA certs | | `with_client_cert_pem(cert_pem, key_pem)` | mTLS client identity (both required; malformed PEM fails at `build`) | | `with_alpn(protocols)` | Sets ALPN protocol list (e.g., `b"h2"`, `b"http/1.1"`) | @@ -53,7 +53,7 @@ The only TLS implementation in the workspace (no OpenSSL anywhere). Wraps | Function | Notes | |---|---| -| `load_system_roots()` | Returns `RootCertStore` from webpki-roots | +| `load_system_roots()` | Returns `RootCertStore` from the bundled `webpki-roots` Mozilla set (not the OS store) | | `load_pem_roots(pem)` | Parses PEM, adds each cert to `RootCertStore`. **Empty input is an error** (returns `PemParse`) | | `load_pem_certs(pem)` | Returns `Vec` from PEM. Does not fail on empty input (unlike `load_pem_roots`) | @@ -97,7 +97,7 @@ The only TLS implementation in the workspace (no OpenSSL anywhere). Wraps ### Client config construction -The ordinary system-root configurations are process-shared through `OnceLock`: +The ordinary bundled-root configurations are process-shared through `OnceLock`: `default_client_config()` and `default_h2_client_config()` return cloned `Arc`s to immutable verified configurations. Feature-gated insecure and H2 variants use separate caches. Custom CA, mTLS, ALPN, and caller-provided @@ -145,14 +145,16 @@ Both `tls_connect` and `tls_accept` use `tokio-rustls`: | Consumer | Usage | |---|---| -| `eggress-outbound` (`executor.rs`) | Upstream `+tls` hops: builds `TlsClientConfigBuilder` with system roots or custom CA, calls `tls_connect` on the box stream | +| `eggress-outbound` (`executor.rs`) | Upstream `+tls` hops: builds `TlsClientConfigBuilder` with bundled Mozilla roots or a custom CA, calls `tls_connect` on the box stream | | `eggress-runtime` (`supervisor/connection.rs`) | Listener TLS: prepares one `Arc` per listener generation, then `wrap_tls_server()` only calls `tls_accept` on inbound streams (shared by standard/transparent/Unix paths) | -| `eggress-protocol-trojan` (`tcp.rs`) | Trojan client: builds `TlsClientConfigBuilder` with system roots, then performs the handshake directly via `tokio_rustls::TlsConnector` (`tcp.rs:267`; does not call `tls_connect`) | +| `eggress-protocol-trojan` (`tcp.rs`) | Trojan client: builds `TlsClientConfigBuilder` with bundled Mozilla roots, then performs the handshake directly via `tokio_rustls::TlsConnector` (`tcp.rs:267`; does not call `tls_connect`) | | `eggress-protocol-reverse` (`tls.rs`, `server.rs`, `client.rs`) | Native reverse control TLS/mTLS: server builds once via `TlsServerConfigBuilder` (+ optional client CA/require), client builds once via `TlsClientConfigBuilder` (+ optional client cert/key) and reuses `Arc` across reconnects; `tls_accept`/`tls_connect` wrap control TCP before reverse framing | ## Security notes -- **Insecure mode is dual-gated.** `with_insecure()` is only available under `#[cfg(any(test, feature = "insecure-tls"))]`. If the feature is not enabled, `build()` returns `TlsError::Handshake("insecure TLS requires the insecure-tls feature")`. This prevents accidental use in release builds. +- **Root source is bundled, not OS.** Outbound verification uses the Mozilla root set compiled in through `webpki-roots`. There is no operating-system-store backend, so a CA installed locally is not trusted automatically; the set moves only with the dependency version. Custom CA PEMs replace the set (`with_custom_ca_pem`) and stay scoped to the builder that supplied them. +- **Insecure mode is dual-gated but compiled into shipped CLI builds.** `with_insecure()` is only available under `#[cfg(any(test, feature = "insecure-tls"))]`, and without the feature `build()` returns `TlsError::Handshake("insecure TLS requires the insecure-tls feature")`. It is *not* test-only in practice: `eggress-cli` and `eggress-runtime` enable `insecure-tls` unconditionally, so a per-hop `?insecure` in a URI is reachable from configuration and executes. The gate protects downstream embedders that never enable the feature, not the shipped binaries. +- **Insecure selection is announced once.** `eggress-config` warns at compile time — one event per upstream, naming the upstream id and the affected hop indexes and protocols, never endpoints, credentials, or the source URI — before any chain executes. No build, root-load, or handshake error falls back to insecure verification, and `tls_override` plus a per-hop `insecure=true` fails closed. - **Empty PEM is an error.** `load_pem_roots(b"")` returns `PemParse("no certificates found in PEM root material")`. This prevents silently trusting everything when CA material is misconfigured. - **Client auth defaults to none; mTLS is opt-in.** See above for the explicit builders. - **PKCS#8 only.** `load_private_key_pem` uses `PrivatePkcs8KeyDer::from_pem_slice`. Other key formats (RSA, EC) are not supported. diff --git a/architecture/udp.md b/architecture/udp.md index 0f97924a..3f1f6a28 100644 --- a/architecture/udp.md +++ b/architecture/udp.md @@ -15,7 +15,7 @@ UDP association management, relay, upstream forwarding, and standalone relay mod | `standalone.rs` | `standalone_udp_relay`: pproxy-compatible standalone UDP relay | | `standalone_shadowsocks.rs` | `shadowsocks_standalone_udp_relay`: standalone AEAD-encrypted UDP relay (feature-gated) | | `flow.rs` | `UdpFlowKey`, `UdpFlowKind`, `TargetFlowEntry`, `ClientFlowState`; per-target flow management | -| `direct.rs` | `UdpTargetFlow`: connected UDP socket per target for direct forwarding | +| `direct.rs` | `UdpTargetFlow`: connected UDP socket per target for direct forwarding; `resolve_target` / `select_resolved_addr` apply `allow_private_egress` to the answers of the single lookup | | `hop.rs` | `UdpHopStack`, `UdpHop`: transport-neutral encode/decode for nested datagrams | | `composed.rs` | `open_composed_udp_upstream`: multi-hop SOCKS5+Shadowsocks composition | | `upstream_socks5.rs` | `open_socks5_udp_upstream`: TCP control + SOCKS5 handshake + UDP ASSOCIATE client | @@ -57,9 +57,10 @@ UDP association management, relay, upstream forwarding, and standalone relay mod `handle_client_datagram` per-packet: 1. `decode_packet()` (SOCKS5 UDP codec + size check). -2. `validate_standalone_target()` (security gate). +2. `validate_standalone_target()` (literal-target security gate). 3. `routing.route(&RouteRequest { transport: TransportKind::Udp, ... })`. -4. `SelectedRoute::Direct`: create/reuse `UdpTargetFlow`, send. +4. `SelectedRoute::Direct`: create/reuse `UdpTargetFlow` (post-DNS policy applies + to domain targets here), send. 5. `SelectedRoute::Upstream`: classify via `udp_capability(&chain)`: - `SupportedSocks5`: create/reuse `Socks5UdpTargetFlow`. - `SupportedShadowsocks` (feature-gated): create/reuse `ShadowsocksUdpTargetFlow`. @@ -146,7 +147,30 @@ First valid packet pins `SocketAddr`; mismatches return `ClientAddressMismatch`. ### Target Validation (`security.rs`) -`validate_standalone_target(target, allow_private_egress)` rejects: multicast, broadcast, unspecified, port zero, loopback (when !allow_private_egress), RFC 1918/link-local/unique-local IPv6 (when !allow_private_egress). IPv4-mapped IPv6 checked via `to_ipv4_mapped()`. +`validate_standalone_target(target, allow_private_egress)` rejects: multicast, +broadcast, unspecified, and port zero always, and loopback plus any +private/reserved address when `!allow_private_egress`. Classification is the +shared `eggress_core::connector::is_reserved_or_private_ip` (RFC 1918, link-local, +CGNAT, documentation/benchmarking, IPv4-mapped forms, unique-local IPv6, NAT64, +6to4, Teredo, ORCHID, and the other special-purpose ranges listed there), so the +UDP gate cannot drift from the TCP DNS-rebinding gate. + +A domain target carries no address at validation time, so the policy is enforced +post-DNS by `direct::resolve_target(target, allow_private_egress)`: + +1. one `tokio::net::lookup_host` call collects **all** answers (no second + lookup); +2. with `allow_private_egress` the first answer is used unchanged (pproxy + compatibility); +3. otherwise every answer is filtered through `is_reserved_or_private_ip` and + the first permitted address is connected; +4. if no answer is permitted, `UdpError::PrivateEgressBlocked` is returned before + a socket is connected, and the call site records the dropped/rejected metric. + +`UdpTargetFlow::new` takes the same `allow_private_egress` flag; the standalone +SOCKS5, SOCKS5 UDP ASSOCIATE, and standalone Shadowsocks relays all pass their +configured value, so a private-resolving domain can no longer bypass the +literal-target check. `validate_datagram_size(size, max_size)` is a standalone helper; `decode_packet()` enforces size limit at codec level. @@ -217,11 +241,13 @@ Bridged via `MetricsRegistry::set_udp_metrics()` (`eggress-metrics/src/udp.rs`); ### Unit Tests (210, `cargo test -p eggress-udp --lib`) -`assoc.rs`: create, close, idempotency, touch, pin. `registry.rs`: create/get/remove, limits, close_all, slot reuse. `relay.rs`: echo, pin reject, route reject, metrics, cancel, idle timeout, flow create/reuse/eviction, registry cleanup, double-close, composed/Shadowsocks upstream. `standalone.rs`+`standalone_shadowsocks.rs`: echo, reject, metrics, flow reuse, limits, timeout, malformed, decode error, wrong password. `flow.rs`: address equivalence (IPv4/v6/domain/mapped), endpoint resolution. `direct.rs`: echo, metrics, encode format. `hop.rs`: nested encode/decode, non-UDP rejection. `codec.rs`: size limits. `security.rs`: all validation paths. `udp_capability.rs`: all chain combinations. `upstream_socks5.rs`: wire format, credential limits, error labels. `metrics.rs`: all counters. +`assoc.rs`: create, close, idempotency, touch, pin. `registry.rs`: create/get/remove, limits, close_all, slot reuse. `relay.rs`: echo, pin reject, route reject, metrics, cancel, idle timeout, flow create/reuse/eviction, registry cleanup, double-close, composed/Shadowsocks upstream, private-domain drop and permissive allow for the direct path. `standalone.rs`+`standalone_shadowsocks.rs`: echo, reject, metrics, flow reuse, limits, timeout, malformed, decode error, wrong password, private-domain drop with `allow_private_egress = false`. `flow.rs`: address equivalence (IPv4/v6/domain/mapped), endpoint resolution. `direct.rs`: echo, metrics, encode format, post-DNS filtering (`select_resolved_addr` mixed/invalid answers, private-domain drop, permissive allow, public resolution under a restrictive policy). `hop.rs`: nested encode/decode, non-UDP rejection. `codec.rs`: size limits. `security.rs`: all validation paths including CGNAT/NAT64/6to4/Teredo literals. `udp_capability.rs`: all chain combinations. `upstream_socks5.rs`: wire format, credential limits, error labels. `metrics.rs`: all counters. ### Crate Integration Tests (`crates/eggress-udp/tests/`) -`udp_integration.rs`, `socks5_upstream.rs`, `standalone_udp.rs`. +`udp_integration.rs`, `socks5_upstream.rs`, `standalone_udp.rs` (including +private-domain drop with `allow_private_egress = false` and the permissive +default). ### Runtime Tests (`crates/eggress-runtime/tests/`) @@ -236,6 +262,7 @@ Bridged via `MetricsRegistry::set_udp_metrics()` (`eggress-metrics/src/udp.rs`); 5. **Standalone has no client pinning**: any client address can send to any target. 6. **Flow key includes upstream_id**: different upstreams for same target get separate flows. 7. **SOCKS5 control keepalive** reads 1 byte with 300s timeout; upstream close tears down flow. +8. **Domain targets are enforced post-DNS**: `validate_standalone_target` can only judge literal shapes, so the private-egress decision for a domain happens in `direct::resolve_target` from the answers of the one `lookup_host` call. Do not add a second resolution or filter only the first answer. 8. **`max_standalone_flows = 0`** falls back to `max_associations_global`. 9. **Feature-gated Shadowsocks**: `standalone_shadowsocks.rs`, `UdpHop::Shadowsocks`, `ShadowsocksUdpTargetFlow` behind `#[cfg(feature = "shadowsocks")]`. 10. **`touch()` after pin check**: decode error or security reject after successful pin does NOT extend lifetime. diff --git a/crates/eggress-admin/src/client.rs b/crates/eggress-admin/src/client.rs index 70571e74..134699e6 100644 --- a/crates/eggress-admin/src/client.rs +++ b/crates/eggress-admin/src/client.rs @@ -389,6 +389,7 @@ mod tests { reverse_registry: Arc::new(crate::reverse::ReverseRegistry::new()), metrics_enabled: true, auth: None, + allowed_hosts: eggress_config::compile::derive_allowed_hosts("127.0.0.1:9090"), }; let cancel = tokio_util::sync::CancellationToken::new(); let server = crate::server::AdminServer::new("127.0.0.1:0", cancel.clone()) diff --git a/crates/eggress-admin/src/lib.rs b/crates/eggress-admin/src/lib.rs index f1cc5eae..14ba5171 100644 --- a/crates/eggress-admin/src/lib.rs +++ b/crates/eggress-admin/src/lib.rs @@ -71,6 +71,7 @@ mod tests { reverse_registry: Arc::new(ReverseRegistry::new()), metrics_enabled: true, auth: None, + allowed_hosts: eggress_config::compile::derive_allowed_hosts("127.0.0.1:9090"), } } @@ -98,6 +99,7 @@ mod tests { reverse_registry: Arc::new(ReverseRegistry::new()), metrics_enabled: true, auth: None, + allowed_hosts: eggress_config::compile::derive_allowed_hosts("127.0.0.1:9090"), } } @@ -496,4 +498,276 @@ mod tests { assert_eq!(status, 503); assert_eq!(body, "not ready"); } + + // === Host / Origin / Content-Type validation === + + async fn http_raw(addr: &str, request: &str) -> (u16, String) { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + tokio::io::AsyncWriteExt::write_all(&mut stream, request.as_bytes()) + .await + .unwrap(); + tokio::io::AsyncWriteExt::flush(&mut stream).await.unwrap(); + + let mut response = Vec::new(); + loop { + let mut buf = [0u8; 4096]; + match tokio::io::AsyncReadExt::read(&mut stream, &mut buf).await { + Ok(0) => break, + Ok(n) => response.extend_from_slice(&buf[..n]), + Err(_) => break, + } + } + let response = String::from_utf8_lossy(&response); + let status_line = response.lines().next().unwrap_or(""); + let status = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string(); + (status, body) + } + + async fn get_with_host(addr: &str, path: &str, host: &str) -> (u16, String) { + http_raw( + addr, + &format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"), + ) + .await + } + + const ROUTE_EXPLAIN_BODY: &str = + r#"{"target":"example.com:443","listener":"l","protocol":"http"}"#; + + async fn post_route_explain( + addr: &str, + host: &str, + extra_headers: &str, + body: &str, + ) -> (u16, String) { + let mut request = format!("POST /-/route-explain HTTP/1.1\r\nHost: {host}\r\n"); + request.push_str(extra_headers); + request.push_str(&format!( + "Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + )); + http_raw(addr, &request).await + } + + #[tokio::test] + async fn default_loopback_hosts_are_accepted() { + let state = test_state(); + let addr = start_server(state).await; + // `http_get` already sends `Host: 127.0.0.1:`; `localhost` and a + // bracketed IPv6 with port must also pass with no configuration. + assert_eq!(http_get(&addr, "/-/health").await.0, 200); + assert_eq!( + get_with_host(&addr, "/-/health", "localhost:9090").await.0, + 200 + ); + assert_eq!( + get_with_host( + &addr, + "/-/health", + &format!("[::1]:{}", addr.rsplit(':').next().unwrap()) + ) + .await + .0, + 200 + ); + } + + #[tokio::test] + async fn dns_rebinding_host_is_rejected() { + let state = test_state(); + let addr = start_server(state).await; + let (status, body) = get_with_host(&addr, "/-/status", "attacker.example").await; + assert_eq!(status, 400); + assert_eq!(body, "bad request"); + // The rejected value and internal topology must not be echoed. + assert!(!body.contains("attacker")); + assert!(!body.contains("generation")); + } + + #[tokio::test] + async fn forwarded_host_header_does_not_widen_the_allowlist() { + let state = test_state(); + let addr = start_server(state).await; + let request = concat!( + "GET /-/status HTTP/1.1\r\n", + "Host: attacker.example\r\n", + "X-Forwarded-Host: 127.0.0.1\r\n", + "Connection: close\r\n\r\n", + ); + let (status, body) = http_raw(&addr, request).await; + assert_eq!(status, 400); + assert_eq!(body, "bad request"); + } + + #[tokio::test] + async fn missing_or_unparseable_host_is_rejected() { + let state = test_state(); + let addr = start_server(state).await; + // HTTP/1.1 without a Host header. + let (status, body) = + http_raw(&addr, "GET /-/health HTTP/1.1\r\nConnection: close\r\n\r\n").await; + assert_eq!(status, 400); + assert_eq!(body, "bad request"); + + // A wildcard is not a host name. + let (status, _) = get_with_host(&addr, "/-/health", "*").await; + assert_eq!(status, 400); + } + + #[tokio::test] + async fn host_rejection_precedes_authentication() { + let mut state = test_state(); + state.auth = Some(eggress_config::compile::AdminAuthConfig { + bearer_token: Some("secret-token".to_string()), + basic_username: None, + basic_password: None, + }); + let addr = start_server(state).await; + // A bad Host fails with 400 before auth would produce a 401: the + // validation must not depend on possessing a credential. + let (status, body) = get_with_host(&addr, "/-/status", "attacker.example").await; + assert_eq!(status, 400); + assert_eq!(body, "bad request"); + + let (status, _) = get_with_host(&addr, "/-/status", "localhost:9090").await; + assert_eq!(status, 401); + } + + #[tokio::test] + async fn configured_allowed_host_is_accepted() { + let mut state = test_state(); + state.allowed_hosts = vec!["admin.example".to_string()]; + let addr = start_server(state).await; + assert_eq!( + get_with_host(&addr, "/-/health", "admin.example:9090") + .await + .0, + 200 + ); + // With an explicit allowlist the bind-derived defaults are replaced. + assert_eq!( + get_with_host(&addr, "/-/health", "127.0.0.1:9090").await.0, + 400 + ); + } + + #[tokio::test] + async fn empty_allowed_hosts_falls_back_to_the_bound_address() { + let mut state = test_state(); + state.allowed_hosts = Vec::new(); + let addr = start_server(state).await; + // The server derives the loopback defaults from its bound address. + assert_eq!(http_get(&addr, "/-/health").await.0, 200); + assert_eq!( + get_with_host(&addr, "/-/health", "localhost:9090").await.0, + 200 + ); + } + + #[tokio::test] + async fn route_explain_accepts_json_content_type() { + let state = test_state(); + let addr = start_server(state).await; + let (status, body) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: application/json\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 200, "body: {body}"); + let json: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(json["target"], "example.com:443"); + + // Media type matching is case-insensitive and tolerates parameters. + let (status, _) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: Application/JSON; charset=utf-8\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 200); + } + + #[tokio::test] + async fn route_explain_requires_json_content_type() { + let state = test_state(); + let addr = start_server(state).await; + + let (status, body) = + post_route_explain(&addr, "127.0.0.1:9090", "", ROUTE_EXPLAIN_BODY).await; + assert_eq!(status, 415, "missing content type must be rejected"); + assert!(body.contains("application/json")); + + let (status, _) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: text/plain\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 415); + } + + #[tokio::test] + async fn route_explain_rejects_cross_origin_post() { + let state = test_state(); + let addr = start_server(state).await; + let (status, body) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: application/json\r\nOrigin: https://attacker.example\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 403); + assert_eq!(body, r#"{"error":"origin not allowed"}"#); + assert!(!body.contains("attacker")); + } + + #[tokio::test] + async fn route_explain_accepts_same_origin_post() { + let state = test_state(); + let addr = start_server(state).await; + let (status, _) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: application/json\r\nOrigin: http://localhost:9090\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 200); + } + + #[tokio::test] + async fn route_explain_rejects_null_origin_unless_allowed() { + let state = test_state(); + let addr = start_server(state).await; + let (status, _) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: application/json\r\nOrigin: null\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 403); + + let mut allowed = test_state(); + allowed.allowed_hosts.push("null".to_string()); + let addr = start_server(allowed).await; + let (status, _) = post_route_explain( + &addr, + "127.0.0.1:9090", + "Content-Type: application/json\r\nOrigin: null\r\n", + ROUTE_EXPLAIN_BODY, + ) + .await; + assert_eq!(status, 200); + } } diff --git a/crates/eggress-admin/src/routes.rs b/crates/eggress-admin/src/routes.rs index b5e440e8..d18d89f6 100644 --- a/crates/eggress-admin/src/routes.rs +++ b/crates/eggress-admin/src/routes.rs @@ -4,8 +4,8 @@ use eggress_core::capability::classify_upstream_chain; use crate::pac::generate_pac; use crate::server::{ - build_json_response, build_not_found, build_response, build_text_response, AdminResponse, - AdminState, + build_json_response, build_not_found, build_response, build_text_response, + request_content_type_is_json, request_origin_allowed, AdminResponse, AdminState, }; use crate::static_content::serve_static; @@ -234,6 +234,22 @@ pub async fn handle_request( if method != http::Method::POST { return build_text_response(405, "method not allowed"); } + // Dry-run explanations reveal routing topology, so a cross-origin + // page must not be able to POST here. Both checks run before the + // body is read and before any routing state is touched. + if !request_content_type_is_json(&req) { + return build_json_response( + 415, + serde_json::json!({"error": "expected content-type: application/json"}) + .to_string(), + ); + } + if !request_origin_allowed(&req, &state.allowed_hosts) { + return build_json_response( + 403, + serde_json::json!({"error": "origin not allowed"}).to_string(), + ); + } let snap = state.snapshot(); let router = &snap.router; let body_bytes = match collect_limited(req.into_body(), MAX_ADMIN_BODY).await { diff --git a/crates/eggress-admin/src/server.rs b/crates/eggress-admin/src/server.rs index 9518fc10..74de90ba 100644 --- a/crates/eggress-admin/src/server.rs +++ b/crates/eggress-admin/src/server.rs @@ -18,6 +18,8 @@ use crate::routes::handle_request; use crate::AdminError; use eggress_config::compile::{PacConfig, StaticRoute}; +use eggress_config::compile::admin_hosts::{derive_allowed_hosts, normalize_host_entry}; + /// Upper bound on concurrently served admin connections. The admin surface is /// local tooling; an unbounded accept loop would otherwise turn the admin port /// into a trivially cheap DoS target. @@ -156,15 +158,99 @@ fn authorization_payload<'a>( }) } +/// True when the host is a normalized entry of the allowlist. +/// +/// Both sides are normalized defensively so a hand-built [`AdminState`] that +/// stores `Admin.Example:9090` still matches `admin.example`. +fn allowed_host_contains(allowed_hosts: &[String], host: &str) -> bool { + allowed_hosts + .iter() + .any(|entry| normalize_host_entry(entry).as_deref() == Some(host)) +} + +/// Validate the request `Host` header against the admin allowlist. +/// +/// Only the actual `Host` header counts — `X-Forwarded-Host` and friends are +/// ignored, so a client cannot widen the allowlist with a header it controls. +/// A missing, unparseable, or unlisted host fails closed. The rejected value is +/// never echoed into the response. +pub(crate) fn host_allowed( + req: &http::Request, + allowed_hosts: &[String], +) -> bool { + let Some(value) = req.headers().get(http::header::HOST) else { + return false; + }; + let Ok(raw) = value.to_str() else { + return false; + }; + normalize_host_entry(raw).is_some_and(|host| allowed_host_contains(allowed_hosts, &host)) +} + +/// True when the request carries no `Origin`, or carries an `Origin` whose +/// host is allowlisted. +/// +/// `Origin: null` (a sandboxed or `file://` document) is rejected unless the +/// operator lists the literal entry `null` in `admin.allowed_hosts`. +pub(crate) fn request_origin_allowed( + req: &http::Request, + allowed_hosts: &[String], +) -> bool { + match req.headers().get(http::header::ORIGIN) { + None => true, + Some(value) => origin_value_allowed(value, allowed_hosts), + } +} + +fn origin_value_allowed(value: &http::HeaderValue, allowed_hosts: &[String]) -> bool { + let Ok(raw) = value.to_str() else { + return false; + }; + let raw = raw.trim(); + if raw.eq_ignore_ascii_case("null") { + return allowed_host_contains(allowed_hosts, "null"); + } + let Some((scheme, rest)) = raw.split_once("://") else { + return false; + }; + if !(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) { + return false; + } + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + // An origin never carries userinfo; reject rather than parse it away. + if authority.is_empty() || authority.contains('@') { + return false; + } + normalize_host_entry(authority).is_some_and(|host| allowed_host_contains(allowed_hosts, &host)) +} + +/// True when a request body is declared as JSON. +/// +/// The media type is compared case-insensitively and parameters (for example +/// `; charset=utf-8`) are ignored. +pub(crate) fn request_content_type_is_json(req: &http::Request) -> bool { + req.headers() + .get(http::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value + .split(';') + .next() + .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json")) + }) +} + impl AdminServer { pub async fn new(bind: &str, cancel: CancellationToken) -> Result { let listener = TcpListener::bind(bind).await?; if let Ok(addr) = listener.local_addr() { if !addr.ip().is_loopback() { tracing::warn!( - "admin listener bound to non-loopback address {addr}: \ - status, metrics, and topology are exposed to the network; \ - prefer a loopback bind or configure admin auth" + "admin listener bound to non-loopback address {addr} over plaintext \ + HTTP: status, metrics, and topology are exposed to the network and \ + Basic/Bearer credentials travel unprotected; prefer a loopback bind, \ + a VPN/SSH tunnel, or a TLS-terminating reverse proxy (set \ + [admin] allowed_hosts to the proxy host name)" ); } } @@ -175,7 +261,20 @@ impl AdminServer { self.listener.local_addr() } - pub async fn run(self, state: AdminState) -> Result<(), AdminError> { + pub async fn run(self, mut state: AdminState) -> Result<(), AdminError> { + // `admin.bind` is not hot-reloaded, so the effective allowlist is + // fixed for the lifetime of this server. A state built without an + // explicit list derives one from the address that actually bound, + // which keeps loopback clients working without configuration while + // still failing closed for a DNS rebinding `Host`. + if state.allowed_hosts.is_empty() { + state.allowed_hosts = match self.listener.local_addr() { + Ok(addr) => derive_allowed_hosts(&addr.to_string()), + Err(_) => vec!["localhost".to_string()], + }; + } + let allowed_hosts: Arc<[String]> = Arc::from(state.allowed_hosts.as_slice()); + let permits = Arc::new(Semaphore::new(MAX_ADMIN_CONNECTIONS)); let auth_failures = Arc::new(AuthFailureLimiter::default()); loop { @@ -189,12 +288,30 @@ impl AdminServer { }; let state = state.clone(); let auth_failures = auth_failures.clone(); + let allowed_hosts = Arc::clone(&allowed_hosts); tokio::spawn(async move { let _permit = permit; let service = service_fn(move |req| { let state = state.clone(); let auth_failures = auth_failures.clone(); + let allowed_hosts = Arc::clone(&allowed_hosts); async move { + // Host validation runs before auth and before + // any body is read: a DNS-rebinding request is + // rejected regardless of credentials, and the + // rejected value is never echoed back. + if !host_allowed(&req, &allowed_hosts) { + // A rejected Host also ends the + // connection: keep-alive would invite a + // probing client to retry on the same + // socket. + let mut response = build_text_response(400, "bad request"); + response.headers_mut().insert( + http::header::CONNECTION, + http::HeaderValue::from_static("close"), + ); + return Ok::<_, std::convert::Infallible>(response); + } let response = match state.auth.as_ref() { Some(auth) if !authorized(&req, auth) => { // Record-then-check: the Nth failure that @@ -313,6 +430,10 @@ pub struct AdminState { /// Whether the `/metrics` endpoint is enabled. pub metrics_enabled: bool, pub auth: Option, + /// `Host` header values accepted by this server, normalized (lowercase, + /// no brackets or port). Empty means "derive from the bound address when + /// the server starts". + pub allowed_hosts: Vec, } #[cfg(test)] diff --git a/crates/eggress-cli/Cargo.toml b/crates/eggress-cli/Cargo.toml index c6dfff9b..42cbc919 100644 --- a/crates/eggress-cli/Cargo.toml +++ b/crates/eggress-cli/Cargo.toml @@ -33,6 +33,12 @@ quic = [ insecure-quic = ["eggress-runtime/insecure-quic", "eggress-transport-quic/insecure-quic"] pproxy-compat = ["dep:eggress-pproxy-compat"] ssh = ["eggress-runtime/ssh", "eggress-pproxy-compat/ssh"] +# Non-default, tests/docs only: enables the offline `eggress update` fixtures +# (`EGRESS_UPDATE_BASE_URL` redirection, `file://` asset URLs, and the +# `EGRESS_UPDATE_CURL` tool override). Release builds must never enable it: +# production updater trust decisions assume every non-HTTPS URL and every +# non-system `curl` is rejected. +update-fixtures = [] [[bin]] name = "eggress" @@ -67,6 +73,8 @@ tokio.workspace = true tokio-util.workspace = true serde_json.workspace = true serde.workspace = true +sha2 = "0.10" +tempfile.workspace = true http.workspace = true [dev-dependencies] @@ -86,7 +94,6 @@ rand.workspace = true rcgen.workspace = true rustls.workspace = true tar = { version = "0.4", default-features = false } -tempfile.workspace = true tokio-rustls.workspace = true toml.workspace = true zip = { version = "6", default-features = false, features = ["deflate-flate2"] } diff --git a/crates/eggress-cli/src/cli.rs b/crates/eggress-cli/src/cli.rs index 25ddb3d6..66521779 100644 --- a/crates/eggress-cli/src/cli.rs +++ b/crates/eggress-cli/src/cli.rs @@ -254,7 +254,8 @@ pub enum SystemProxyAction { #[cfg(feature = "operations")] #[derive(Parser, Debug)] pub struct SystemProxyInspect { - /// Output as JSON + /// Output as JSON. Settings are emitted redacted only: credentials in + /// proxy URIs (`user:pass@`) never appear in this output. #[arg(long)] pub json: bool, } diff --git a/crates/eggress-cli/src/commands/pproxy.rs b/crates/eggress-cli/src/commands/pproxy.rs index ffa2daf4..0a98eb4f 100644 --- a/crates/eggress-cli/src/commands/pproxy.rs +++ b/crates/eggress-cli/src/commands/pproxy.rs @@ -52,7 +52,10 @@ fn handle_pproxy_translate(args: &PproxyTranslate) -> i32 { if args.annotate { println!("# Generated by eggress pproxy translate"); - println!("# pproxy arguments: {}", args.args.join(" ")); + println!( + "# pproxy arguments: {}", + eggress_pproxy_compat::redact_argv_for_annotation(&args.args) + ); if !output.warnings().is_empty() || !output.unsupported().is_empty() { println!("#"); for w in &output.warnings() { diff --git a/crates/eggress-cli/src/pproxy_exec.rs b/crates/eggress-cli/src/pproxy_exec.rs index 81ea9bcc..3fdd5c05 100644 --- a/crates/eggress-cli/src/pproxy_exec.rs +++ b/crates/eggress-cli/src/pproxy_exec.rs @@ -188,6 +188,23 @@ pub fn compile(gated: GatedRun) -> Result { }) } +/// Startup advisory for the pproxy-compatible auth-reuse cache, if relevant. +/// +/// The cache is source-IP keyed and process-global, so it only becomes +/// observable when a translated listener carries `[listeners.auth]`. Gating on +/// the compiled config (not on raw `-l` strings) keeps the warning out of +/// unauthenticated runs and out of translation-only subcommands. +fn auth_reuse_advisory_for( + args: &eggress_pproxy_compat::PproxyArgs, + rt_config: &eggress_config::compile::RuntimeConfig, +) -> Option { + rt_config + .listeners + .iter() + .any(|listener| listener.auth.is_some()) + .then(|| args.auth_reuse_advisory()) +} + /// Execute a prepared compatibility run: warnings, `--test` diagnostics, /// daemon transition, then the supervised service. /// @@ -224,6 +241,14 @@ pub fn execute(prepared: PreparedRun, diag_prefix: &str) -> i32 { return run_upstream_test(&rt_config, Some(&target), timeout, false); } + // One startup advisory for the pproxy-compatible auth-reuse cache. It is + // gated on translated `[listeners.auth]` (never on raw argv) and emitted + // before daemonization so the operator sees it; it is never per + // connection and never contains a listener URI or credential. + if let Some(advisory) = auth_reuse_advisory_for(&pproxy_args, &rt_config) { + eprintln!("{diag_prefix}warning: {advisory}"); + } + #[cfg(feature = "pproxy-daemon")] if let Err(error) = crate::maybe_daemonize(pproxy_args.daemon) { eprintln!("{diag_prefix}error: {error}"); @@ -399,4 +424,30 @@ mod tests { assert!(joined.contains("tls: enabled")); assert!(joined.contains("pac: enabled")); } + + fn prepared_run(args: &[&str]) -> PreparedRun { + match prepare(&argv(args)).expect("supported args must prepare") { + PreparedAction::Run(gated) => compile(*gated).expect("translated TOML must compile"), + _ => panic!("expected a prepared run"), + } + } + + #[test] + fn auth_reuse_advisory_fires_for_credentialed_listener_only() { + let prepared = prepared_run(&["-l", "http://user:pass@127.0.0.1:0"]); + let advisory = auth_reuse_advisory_for(&prepared.args, &prepared.rt_config) + .expect("credentialed listener must produce the reuse advisory"); + assert!(advisory.contains("30 days"), "{advisory}"); + assert!(advisory.contains("source IP"), "{advisory}"); + assert!(!advisory.contains("user"), "{advisory}"); + assert!(!advisory.contains("pass"), "{advisory}"); + assert!(!advisory.contains("127.0.0.1"), "{advisory}"); + + // No listener credentials: the cache is inert and must not warn. + let prepared = prepared_run(&["-l", "http://127.0.0.1:0", "-r", "socks5://127.0.0.1:1080"]); + assert!( + auth_reuse_advisory_for(&prepared.args, &prepared.rt_config).is_none(), + "unauthenticated listeners must not warn about auth reuse" + ); + } } diff --git a/crates/eggress-cli/src/update/download.rs b/crates/eggress-cli/src/update/download.rs index e32b5c9b..f9620383 100644 --- a/crates/eggress-cli/src/update/download.rs +++ b/crates/eggress-cli/src/update/download.rs @@ -1,19 +1,35 @@ //! Bounded `curl` downloads for self-update. //! //! Like the bootstrap installer, the updater shells out to `curl` with -//! explicit discovery, timeouts, redirect following, and failure capture -//! instead of adding a heavyweight HTTP client dependency to `eggress-cli`. -//! Downloaded content is only ever treated as data (archives/checksums), and -//! nothing fetched here is shell-evaluated. +//! timeouts, redirect following, and failure capture instead of adding a +//! heavyweight HTTP client dependency to `eggress-cli`. Downloaded content is +//! only ever treated as data (archives/checksums), and nothing fetched here is +//! shell-evaluated. +//! +//! Trust boundaries: +//! +//! - `curl` is resolved only from fixed system locations +//! (`/usr/bin/curl`, `/bin/curl`, or `%SystemRoot%\System32\curl.exe`). The +//! updater never scans `PATH`, and it rejects a symlinked, non-regular, or +//! group/other-writable candidate. +//! - Every URL must be `https://`; `file://` is accepted only by test builds +//! or the non-default `update-fixtures` feature, never by a release build. +//! - Download outputs are created with `create_new` (owner-only, no symlink +//! following) inside the private staging directory, so a planted path can +//! only fail the update, never redirect the write. +use std::fs::{File, OpenOptions}; use std::path::{Path, PathBuf}; -use std::process::Command; +use std::process::{Command, Stdio}; /// Why a download failed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum DownloadError { - /// No `curl` executable is available on `PATH`. - MissingCurl, + /// No trustworthy `curl` executable exists at a fixed system location. + MissingCurl(String), + /// The staging output path already exists or is not a safe regular file + /// (for example a symlink planted at the archive path). + UnsafeDestination(String), /// The asset does not exist at this release (HTTP 404). NotFound(String), /// Any other transport failure with a captured detail. @@ -23,12 +39,14 @@ pub enum DownloadError { impl std::fmt::Display for DownloadError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - DownloadError::MissingCurl => write!( + DownloadError::MissingCurl(detail) => write!( f, - "curl is required for `eggress update` but was not found on PATH; \ - install curl or update with the bootstrap installer instead \ - (see docs/INSTALLATION.md)" + "curl is required for `eggress update` but no trusted executable was found \ + (looked only at {}; {detail}); install curl as a system package or update \ + with the bootstrap installer instead (see docs/INSTALLATION.md)", + trusted_locations_description() ), + DownloadError::UnsafeDestination(detail) => write!(f, "{detail}"), DownloadError::NotFound(url) => write!( f, "release asset not found: {url} (the release may predate prebuilt binaries for this target)" @@ -38,54 +56,152 @@ impl std::fmt::Display for DownloadError { } } -/// Locate `curl` on `PATH`. +/// Fixed system locations for the integrity-critical `curl` executable. +/// +/// `PATH` is deliberately absent: a writable or user-controlled `PATH` entry +/// must never be able to supply the binary that fetches release assets. +#[cfg(windows)] +fn trusted_curl_candidates() -> Vec { + let mut candidates = Vec::new(); + if let Some(root) = std::env::var_os("SystemRoot") { + candidates.push(PathBuf::from(root).join("System32").join("curl.exe")); + } + let fallback = PathBuf::from(r"C:\Windows\System32\curl.exe"); + if !candidates.contains(&fallback) { + candidates.push(fallback); + } + candidates +} + +#[cfg(not(windows))] +fn trusted_curl_candidates() -> Vec { + vec![PathBuf::from("/usr/bin/curl"), PathBuf::from("/bin/curl")] +} + +fn trusted_locations_description() -> &'static str { + #[cfg(windows)] + { + r"%SystemRoot%\System32\curl.exe" + } + #[cfg(not(windows))] + { + "/usr/bin/curl and /bin/curl" + } +} + +/// Test-only `curl` override (`EGRESS_UPDATE_CURL`). +/// +/// Compiled for unit tests and the non-default `update-fixtures` feature only, +/// so release builds cannot be pointed at an attacker-supplied executable. +#[cfg(any(test, feature = "update-fixtures"))] +fn fixture_curl_override() -> Option { + std::env::var_os("EGRESS_UPDATE_CURL").map(PathBuf::from) +} + +/// Whether `url` is an offline fixture URL. +/// +/// Release/default builds always answer `false`, which makes every +/// `file://` (and any other non-HTTPS) update URL fail closed. +#[cfg(any(test, feature = "update-fixtures"))] +fn is_fixture_url(url: &str) -> bool { + url.starts_with("file://") +} + +#[cfg(not(any(test, feature = "update-fixtures")))] +fn is_fixture_url(_url: &str) -> bool { + false +} + +/// Locate a trusted `curl` executable. +/// +/// Only fixed system locations are considered. A candidate that is missing, +/// symlinked, not a regular file, or writable by group/other is rejected with +/// its reason; if every candidate is rejected the update fails closed. pub fn find_curl() -> Result { - let path_var = std::env::var_os("PATH").unwrap_or_default(); - let exe = if cfg!(windows) { "curl.exe" } else { "curl" }; - for dir in std::env::split_paths(&path_var) { - if dir.as_os_str().is_empty() { - continue; + #[cfg(any(test, feature = "update-fixtures"))] + { + if let Some(path) = fixture_curl_override() { + return Ok(path); } - let candidate = dir.join(exe); - if candidate.is_file() { - return Ok(candidate); + } + let mut rejections = Vec::new(); + for candidate in trusted_curl_candidates() { + match validate_trusted_executable(&candidate) { + Ok(()) => return Ok(candidate), + Err(reason) => rejections.push(reason), } } - // `curl.exe` ships with modern Windows even when PATH lookup above - // misses it; let process spawning be the final arbiter there. - if cfg!(windows) { - return Ok(PathBuf::from(exe)); + Err(DownloadError::MissingCurl(rejections.join("; "))) +} + +/// Reject a tool path that is not an untampered regular file. +fn validate_trusted_executable(path: &Path) -> Result<(), String> { + let metadata = + std::fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + if metadata.file_type().is_symlink() { + return Err(format!( + "{}: symbolic links are not trusted", + path.display() + )); + } + if !metadata.is_file() { + return Err(format!("{}: not a regular file", path.display())); } - Err(DownloadError::MissingCurl) + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = metadata.permissions().mode(); + if mode & 0o022 != 0 { + return Err(format!( + "{}: writable by group or other (mode {:o})", + path.display(), + mode & 0o7777 + )); + } + } + Ok(()) } -/// Fetch a URL body as text (used for the small release-metadata JSON). -/// `file://` URLs are honored for fixture-based tests; anything else must -/// be `https://`. -pub fn curl_fetch_text(url: &str, user_agent: &str) -> Result { +/// Build the base `curl` invocation shared by metadata fetches and asset +/// downloads, including the HTTPS-only protocol policy. +fn curl_command( + url: &str, + user_agent: &str, + max_time_secs: &str, + github_accept: bool, +) -> Result { let curl = find_curl()?; let mut cmd = Command::new(curl); cmd.arg("-fsSL") .arg("--connect-timeout") .arg("15") .arg("--max-time") - .arg("60") - .arg("-H") - .arg("Accept: application/vnd.github+json") - .arg("-A") - .arg(user_agent); + .arg(max_time_secs); + if github_accept { + cmd.arg("-H").arg("Accept: application/vnd.github+json"); + } + cmd.arg("-A").arg(user_agent); if url.starts_with("https://") { cmd.arg("--proto").arg("=https").arg("--tlsv1.2"); - } else if !url.starts_with("file://") { + } else if !is_fixture_url(url) { return Err(DownloadError::Transport(format!( "refusing non-HTTPS update URL: {}", redact_url(url) ))); } cmd.arg(url); + Ok(cmd) +} + +/// Fetch a URL body as text (used for the small release-metadata JSON). +/// +/// `file://` URLs are honored only for fixtures; everything else must be +/// `https://`. +pub fn curl_fetch_text(url: &str, user_agent: &str) -> Result { + let mut cmd = curl_command(url, user_agent, "60", true)?; let output = cmd.output().map_err(|e| { if e.kind() == std::io::ErrorKind::NotFound { - DownloadError::MissingCurl + DownloadError::MissingCurl("the trusted curl disappeared before execution".to_string()) } else { DownloadError::Transport(format!("failed to run curl: {e}")) } @@ -102,32 +218,26 @@ pub fn curl_fetch_text(url: &str, user_agent: &str) -> Result Result<(), DownloadError> { - let curl = find_curl()?; - let mut cmd = Command::new(curl); - cmd.arg("-fsSL") - .arg("--connect-timeout") - .arg("15") - .arg("--max-time") - .arg("600") - .arg("-A") - .arg(user_agent); - if url.starts_with("https://") { - cmd.arg("--proto").arg("=https").arg("--tlsv1.2"); - } else if !url.starts_with("file://") { - return Err(DownloadError::Transport(format!( - "refusing non-HTTPS update URL: {}", - redact_url(url) - ))); - } - cmd.arg("-o").arg(dest).arg(url); - let output = cmd.output().map_err(|e| { + let mut cmd = curl_command(url, user_agent, "600", false)?; + let output_file = create_private_output(dest)?; + cmd.stdout(Stdio::from(output_file)).stderr(Stdio::piped()); + let child = cmd.spawn().map_err(|e| { if e.kind() == std::io::ErrorKind::NotFound { - DownloadError::MissingCurl + DownloadError::MissingCurl("the trusted curl disappeared before execution".to_string()) } else { DownloadError::Transport(format!("failed to run curl: {e}")) } })?; + // `wait_with_output` drains the piped stderr while the child runs; stdout + // is the already-open staging file, so no path is ever followed. + let output = child + .wait_with_output() + .map_err(|e| DownloadError::Transport(format!("failed to run curl: {e}")))?; if output.status.success() { return Ok(()); } @@ -138,6 +248,36 @@ pub fn curl_download(url: &str, dest: &Path, user_agent: &str) -> Result<(), Dow )) } +/// Create a download output path without following symlinks and without +/// overwriting an existing file. +/// +/// `create_new` maps to `O_CREAT|O_EXCL`, which fails (rather than following) +/// when the path is a symlink and refuses any pre-existing file, so a local +/// user cannot redirect the download or pre-seed its content. +fn create_private_output(dest: &Path) -> Result { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options.open(dest).map_err(|e| { + if e.kind() == std::io::ErrorKind::AlreadyExists { + DownloadError::UnsafeDestination(format!( + "refusing to reuse existing update staging path {}; another update \ + transaction or a planted path may own it", + dest.display() + )) + } else { + DownloadError::Transport(format!( + "cannot create update staging file {}: {e}", + dest.display() + )) + } + }) +} + fn classify_curl_failure(url: &str, code: Option, stderr: &[u8]) -> DownloadError { let detail = String::from_utf8_lossy(stderr); // `curl -f` exits 22 on HTTP errors; a 404 means the asset is absent @@ -176,6 +316,7 @@ mod tests { fn refuses_non_https_update_urls() { let dir = std::env::temp_dir(); let dest = dir.join("eggress-update-refused-test"); + let _ = std::fs::remove_file(&dest); let err = curl_download("http://example.com/eggress.tar.gz", &dest, "test").unwrap_err(); assert!( matches!(err, DownloadError::Transport(_)), @@ -195,4 +336,110 @@ mod tests { "https://github.com/eggstack/eggress/releases/latest" ); } + + #[test] + fn trusted_candidates_are_fixed_system_locations() { + let candidates = trusted_curl_candidates(); + assert!(!candidates.is_empty()); + for candidate in &candidates { + assert!( + candidate.is_absolute(), + "trusted curl candidates must be absolute: {}", + candidate.display() + ); + } + // The candidate set is a constant: it is not computed from `PATH`. + #[cfg(not(windows))] + assert_eq!( + candidates, + vec![PathBuf::from("/usr/bin/curl"), PathBuf::from("/bin/curl")] + ); + } + + #[test] + fn rejects_symlinked_or_writable_tools() { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let root = + std::env::temp_dir().join(format!("eggress-curl-trust-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + + let real = root.join("curl-real"); + std::fs::write(&real, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o755)).unwrap(); + validate_trusted_executable(&real).unwrap(); + + let link = root.join("curl-link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let err = validate_trusted_executable(&link).unwrap_err(); + assert!(err.contains("symbolic link"), "{err}"); + + let writable = root.join("curl-writable"); + std::fs::write(&writable, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&writable, std::fs::Permissions::from_mode(0o777)).unwrap(); + let err = validate_trusted_executable(&writable).unwrap_err(); + assert!(err.contains("group or other"), "{err}"); + + let dir_at_path = root.join("curl-dir"); + std::fs::create_dir_all(&dir_at_path).unwrap(); + let err = validate_trusted_executable(&dir_at_path).unwrap_err(); + assert!(err.contains("not a regular file"), "{err}"); + + let _ = std::fs::remove_dir_all(&root); + } + } + + #[test] + fn staging_outputs_are_created_new_and_owner_only() { + let root = std::env::temp_dir().join(format!("eggress-curl-output-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let dest = root.join("archive.tar.gz"); + + drop(create_private_output(&dest).unwrap()); + let err = create_private_output(&dest).unwrap_err(); + assert!( + matches!(err, DownloadError::UnsafeDestination(_)), + "an existing staging path must never be reused: {err:?}" + ); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&dest).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "staging files must be owner-only"); + } + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn pre_existing_symlink_at_archive_path_is_refused() { + let Ok(_) = find_curl() else { + return; // no trusted curl on this host; fail-closed covered above. + }; + #[cfg(unix)] + { + let root = + std::env::temp_dir().join(format!("eggress-curl-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let victim = root.join("victim"); + std::fs::write(&victim, b"do-not-touch").unwrap(); + let source = root.join("source.tar.gz"); + std::fs::write(&source, b"archive-bytes").unwrap(); + let dest = root.join("archive.tar.gz"); + std::os::unix::fs::symlink(&victim, &dest).unwrap(); + + let url = format!("file://{}", source.display()); + let err = curl_download(&url, &dest, "test").unwrap_err(); + assert!( + matches!(err, DownloadError::UnsafeDestination(_)), + "a symlinked archive path must fail closed: {err:?}" + ); + assert_eq!(std::fs::read(&victim).unwrap(), b"do-not-touch"); + let _ = std::fs::remove_dir_all(&root); + } + } } diff --git a/crates/eggress-cli/src/update/mod.rs b/crates/eggress-cli/src/update/mod.rs index dc56fbda..494cd3af 100644 --- a/crates/eggress-cli/src/update/mod.rs +++ b/crates/eggress-cli/src/update/mod.rs @@ -16,8 +16,14 @@ //! - a failed update leaves the prior installation usable; //! - normal operation never touches the network except for this explicit //! command; unit tests never depend on live GitHub availability -//! (`EGRESS_UPDATE_BASE_URL` + `file://` fixtures cover the flow -//! offline). +//! (`EGRESS_UPDATE_BASE_URL` + `file://` fixtures cover the flow offline, +//! compiled only for tests or the non-default `update-fixtures` feature); +//! - every update URL is HTTPS and every integrity decision is made +//! in-process; `curl` is resolved from fixed system locations and never +//! from `PATH`; +//! - staging is an unpredictable, owner-only directory created atomically, +//! downloads are `create_new`, and the archive is re-hashed immediately +//! before extraction. pub mod download; pub mod eggup; @@ -98,9 +104,10 @@ fn run_update() -> Result { let current = ReleaseVersion::current(); let target = detect_target().map_err(UpdateFailure::UnsupportedTarget)?; - // Test hook: redirect release discovery/downloads at `file://` fixtures - // without touching production URLs. - let base_override = std::env::var("EGRESS_UPDATE_BASE_URL").ok(); + // Offline fixture redirect. Only tests or the non-default + // `update-fixtures` feature can produce a value here; release builds + // ignore `EGRESS_UPDATE_BASE_URL` entirely. + let base_override = update_base_url_override(); let latest = discover_latest_release(&base_override)?; if current >= latest { @@ -126,27 +133,43 @@ fn run_update() -> Result { let (archive_url, checksum_url) = asset_urls(&download_base, target); let stage = staging_dir()?; - let archive_path = stage.join(target::archive_name(target)); - let checksum_path = stage.join(target::checksum_name(target)); + let archive_path = stage.path().join(target::archive_name(target)); + let checksum_path = stage.path().join(target::checksum_name(target)); let outcome = update_from_urls( &archive_url, &checksum_url, target, latest, - &stage, + stage.path(), &archive_path, &checksum_path, &installed_eggress, &installed_pproxy, ); - let _ = std::fs::remove_dir_all(&stage); + // Dropping the guard removes this transaction's private staging tree + // (its own path only; best-effort and never an unrelated path). + drop(stage); let outcome = outcome?; Ok(format!("updated eggress {current} -> {latest}{outcome}")) } +/// Offline fixture redirect for release discovery/downloads. +/// +/// Compiled away for release/default builds, which therefore never read +/// `EGRESS_UPDATE_BASE_URL` and cannot be pointed at a `file://` tree. +#[cfg(any(test, feature = "update-fixtures"))] +fn update_base_url_override() -> Option { + std::env::var("EGRESS_UPDATE_BASE_URL").ok() +} + +#[cfg(not(any(test, feature = "update-fixtures")))] +fn update_base_url_override() -> Option { + None +} + /// Download, verify, stage, and install one release. Factored out so /// fixture-based tests can drive the full flow offline. #[allow(clippy::too_many_arguments)] @@ -190,10 +213,27 @@ fn update_from_urls( installed_eggress.display() ))); } + // Re-hash immediately before extraction: the staging directory is + // private and create-new, but a replacement after the first verification + // must still fail closed instead of extracting unverified bytes. + verify_archive_before_extraction(archive_path, &sidecar)?; install_pair_via_eggup(archive_path, target, expected, install_dir, stage) .map_err(UpdateFailure::Failed) } +/// Last integrity gate before extraction. +/// +/// `verify_archive` already ran once after download; this second hash of the +/// exact archive file closes the verify/extract window, so a post-verification +/// replacement is rejected instead of extracted. +fn verify_archive_before_extraction(archive: &Path, sidecar: &str) -> Result<(), UpdateFailure> { + verify::verify_archive(archive, sidecar).map_err(|e| { + UpdateFailure::Failed(format!( + "{e} (the staged archive changed after checksum verification)" + )) + }) +} + /// Resolve the latest stable release version from GitHub (or fixtures). fn discover_latest_release( base_override: &Option, @@ -265,19 +305,32 @@ fn verify_sibling_identity(sibling: &Path, current: ReleaseVersion) -> Result<() Ok(()) } -fn staging_dir() -> Result { - let dir = std::env::temp_dir().join(format!("eggress-update-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir) - .map_err(|e| UpdateFailure::Failed(format!("cannot create staging directory: {e}")))?; - Ok(dir) +/// Create the private staging directory for one update transaction. +/// +/// `tempfile` creates the directory atomically under the default temp root +/// (so filesystem/installation semantics match the previous staging) with an +/// unpredictable name. The explicit owner-only mode matters: `tempfile`'s +/// platform default is the process umask (typically `0755`), which would let +/// another local user read the staged archive and race the output paths. +fn staging_dir() -> Result { + let mut builder = tempfile::Builder::new(); + builder.prefix("eggress-update-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + builder + .tempdir() + .map_err(|e| UpdateFailure::Failed(format!("cannot create private staging directory: {e}"))) } fn map_download_error(error: DownloadError) -> UpdateFailure { match error { - DownloadError::MissingCurl | DownloadError::NotFound(_) | DownloadError::Transport(_) => { - UpdateFailure::ExternalDependency(error.to_string()) - } + DownloadError::MissingCurl(_) + | DownloadError::NotFound(_) + | DownloadError::Transport(_) => UpdateFailure::ExternalDependency(error.to_string()), + DownloadError::UnsafeDestination(_) => UpdateFailure::Failed(error.to_string()), } } @@ -319,7 +372,7 @@ mod tests { /// End-to-end offline flow: fixture release metadata + archive + /// checksum over `file://`, installed into a temp pair directory. - /// Requires `curl`, `tar`, and a SHA-256 tool (present on CI runners). + /// Requires a trusted `curl` and `tar` (present on CI runners). #[test] fn offline_fixture_update_replaces_pair_atomically() { let Some(target) = target::detect_target().ok() else { @@ -328,15 +381,11 @@ mod tests { if target::is_windows_target(target) { return; // fixture scripts are POSIX shell; Windows covered by installer tests. } - for tool in ["curl", "tar"] { - let available = std::process::Command::new(tool) - .arg("--version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false); - if !available { - return; - } + let Some(tar) = absolute_tar() else { + return; + }; + if download::find_curl().is_err() { + return; } let root = std::env::temp_dir().join(format!("eggress-update-e2e-{}", std::process::id())); @@ -367,7 +416,7 @@ mod tests { ); let archive_name = target::archive_name(target); let archive_path = release_dir.join(&archive_name); - let status = std::process::Command::new("tar") + let status = std::process::Command::new(&tar) .arg("-czf") .arg(&archive_path) .arg("-C") @@ -429,15 +478,11 @@ mod tests { if target::is_windows_target(target) { return; } - for tool in ["curl", "tar"] { - let available = std::process::Command::new(tool) - .arg("--version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false); - if !available { - return; - } + let Some(tar) = absolute_tar() else { + return; + }; + if download::find_curl().is_err() { + return; } let root = std::env::temp_dir().join(format!("eggress-update-neg-{}", std::process::id())); @@ -457,7 +502,7 @@ mod tests { ); let archive_name = target::archive_name(target); let archive_path = release_dir.join(&archive_name); - std::process::Command::new("tar") + std::process::Command::new(&tar) .arg("-czf") .arg(&archive_path) .arg("-C") @@ -511,4 +556,134 @@ mod tests { std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); } } + + /// Resolve `tar` once, by absolute path, so a concurrently running test + /// that temporarily rewrites `PATH` cannot make a fixture spawn fail. + fn absolute_tar() -> Option { + let path_var = std::env::var_os("PATH")?; + std::env::split_paths(&path_var) + .filter(|dir| !dir.as_os_str().is_empty()) + .map(|dir| dir.join("tar")) + .find(|candidate| candidate.is_file()) + } + + /// Staging is created atomically with an unpredictable name and + /// owner-only permissions; a second transaction never reuses or clears + /// the first one's tree. + #[test] + fn staging_directory_is_private_and_unique() { + let first = staging_dir().unwrap(); + let second = staging_dir().unwrap(); + assert_ne!(first.path(), second.path()); + std::fs::write(first.path().join("marker"), b"in-flight").unwrap(); + assert!( + first.path().join("marker").is_file(), + "creating a second staging directory must not disturb the first" + ); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(first.path()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o700, "staging directory must be owner-only"); + } + } + + /// Concurrent updater attempts get distinct private directories instead + /// of racing on one predictable path. + #[test] + fn concurrent_staging_attempts_do_not_share_a_directory() { + let handles: Vec<_> = (0..8) + .map(|_| std::thread::spawn(|| staging_dir().unwrap())) + .collect(); + let dirs: Vec<_> = handles + .into_iter() + .map(|handle| handle.join().expect("staging thread panicked")) + .collect(); + let unique: std::collections::HashSet<_> = + dirs.iter().map(|dir| dir.path().to_path_buf()).collect(); + assert_eq!( + unique.len(), + dirs.len(), + "concurrent staging attempts must never share a path" + ); + } + + /// A replacement after the first checksum verification must fail closed + /// before any extraction happens. + #[test] + fn post_verification_archive_replacement_fails_closed() { + let root = + std::env::temp_dir().join(format!("eggress-update-toctou-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let archive = root.join("eggress-x86_64-unknown-linux-gnu.tar.gz"); + std::fs::write(&archive, b"verified-bytes").unwrap(); + let pristine = verify::compute_sha256(&archive).unwrap(); + let sidecar = format!("{pristine} eggress-x86_64-unknown-linux-gnu.tar.gz\n"); + verify::verify_archive(&archive, &sidecar).expect("first verification passes"); + + // Swap the archive after the checksum gate accepted it. + std::fs::write(&archive, b"attacker-replacement").unwrap(); + let err = verify_archive_before_extraction(&archive, &sidecar).unwrap_err(); + assert!( + err.to_string() + .contains("changed after checksum verification"), + "post-verification replacement must fail closed: {err}" + ); + assert_eq!(err.code(), eggress_cli::EXIT_RUNTIME_FAILURE); + let _ = std::fs::remove_dir_all(&root); + } + + /// `PATH` must never supply an integrity-critical tool: a planted + /// `sha256sum` cannot change the digest and a planted `curl` is never + /// selected. + #[test] + fn path_tools_are_not_trusted() { + let root = std::env::temp_dir().join(format!("eggress-update-path-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + + // `PATH` is process-global; restore it even if an assertion panics. + struct PathGuard(Option); + impl Drop for PathGuard { + fn drop(&mut self) { + match self.0.take() { + Some(value) => std::env::set_var("PATH", value), + None => std::env::remove_var("PATH"), + } + } + } + + write_script( + &root.join("sha256sum"), + "echo '0000000000000000000000000000000000000000000000000000000000000000 x'", + ); + write_script(&root.join("curl"), "echo 'fake curl 0.0.0'"); + + let guard = PathGuard(std::env::var_os("PATH")); + std::env::set_var("PATH", &root); + + let sample = root.join("sample"); + std::fs::write(&sample, b"abc").unwrap(); + assert_eq!( + verify::compute_sha256(&sample).unwrap(), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + "a fake `sha256sum` on PATH must not influence verification" + ); + if let Ok(resolved) = download::find_curl() { + assert_ne!( + resolved, + root.join("curl"), + "a PATH-only curl must never be selected" + ); + } + + drop(guard); + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/crates/eggress-cli/src/update/verify.rs b/crates/eggress-cli/src/update/verify.rs index d90493da..772fd02c 100644 --- a/crates/eggress-cli/src/update/verify.rs +++ b/crates/eggress-cli/src/update/verify.rs @@ -7,9 +7,12 @@ //! replacement begin. Any mismatch is a hard error with no fallback to //! another install source. +use std::io::Read; use std::path::Path; use std::process::Command; +use sha2::{Digest, Sha256}; + use super::version::ReleaseVersion; /// Parse a `.sha256` sidecar to its expected lowercase hex digest. @@ -28,30 +31,42 @@ pub fn parse_checksum_sidecar(text: &str) -> Result { Err("checksum sidecar contains no SHA-256 digest".to_string()) } -/// Compute the SHA-256 hex digest of a file using `sha256sum` or -/// `shasum -a 256` (the same tools the bootstrap installer uses). +/// Compute the SHA-256 hex digest of a file in-process. +/// +/// This hash is the integrity authority. No `sha256sum`/`shasum` process is +/// discovered, executed, or parsed, so a `PATH`-planted tool can never +/// influence whether an archive is accepted. pub fn compute_sha256(path: &Path) -> Result { - for (program, args) in [("sha256sum", vec![]), ("shasum", vec!["-a", "256"])] { - let output = match Command::new(program).args(&args).arg(path).output() { - Ok(output) => output, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, - Err(e) => { - return Err(format!("failed to run {program}: {e}")); - } - }; - if !output.status.success() { - continue; + let mut file = std::fs::File::open(path).map_err(|e| { + format!( + "cannot open {} for SHA-256 verification: {e}", + path.display() + ) + })?; + let mut hasher = Sha256::new(); + let mut buffer = vec![0u8; 64 * 1024]; + loop { + let read = file.read(&mut buffer).map_err(|e| { + format!( + "cannot read {} for SHA-256 verification: {e}", + path.display() + ) + })?; + if read == 0 { + break; } - let stdout = String::from_utf8_lossy(&output.stdout); - if let Some(digest) = stdout - .split_whitespace() - .next() - .filter(|t| t.len() == 64 && t.bytes().all(|b| b.is_ascii_hexdigit())) - { - return Ok(digest.to_ascii_lowercase()); + hasher.update(&buffer[..read]); + } + let digest = hasher.finalize(); + let mut hex = String::with_capacity(64); + { + use std::fmt::Write as _; + for byte in digest { + // Writing into a `String` cannot fail. + let _ = write!(hex, "{byte:02x}"); } } - Err("neither `sha256sum` nor `shasum -a 256` is available; install one or update with the bootstrap installer instead".to_string()) + Ok(hex) } /// Verify an archive against its sidecar text. Fails closed on any mismatch. @@ -165,6 +180,65 @@ mod tests { assert!(parse_checksum_sidecar("").is_err()); } + /// FIPS 180-2 / RFC 6234 known-answer vectors: the in-process hasher must + /// agree with the published SHA-256 values, not with a shell tool. + #[test] + fn sha256_matches_known_vectors() { + let root = std::env::temp_dir().join(format!("eggress-sha256-vec-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + + let empty = root.join("empty"); + std::fs::write(&empty, b"").unwrap(); + assert_eq!( + compute_sha256(&empty).unwrap(), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + + let abc = root.join("abc"); + std::fs::write(&abc, b"abc").unwrap(); + assert_eq!( + compute_sha256(&abc).unwrap(), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + + // Multi-block input: 1,000,000 'a' bytes crosses the 64 KiB read + // buffer many times and must still hash as one stream. + let million = root.join("million"); + std::fs::write(&million, vec![b'a'; 1_000_000]).unwrap(); + assert_eq!( + compute_sha256(&million).unwrap(), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); + + assert!(compute_sha256(&root.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(&root); + } + + /// The sidecar remains the gate: the in-process digest of the exact + /// archive file is what decides acceptance. + #[test] + fn sidecar_comparison_uses_the_in_process_digest() { + let root = std::env::temp_dir().join(format!("eggress-sha256-side-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let archive = root.join("eggress-x86_64-unknown-linux-gnu.tar.gz"); + std::fs::write(&archive, b"release-bytes").unwrap(); + + let digest = compute_sha256(&archive).unwrap(); + let sidecar = format!("{digest} eggress-x86_64-unknown-linux-gnu.tar.gz\n"); + verify_archive(&archive, &sidecar).unwrap(); + + std::fs::write(&archive, b"tampered-bytes").unwrap(); + let err = verify_archive(&archive, &sidecar).unwrap_err(); + assert!(err.contains("checksum mismatch"), "{err}"); + + // Same bytes written back: the digest is deterministic. + std::fs::write(&archive, b"release-bytes").unwrap(); + verify_archive(&archive, &sidecar).unwrap(); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn parses_candidate_version_strings() { assert_eq!( diff --git a/crates/eggress-cli/tests/pproxy_cli.rs b/crates/eggress-cli/tests/pproxy_cli.rs index 0f6eed17..7898a1af 100644 --- a/crates/eggress-cli/tests/pproxy_cli.rs +++ b/crates/eggress-cli/tests/pproxy_cli.rs @@ -204,6 +204,54 @@ fn translate_annotate_flag() { assert!(stdout.contains("# Generated by eggress pproxy translate")); } +#[test] +fn translate_annotate_redacts_credentials_but_keeps_toml_runnable() { + let output = eggress_bin() + .args([ + "pproxy", + "translate", + "--annotate", + "--", + "-l", + "http://admin:supersecret@127.0.0.1:1080", + "-r", + "socks5://bob:hunter2@upstream:1080", + ]) + .output() + .expect("failed to run eggress"); + assert!( + output.status.success(), + "translate failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let annotation = stdout + .lines() + .find(|line| line.starts_with("# pproxy arguments:")) + .expect("annotate output must include the pproxy argument line"); + assert!( + annotation.contains("http://****:****@127.0.0.1:1080"), + "listener credentials must be redacted: {annotation}" + ); + assert!( + annotation.contains("socks5://****:****@upstream:1080"), + "remote credentials must be redacted: {annotation}" + ); + assert!( + !annotation.contains("supersecret") && !annotation.contains("hunter2"), + "annotated argv leaked credentials: {annotation}" + ); + // Generated TOML keeps the real credentials so it stays runnable. + assert!( + stdout.contains("password = \"supersecret\""), + "generated TOML lost listener credentials: {stdout}" + ); + assert!( + stdout.contains("socks5://bob:hunter2@upstream:1080"), + "generated TOML lost upstream credentials: {stdout}" + ); +} + #[test] fn translate_chain_of_two_upstreams() { let output = eggress_bin() @@ -226,3 +274,58 @@ fn translate_chain_of_two_upstreams() { assert!(stdout.contains("pproxy-upstream-1")); assert!(stdout.contains("first-available")); } + +// `check --json` must keep its recognized display paths redacted. Note that +// `raw_args` and `chain_info[].raw` are documented "raw" fields (see the +// `cli.check_json_chain_info` manifest entry); closing those is a separate +// contract decision and is not asserted here. +#[test] +fn check_json_redacts_parsed_uris_and_diagnostics() { + let output = eggress_bin() + .args([ + "pproxy", + "check", + "--json", + "--", + "-l", + "socks5://alice:s3cr3t-listen@127.0.0.1:1080", + "-r", + "http://bob:hunter2-up@upstream:8080", + ]) + .output() + .expect("failed to run eggress"); + assert!( + output.status.success(), + "check --json failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + let json: serde_json::Value = + serde_json::from_str(&stdout).expect("check --json must be valid JSON"); + + let parsed = &json["parsed_uris"]; + let parsed_display = format!("{} {}", parsed["listeners"], parsed["remotes"]); + assert!( + !parsed_display.contains("s3cr3t-listen") && !parsed_display.contains("hunter2-up"), + "parsed_uris leaked credentials: {parsed_display}" + ); + assert!( + parsed["listeners"][0] + .as_str() + .unwrap() + .contains("****:****@"), + "listener display must be redacted: {parsed_display}" + ); + assert!( + parsed["remotes"][0] + .as_str() + .unwrap() + .contains("****:****@"), + "remote display must be redacted: {parsed_display}" + ); + let diagnostics = json["diagnostics"].to_string(); + assert!( + !diagnostics.contains("s3cr3t-listen") && !diagnostics.contains("hunter2-up"), + "diagnostics leaked credentials: {diagnostics}" + ); +} diff --git a/crates/eggress-cli/tests/system_proxy_inspect.rs b/crates/eggress-cli/tests/system_proxy_inspect.rs new file mode 100644 index 00000000..22aa4f67 --- /dev/null +++ b/crates/eggress-cli/tests/system_proxy_inspect.rs @@ -0,0 +1,58 @@ +//! `eggress system-proxy inspect --json` must never print raw proxy +//! credentials. The inspection surface is copy/paste-able diagnostics, and +//! OS/environment proxy settings can carry `user:pass@` userinfo. +#![cfg(feature = "operations")] + +use std::process::Command; + +fn eggress_bin() -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_eggress")); + cmd.env("RUST_LOG", "error"); + cmd +} + +#[test] +fn system_proxy_inspect_json_contains_no_credentials() { + let output = eggress_bin() + .args(["system-proxy", "inspect", "--json"]) + // Credential-bearing proxy environment (the env backend reads these + // verbatim; macOS/Linux backends fall back to them when the native + // settings source is unavailable). + .env("http_proxy", "http://user:pass@proxy.invalid:8080") + .env("HTTP_PROXY", "http://user:pass@proxy.invalid:8080") + .env("https_proxy", "http://user:pass@proxy.invalid:8443") + .env("HTTPS_PROXY", "http://user:pass@proxy.invalid:8443") + .env("all_proxy", "socks5://admin:secret@proxy.invalid:1080") + .env("ALL_PROXY", "socks5://admin:secret@proxy.invalid:1080") + .output() + .expect("failed to run eggress"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "system-proxy inspect --json failed: {stderr}\nstdout: {stdout}" + ); + + let value: serde_json::Value = + serde_json::from_str(&stdout).expect("inspect --json must emit valid JSON"); + assert!( + value.get("settings").is_none(), + "raw settings must not be serialized: {stdout}" + ); + assert!( + value.get("redacted_settings").is_some(), + "redacted settings must always be emitted: {stdout}" + ); + + for secret in ["user:pass@", "admin:secret@", "pass@proxy", "secret@proxy"] { + assert!( + !stdout.contains(secret), + "inspect --json leaked proxy credentials ({secret}): {stdout}" + ); + assert!( + !stderr.contains(secret), + "inspect --json stderr leaked proxy credentials ({secret}): {stderr}" + ); + } +} diff --git a/crates/eggress-cli/tests/updater_trust.rs b/crates/eggress-cli/tests/updater_trust.rs new file mode 100644 index 00000000..a11061e1 --- /dev/null +++ b/crates/eggress-cli/tests/updater_trust.rs @@ -0,0 +1,102 @@ +//! Updater trust-boundary contracts exercised through the real binary. +//! +//! These tests cover what only a built binary can prove: +//! +//! - a default/release build ignores `EGRESS_UPDATE_BASE_URL` and therefore +//! cannot be redirected at a `file://` tree; +//! - a build with the non-default `update-fixtures` feature does honor the +//! fixture base URL (the offline test hook still exists, behind the +//! feature). + +use std::path::PathBuf; +use std::process::Command; + +fn eggress_bin() -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_eggress")); + cmd.env("RUST_LOG", "error"); + cmd +} + +fn fixture_root(label: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!( + "eggress-updater-trust-{label}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + // Older than the running build, so a fixture-aware updater exits before + // any installation or replacement step. + std::fs::write(root.join("latest.json"), "v0.0.1").unwrap(); + root +} + +/// Default/release builds must ignore the fixture hook: the only permitted +/// discovery URL is the HTTPS GitHub API. +#[cfg(not(feature = "update-fixtures"))] +#[test] +fn default_build_ignores_update_base_url_and_rejects_file_urls() { + let root = fixture_root("release"); + let output = eggress_bin() + .arg("update") + .env( + "EGRESS_UPDATE_BASE_URL", + format!("file://{}", root.display()), + ) + // Force any real HTTPS attempt to fail immediately and locally. If the + // fixture base URL were honored, curl would read the local file and + // report "already the latest stable version" instead. + .env("https_proxy", "http://127.0.0.1:1") + .env("HTTPS_PROXY", "http://127.0.0.1:1") + .env("all_proxy", "http://127.0.0.1:1") + .env("ALL_PROXY", "http://127.0.0.1:1") + .env("no_proxy", "") + .env("NO_PROXY", "") + .output() + .expect("failed to run eggress update"); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + + assert!( + !stdout.contains("already the latest stable version"), + "release updater honored EGRESS_UPDATE_BASE_URL/file://: stdout={stdout}" + ); + assert_eq!( + output.status.code(), + Some(eggress_cli::EXIT_EXTERNAL_DEPENDENCY), + "release updater must fail on the unreachable HTTPS discovery URL \ + (not read the fixture):\nstdout: {stdout}\nstderr: {stderr}" + ); + assert!( + stderr.contains("download failed"), + "expected a discovery/download failure against GitHub, got: {stderr}" + ); + + let _ = std::fs::remove_dir_all(&root); +} + +/// The offline fixture hook still works, but only when the non-default +/// `update-fixtures` feature is enabled at build time. +#[cfg(all(unix, feature = "update-fixtures"))] +#[test] +fn update_fixtures_feature_honors_file_base_url() { + let root = fixture_root("feature"); + let output = eggress_bin() + .arg("update") + .env( + "EGRESS_UPDATE_BASE_URL", + format!("file://{}", root.display()), + ) + .output() + .expect("failed to run eggress update"); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "fixture updater should read the local release metadata:\nstdout: {stdout}\nstderr: {stderr}" + ); + assert!( + stdout.contains("already the latest stable version"), + "fixture base URL was not honored: {stdout}" + ); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/eggress-config/Cargo.toml b/crates/eggress-config/Cargo.toml index a9b4a901..4af66447 100644 --- a/crates/eggress-config/Cargo.toml +++ b/crates/eggress-config/Cargo.toml @@ -24,6 +24,7 @@ rustls.workspace = true serde = { workspace = true, features = ["derive"] } toml.workspace = true thiserror.workspace = true +tracing.workspace = true regex.workspace = true ipnet.workspace = true zeroize.workspace = true diff --git a/crates/eggress-config/src/compile/admin_hosts.rs b/crates/eggress-config/src/compile/admin_hosts.rs new file mode 100644 index 00000000..8a7a05d0 --- /dev/null +++ b/crates/eggress-config/src/compile/admin_hosts.rs @@ -0,0 +1,235 @@ +//! Admin `Host` allowlist normalization. +//! +//! The admin HTTP surface validates the `Host` header (and the `Origin` host of +//! state-changing requests) against this allowlist to block DNS-rebinding +//! reads. Entries are stored normalized — lowercase, without IPv6 brackets and +//! without a port — so comparisons are case-insensitive and port-insensitive. + +use std::net::IpAddr; + +/// Normalize a host entry to a bare lowercase host. +/// +/// Accepts the forms a `Host` header, an `Origin` authority, or a configured +/// `admin.allowed_hosts` entry can take: `example.com`, `example.com:9090`, +/// `[::1]:9090`, `::1`, and `[::1]`. Returns `None` for empty input, a +/// malformed bracket/port suffix, or characters that cannot appear in a host +/// (whitespace, `/`, `\`, `@`, `*`, `?`, `#`). +/// +/// A literal `null` normalizes to `null`; the admin server accepts +/// `Origin: null` only when the operator lists `null` explicitly. +pub fn normalize_host_entry(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return None; + } + + let host = if let Some(rest) = trimmed.strip_prefix('[') { + let close = rest.find(']')?; + let after = &rest[close + 1..]; + if !after.is_empty() { + // Only `:port` may follow the closing bracket. + let port = after.strip_prefix(':')?; + port.parse::().ok()?; + } + &rest[..close] + } else if trimmed.matches(':').count() == 1 { + let (host, port) = trimmed.rsplit_once(':')?; + port.parse::().ok()?; + host + } else { + // No colon, or an unbracketed IPv6 literal. + trimmed + }; + + let host = host.trim(); + if host.is_empty() || !host.chars().all(is_host_char) { + return None; + } + Some(host.to_ascii_lowercase()) +} + +fn is_host_char(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ':') +} + +/// Effective admin `Host` allowlist: bind-derived defaults plus configured +/// entries (deduplicated, order preserved). +pub fn effective_allowed_hosts(configured: Option<&[String]>, bind: &str) -> Vec { + let mut hosts = derive_allowed_hosts(bind); + if let Some(configured) = configured { + for entry in configured { + if let Some(host) = normalize_host_entry(entry) { + push_unique(&mut hosts, host); + } + } + } + hosts +} + +/// Default allowlist implied by an admin bind address. +/// +/// * loopback bind (`127.0.0.1`, `[::1]`, …) and unspecified bind (`0.0.0.0`, +/// `::`): the bind host plus `localhost`, `127.0.0.1`, and `::1`, so plain +/// loopback clients keep working without configuration; +/// * any other non-loopback bind: the bind host plus `localhost`. An operator +/// behind a reverse proxy or using a DNS name must list that host explicitly +/// in `[admin] allowed_hosts`. +pub fn derive_allowed_hosts(bind: &str) -> Vec { + let bind_host = normalize_host_entry(host_part(bind)).unwrap_or_default(); + let loopback_reachable = is_loopback_host(&bind_host) || is_unspecified_host(&bind_host); + + let mut hosts = Vec::new(); + if !bind_host.is_empty() { + hosts.push(bind_host); + } + push_unique(&mut hosts, "localhost".to_string()); + if loopback_reachable { + push_unique(&mut hosts, "127.0.0.1".to_string()); + push_unique(&mut hosts, "::1".to_string()); + } + hosts +} + +fn push_unique(hosts: &mut Vec, host: String) { + if !hosts.iter().any(|existing| existing == &host) { + hosts.push(host); + } +} + +/// Extract the host part of a `host:port` bind string, tolerating bracketed +/// IPv6 (`[::1]:9090`) and unbracketed forms (`::`, `0.0.0.0:9090`). +fn host_part(bind: &str) -> &str { + let bind = bind.trim(); + if let Some(rest) = bind.strip_prefix('[') { + return match rest.find(']') { + Some(close) => &rest[..close], + None => bind, + }; + } + match bind.rsplit_once(':') { + Some((host, port)) if !host.contains(':') && port.parse::().is_ok() => host, + _ => bind, + } +} + +fn is_loopback_host(host: &str) -> bool { + if host.eq_ignore_ascii_case("localhost") { + return true; + } + match host.parse::() { + Ok(IpAddr::V4(v4)) => v4.is_loopback(), + Ok(IpAddr::V6(v6)) => { + v6.is_loopback() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()) + } + Err(_) => false, + } +} + +fn is_unspecified_host(host: &str) -> bool { + host.parse::().is_ok_and(|ip| ip.is_unspecified()) +} + +#[cfg(test)] +mod tests { + use super::{derive_allowed_hosts, effective_allowed_hosts, normalize_host_entry}; + + #[test] + fn normalizes_host_and_port_forms() { + assert_eq!( + normalize_host_entry("Example.COM"), + Some("example.com".into()) + ); + assert_eq!( + normalize_host_entry("admin.example.com:9090"), + Some("admin.example.com".into()) + ); + assert_eq!( + normalize_host_entry("127.0.0.1:9090"), + Some("127.0.0.1".into()) + ); + assert_eq!(normalize_host_entry("[::1]:9090"), Some("::1".into())); + assert_eq!(normalize_host_entry("[::1]"), Some("::1".into())); + assert_eq!(normalize_host_entry("::1"), Some("::1".into())); + assert_eq!( + normalize_host_entry(" ::ffff:127.0.0.1 "), + Some("::ffff:127.0.0.1".into()) + ); + } + + #[test] + fn rejects_malformed_and_injectable_entries() { + assert_eq!(normalize_host_entry(""), None); + assert_eq!(normalize_host_entry(" "), None); + assert_eq!(normalize_host_entry("[::1"), None); + assert_eq!(normalize_host_entry("[::1]junk"), None); + assert_eq!(normalize_host_entry("host:notaport"), None); + assert_eq!(normalize_host_entry("*.example.com"), None); + assert_eq!(normalize_host_entry("host/path"), None); + assert_eq!(normalize_host_entry("user@host"), None); + assert_eq!(normalize_host_entry("host name"), None); + } + + #[test] + fn loopback_bind_allows_loopback_names() { + assert_eq!( + derive_allowed_hosts("127.0.0.1:9090"), + vec![ + "127.0.0.1".to_string(), + "localhost".to_string(), + "::1".to_string() + ] + ); + assert_eq!( + derive_allowed_hosts("[::1]:9090"), + vec![ + "::1".to_string(), + "localhost".to_string(), + "127.0.0.1".to_string() + ] + ); + } + + #[test] + fn wildcard_bind_still_allows_loopback_clients() { + let hosts = derive_allowed_hosts("0.0.0.0:9090"); + assert!(hosts.contains(&"0.0.0.0".to_string())); + assert!(hosts.contains(&"127.0.0.1".to_string())); + assert!(hosts.contains(&"::1".to_string())); + assert!(hosts.contains(&"localhost".to_string())); + } + + #[test] + fn non_loopback_bind_allows_bind_host_and_localhost_only() { + let hosts = derive_allowed_hosts("10.1.2.3:9090"); + assert_eq!(hosts, vec!["10.1.2.3".to_string(), "localhost".to_string()]); + } + + #[test] + fn configured_hosts_extend_bind_defaults_without_duplicates() { + let configured = vec![ + "Admin.Example".to_string(), + "127.0.0.1:9090".to_string(), + "null".to_string(), + ]; + let hosts = effective_allowed_hosts(Some(&configured), "127.0.0.1:9090"); + assert_eq!( + hosts, + vec![ + "127.0.0.1".to_string(), + "localhost".to_string(), + "::1".to_string(), + "admin.example".to_string(), + "null".to_string(), + ] + ); + // An absent or empty list is a no-op: the bind defaults stand alone. + assert_eq!( + effective_allowed_hosts(None, "127.0.0.1:9090"), + derive_allowed_hosts("127.0.0.1:9090") + ); + assert_eq!( + effective_allowed_hosts(Some(&[]), "127.0.0.1:9090"), + derive_allowed_hosts("127.0.0.1:9090") + ); + } +} diff --git a/crates/eggress-config/src/compile/mod.rs b/crates/eggress-config/src/compile/mod.rs index 6e63deca..0ea9f667 100644 --- a/crates/eggress-config/src/compile/mod.rs +++ b/crates/eggress-config/src/compile/mod.rs @@ -5,6 +5,7 @@ //! startup. Public compiled types stay reachable at //! `eggress_config::compile::…` via re-exports. +pub mod admin_hosts; pub mod listeners; pub mod model; pub mod process; @@ -12,6 +13,8 @@ pub mod reverse; pub mod rules; pub mod upstreams; +pub use admin_hosts::{derive_allowed_hosts, effective_allowed_hosts, normalize_host_entry}; + pub use model::{ AdminAuthConfig, AdminConfig, CompiledH2Config, CompiledListenerTlsConfig, CompiledListenerUdpConfig, CompiledReverseClientConfig, CompiledReverseClientTls, diff --git a/crates/eggress-config/src/compile/model.rs b/crates/eggress-config/src/compile/model.rs index 99f665cb..5f524893 100644 --- a/crates/eggress-config/src/compile/model.rs +++ b/crates/eggress-config/src/compile/model.rs @@ -295,13 +295,25 @@ pub struct ListenerConfig { } /// Compiled TLS configuration for a listener. -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct CompiledListenerTlsConfig { pub cert_pem: Vec, pub key_pem: Vec, pub alpn: Vec>, } +impl std::fmt::Debug for CompiledListenerTlsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Never print PEM material; presence flags and a length only. + f.debug_struct("CompiledListenerTlsConfig") + .field("has_cert", &!self.cert_pem.is_empty()) + .field("has_key", &!self.key_pem.is_empty()) + .field("key_len", &self.key_pem.len()) + .field("alpn", &self.alpn) + .finish() + } +} + #[derive(Debug, Clone)] pub struct CompiledH2Config { pub max_concurrent_streams: u32, @@ -375,6 +387,10 @@ pub struct AdminConfig { pub bind: String, pub enabled: bool, pub metrics: bool, + /// Host header values the admin server accepts, normalized (lowercase, + /// no brackets or port). Contains the bind-derived defaults plus any + /// configured `[admin] allowed_hosts` entries. + pub allowed_hosts: Vec, pub auth: Option, pub pac: Option, pub static_content: Vec, @@ -409,3 +425,85 @@ impl Drop for AdminAuthConfig { } } } + +#[cfg(test)] +mod tests { + use super::*; + + const CERT_PEM: &[u8] = + b"-----BEGIN CERTIFICATE-----\nCERT-SECRET-BYTES\n-----END CERTIFICATE-----\n"; + const KEY_PEM: &[u8] = + b"-----BEGIN PRIVATE KEY-----\nKEY-SECRET-BYTES\n-----END PRIVATE KEY-----\n"; + + fn listener_with_tls(tls: CompiledListenerTlsConfig) -> ListenerConfig { + ListenerConfig { + name: "tls-in".to_string(), + bind: "127.0.0.1:8443".to_string(), + protocols: vec![ProtocolId::Http], + reuse_port: None, + connection_limit: None, + auth: None, + udp: None, + tls: Some(tls), + shadowsocks: None, + trojan: None, + transparent: None, + unix: None, + fixed_target: None, + local_bind: None, + } + } + + #[test] + fn compiled_listener_tls_debug_redacts_pem_material() { + let config = CompiledListenerTlsConfig { + cert_pem: CERT_PEM.to_vec(), + key_pem: KEY_PEM.to_vec(), + alpn: vec![b"h2".to_vec()], + }; + + let rendered = format!("{config:?}"); + assert!(!rendered.contains("KEY-SECRET-BYTES"), "{rendered}"); + assert!(!rendered.contains("CERT-SECRET-BYTES"), "{rendered}"); + assert!(!rendered.contains("PRIVATE KEY"), "{rendered}"); + assert!(!rendered.contains("BEGIN CERTIFICATE"), "{rendered}"); + // Non-secret shape only: presence flags plus a key length. + assert!(rendered.contains("has_cert: true"), "{rendered}"); + assert!(rendered.contains("has_key: true"), "{rendered}"); + assert!( + rendered.contains(&format!("key_len: {}", KEY_PEM.len())), + "{rendered}" + ); + } + + #[test] + fn compiled_listener_tls_debug_reports_absent_material() { + let config = CompiledListenerTlsConfig { + cert_pem: Vec::new(), + key_pem: Vec::new(), + alpn: Vec::new(), + }; + + let rendered = format!("{config:?}"); + assert!(rendered.contains("has_cert: false"), "{rendered}"); + assert!(rendered.contains("has_key: false"), "{rendered}"); + assert!(rendered.contains("key_len: 0"), "{rendered}"); + } + + /// The enclosing `ListenerConfig` derives `Debug`; the redaction must hold + /// across that nesting boundary, which is how compiled listeners are + /// actually rendered. + #[test] + fn listener_config_debug_redacts_nested_tls_key() { + let listener = listener_with_tls(CompiledListenerTlsConfig { + cert_pem: CERT_PEM.to_vec(), + key_pem: KEY_PEM.to_vec(), + alpn: Vec::new(), + }); + + let rendered = format!("{listener:?}"); + assert!(!rendered.contains("KEY-SECRET-BYTES"), "{rendered}"); + assert!(!rendered.contains("CERT-SECRET-BYTES"), "{rendered}"); + assert!(rendered.contains("CompiledListenerTlsConfig"), "{rendered}"); + } +} diff --git a/crates/eggress-config/src/compile/process.rs b/crates/eggress-config/src/compile/process.rs index 9c16f31d..377d86d8 100644 --- a/crates/eggress-config/src/compile/process.rs +++ b/crates/eggress-config/src/compile/process.rs @@ -81,13 +81,20 @@ pub(crate) fn compile_admin(config: &ConfigFile) -> Result, }) .unwrap_or_default(); + let bind = admin + .bind + .clone() + .unwrap_or_else(|| "127.0.0.1:9090".to_string()); + // Bind-derived defaults keep loopback admin clients working without + // configuration; configured hosts are additive. + let allowed_hosts = + super::admin_hosts::effective_allowed_hosts(admin.allowed_hosts.as_deref(), &bind); + Ok(Some(AdminConfig { - bind: admin - .bind - .clone() - .unwrap_or_else(|| "127.0.0.1:9090".to_string()), + bind, enabled: admin.enabled.unwrap_or(true), metrics: admin.metrics.unwrap_or(true), + allowed_hosts, auth, pac, static_content, diff --git a/crates/eggress-config/src/compile/upstreams.rs b/crates/eggress-config/src/compile/upstreams.rs index ddf0a2a9..4d6b624b 100644 --- a/crates/eggress-config/src/compile/upstreams.rs +++ b/crates/eggress-config/src/compile/upstreams.rs @@ -199,6 +199,8 @@ pub(crate) fn compile_upstreams(config: &ConfigFile) -> Result { ConfigError::validation(&format!("upstream {}.{}", u.id, path), &message) @@ -273,3 +275,199 @@ pub(crate) fn compile_groups(config: &ConfigFile) -> Result ([+])` entries joined by `, `. +/// +/// Returns `None` when every hop verifies certificates. Kept separate from the +/// logging call so the redacted shape can be asserted directly in tests. +fn insecure_hop_summary(chain: &eggress_uri::ProxyChainSpec) -> Option { + let summary: Vec = chain + .hops + .iter() + .enumerate() + .filter(|(_, hop)| hop.insecure) + .map(|(idx, hop)| { + let protocols: Vec<&str> = hop + .protocols + .iter() + .map(|protocol| protocol.canonical_name()) + .collect(); + format!("hop {idx} ({})", protocols.join("+")) + }) + .collect(); + if summary.is_empty() { + None + } else { + Some(summary.join(", ")) + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use tracing::field::{Field, Visit}; + use tracing::span::{Attributes, Id, Record}; + use tracing::{Event, Metadata, Subscriber}; + + use super::*; + + fn parse_chain(uri: &str) -> eggress_uri::ProxyChainSpec { + eggress_uri::parse_proxy_chain(uri).expect("test URI must parse") + } + + #[test] + fn insecure_hop_summary_is_none_for_verified_chain() { + let chain = parse_chain("socks5://hop1:1080__http://hop2:8080"); + assert!(insecure_hop_summary(&chain).is_none()); + } + + #[test] + fn insecure_hop_summary_names_only_hop_index_and_protocols() { + let chain = + parse_chain("socks5://user:topsecret@insecure.example:1080?insecure__http://hop2:8080"); + let summary = insecure_hop_summary(&chain).expect("hop 0 selects ?insecure"); + assert_eq!(summary, "hop 0 (socks5)"); + assert!( + !summary.contains("topsecret"), + "credentials leaked: {summary}" + ); + assert!( + !summary.contains("insecure.example"), + "host leaked: {summary}" + ); + assert!(!summary.contains("1080"), "port leaked: {summary}"); + } + + #[test] + fn insecure_hop_summary_lists_every_insecure_hop() { + let chain = parse_chain("socks5://a:1?insecure__http://b:2?insecure"); + let summary = insecure_hop_summary(&chain).expect("both hops select ?insecure"); + assert_eq!(summary, "hop 0 (socks5), hop 1 (http)"); + } + + /// Minimal subscriber that records every event's fields as + /// `name=value` pairs, so a compile-time warning can be asserted without + /// adding a logging test dependency. + #[derive(Default)] + struct CaptureSubscriber { + events: Arc>>, + } + + struct FieldCollector(Vec); + + impl Visit for FieldCollector { + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + self.0.push(format!("{}={value:?}", field.name())); + } + } + + impl Subscriber for CaptureSubscriber { + fn enabled(&self, _metadata: &Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _span: &Attributes<'_>) -> Id { + Id::from_u64(1) + } + + fn record(&self, _span: &Id, _values: &Record<'_>) {} + + fn record_follows_from(&self, _span: &Id, _follows: &Id) {} + + fn event(&self, event: &Event<'_>) { + let mut collector = FieldCollector(Vec::new()); + event.record(&mut collector); + self.events.lock().unwrap().push(collector.0.join(" ")); + } + + fn enter(&self, _span: &Id) {} + + fn exit(&self, _span: &Id) {} + } + + fn compile_and_capture(config_toml: &str) -> Vec { + let config: crate::model::ConfigFile = + toml::from_str(config_toml).expect("test config must parse"); + + let subscriber = CaptureSubscriber::default(); + let events = Arc::clone(&subscriber.events); + tracing::subscriber::with_default(subscriber, || { + compile_upstreams(&config).expect("upstreams must compile"); + }); + let captured = events.lock().unwrap().clone(); + captured + } + + #[test] + fn compile_warns_once_for_the_insecure_upstream_only() { + let events = compile_and_capture( + r#" +version = 1 + +[[upstreams]] +id = "verified" +uri = "socks5://verify.example:1080" + +[[upstreams]] +id = "bypassed" +uri = "socks5://user:topsecret@insecure.example:1080?insecure" +"#, + ); + + assert_eq!( + events.len(), + 1, + "exactly one notice expected, got {events:?}" + ); + let notice = &events[0]; + assert!(notice.contains("upstream=bypassed"), "{notice}"); + assert!(notice.contains("insecure_hops=hop 0 (socks5)"), "{notice}"); + assert!(notice.contains("insecure-tls"), "{notice}"); + assert!( + !notice.contains("topsecret"), + "credentials leaked: {notice}" + ); + assert!( + !notice.contains("insecure.example"), + "host leaked: {notice}" + ); + } + + #[test] + fn compile_does_not_warn_when_every_hop_verifies() { + let events = compile_and_capture( + r#" +version = 1 + +[[upstreams]] +id = "verified" +uri = "socks5+tls://verify.example:1080" +"#, + ); + + assert!(events.is_empty(), "unexpected notice: {events:?}"); + } +} diff --git a/crates/eggress-config/src/lib.rs b/crates/eggress-config/src/lib.rs index 88d88449..ea5ac4e8 100644 --- a/crates/eggress-config/src/lib.rs +++ b/crates/eggress-config/src/lib.rs @@ -485,6 +485,66 @@ protocols = ["http"] assert!(rt.admin.is_none()); } + #[test] + fn compile_admin_allowed_hosts_default_to_loopback_names() { + let config = r#" +version = 1 + +[admin] +bind = "127.0.0.1:9090" +"#; + let f = write_config(config); + let rt = load_and_validate(f.path().to_str().unwrap()).unwrap(); + let admin = rt.admin.expect("admin section compiles"); + assert_eq!(admin.bind, "127.0.0.1:9090"); + assert_eq!( + admin.allowed_hosts, + vec!["127.0.0.1", "localhost", "::1"] + .into_iter() + .map(str::to_string) + .collect::>() + ); + } + + #[test] + fn compile_admin_allowed_hosts_are_additive_and_normalized() { + let config = r#" +version = 1 + +[admin] +bind = "127.0.0.1:9090" +allowed_hosts = ["Admin.Example", "[::1]:9090", "null"] +"#; + let f = write_config(config); + let rt = load_and_validate(f.path().to_str().unwrap()).unwrap(); + let admin = rt.admin.expect("admin section compiles"); + assert_eq!( + admin.allowed_hosts, + vec!["127.0.0.1", "localhost", "::1", "admin.example", "null"] + .into_iter() + .map(str::to_string) + .collect::>() + ); + } + + #[test] + fn invalid_admin_allowed_host_entry_is_rejected() { + let config = r#" +version = 1 + +[admin] +bind = "127.0.0.1:9090" +allowed_hosts = ["*.example.com"] +"#; + let f = write_config(config); + let err = load_and_validate(f.path().to_str().unwrap()).unwrap_err(); + let message = err.to_string(); + assert!( + message.contains("admin.allowed_hosts[0]"), + "unexpected error: {message}" + ); + } + #[test] fn parse_duration_seconds() { let d = validate::validate_duration("30s").unwrap(); diff --git a/crates/eggress-config/src/model.rs b/crates/eggress-config/src/model.rs index 27814434..f2babc90 100644 --- a/crates/eggress-config/src/model.rs +++ b/crates/eggress-config/src/model.rs @@ -349,6 +349,11 @@ pub struct AdminConfig { pub bind: Option, pub enabled: Option, pub metrics: Option, + /// Extra `Host` header values accepted by the admin server, on top of the + /// defaults derived from `bind`. Required when the admin port is reached + /// through a reverse proxy or a DNS name. + #[serde(default)] + pub allowed_hosts: Option>, pub auth: Option, pub pac: Option, pub static_content: Option>, diff --git a/crates/eggress-config/src/validate/core.rs b/crates/eggress-config/src/validate/core.rs index 0ae9025e..09187ac0 100644 --- a/crates/eggress-config/src/validate/core.rs +++ b/crates/eggress-config/src/validate/core.rs @@ -130,6 +130,20 @@ pub(crate) fn validate_admin(admin: &crate::model::AdminConfig, errors: &mut Vec )); } + if let Some(ref allowed_hosts) = admin.allowed_hosts { + for (i, entry) in allowed_hosts.iter().enumerate() { + if crate::compile::admin_hosts::normalize_host_entry(entry).is_none() { + errors.push(ConfigError::validation( + &format!("admin.allowed_hosts[{i}]"), + &format!( + "invalid host entry '{entry}': expected a host name or IP literal, \ + optionally with a port; wildcards are not supported" + ), + )); + } + } + } + if let Some(auth) = &admin.auth { if auth.bearer_token.as_deref().is_some_and(str::is_empty) { errors.push(ConfigError::validation( diff --git a/crates/eggress-config/src/validate/security.rs b/crates/eggress-config/src/validate/security.rs index a0cd6ae0..a195b9be 100644 --- a/crates/eggress-config/src/validate/security.rs +++ b/crates/eggress-config/src/validate/security.rs @@ -1,10 +1,13 @@ //! Security validation: warnings for dangerous combinations and //! pproxy-compatibility alias notices. Non-fatal by design. +use eggress_core::connector::is_reserved_or_private_ip; + use super::listeners::is_loopback_bind; use super::rules::MAX_MATCH_EXPR_DEPTH; use crate::error::ConfigWarning; -use crate::model::{ConfigFile, MatchExprConfig}; +use crate::model::{ConfigFile, MatchExprConfig, RuleConfig}; + /// Emit security warnings for dangerous config combinations. /// /// This runs after structural validation succeeds and produces non-fatal @@ -32,6 +35,28 @@ pub fn validate_config_security(config: &ConfigFile) -> Vec { ), }); } + // Password-authenticated HTTP/SOCKS on a non-loopback bind + // without TLS sends the credential in clear on the wire. + // Shadowsocks and Trojan carry their own encryption, and a + // configured [listeners.tls] terminates TLS in front of the + // whole listener, so neither needs this warning. + if has_auth + && listener.tls.is_none() + && listener + .protocols + .iter() + .any(|protocol| matches!(protocol.as_str(), "http" | "socks4" | "socks5")) + { + warnings.push(ConfigWarning { + path: format!("listeners[{}].tls", i), + message: format!( + "listener '{}' binds to {} with password authentication but \ + no [listeners.tls] — HTTP/SOCKS credentials may be transmitted \ + in clear; configure TLS, bind to loopback, or use a trusted tunnel", + listener.name, listener.bind, + ), + }); + } } } } @@ -39,15 +64,32 @@ pub fn validate_config_security(config: &ConfigFile) -> Vec { // 35.4 / 35.7: Warn about non-loopback admin bind if let Some(ref admin) = config.admin { if let Some(ref bind) = admin.bind { - if !is_loopback_bind(bind) && admin.auth.is_none() { + if !is_loopback_bind(bind) { + // M8: the admin protocol is plaintext HTTP; there is no + // native TLS listener (`eggress-admin` rejects `https://` + // admin client URLs too). Warn regardless of auth so an + // operator never assumes the credential protects the wire. warnings.push(ConfigWarning { path: "admin.bind".to_string(), message: format!( - "admin server binds to {} without authentication — \ - this may expose admin endpoints to untrusted networks", + "admin server binds to {} over plaintext HTTP — Basic/Bearer \ + credentials, status, metrics, and routing topology are exposed to \ + the network; bind to loopback, use a VPN or SSH tunnel, or place a \ + TLS-terminating reverse proxy in front and set [admin] \ + allowed_hosts to the proxy host name", bind, ), }); + if admin.auth.is_none() { + warnings.push(ConfigWarning { + path: "admin.bind".to_string(), + message: format!( + "admin server binds to {} without authentication — \ + this may expose admin endpoints to untrusted networks", + bind, + ), + }); + } } } } @@ -80,10 +122,142 @@ pub fn validate_config_security(config: &ConfigFile) -> Vec { } warn_protocol_aliases(config, &mut warnings); + warn_literal_only_cidr_reject_rules(config, &mut warnings); warnings } +/// Warn when a `reject` rule relies on a private/reserved `destination_cidr` +/// without any host condition. +/// +/// `DestinationCidr` matches literal IP targets only and never resolves a +/// name, so such a rule is not a complete private-network ACL: a hostname that +/// resolves into the range bypasses it, and a request sent through an upstream +/// group is resolved by the upstream. The warning is advisory — rejecting +/// literal private targets on purpose stays valid — and never includes a +/// credential or upstream URI. +fn warn_literal_only_cidr_reject_rules(config: &ConfigFile, warnings: &mut Vec) { + let Some(ref rules) = config.rules else { + return; + }; + for (i, rule) in rules.iter().enumerate() { + if rule.reject.is_none() { + continue; + } + let mut host_condition = rule_has_host_condition(rule); + let mut private_cidr = None; + if let Some(ref expr) = rule.match_expr { + collect_private_destination_cidr( + expr, + &format!("rules[{}].match", i), + 0, + &mut host_condition, + &mut private_cidr, + ); + } + let Some((path, cidr)) = private_cidr else { + continue; + }; + if host_condition { + // The rule already scopes names; an operator combining a CIDR + // with a host condition is not relying on CIDR alone. + continue; + } + warnings.push(ConfigWarning { + path, + message: format!( + "rule '{}' rejects destinations in {} by destination_cidr, but CIDR \ + matching applies to literal IP targets only — a hostname that resolves \ + into {} is not matched by this rule, and a name routed through an \ + upstream group is resolved by the upstream, not locally; add a \ + host_exact/host_suffix/host_regex condition, or use allow_private_egress \ + or a trusted upstream for name-based private-network policy", + rule.id, cidr, cidr, + ), + }); + } +} + +fn rule_has_host_condition(rule: &RuleConfig) -> bool { + rule.host_exact.is_some() || rule.host_suffix.is_some() || rule.host_regex.is_some() +} + +/// Walk a match expression, recording (a) whether any host condition scopes +/// the rule to names and (b) the path and normalized form of the first +/// `destination_cidr` that overlaps a private/reserved range. +fn collect_private_destination_cidr( + expr: &MatchExprConfig, + path: &str, + depth: usize, + host_condition: &mut bool, + private_cidr: &mut Option<(String, String)>, +) { + if depth >= MAX_MATCH_EXPR_DEPTH { + return; + } + match expr { + MatchExprConfig::Composite(composite) => { + if let Some(ref all) = composite.all { + for (i, child) in all.iter().enumerate() { + collect_private_destination_cidr( + child, + &format!("{path}.all[{i}]"), + depth + 1, + host_condition, + private_cidr, + ); + } + } + if let Some(ref any_of) = composite.any_of { + for (i, child) in any_of.iter().enumerate() { + collect_private_destination_cidr( + child, + &format!("{path}.any_of[{i}]"), + depth + 1, + host_condition, + private_cidr, + ); + } + } + if let Some(ref not) = composite.not { + collect_private_destination_cidr( + not, + &format!("{path}.not"), + depth + 1, + host_condition, + private_cidr, + ); + } + } + MatchExprConfig::Leaf(leaf) => { + if leaf.host_exact.is_some() || leaf.host_suffix.is_some() || leaf.host_regex.is_some() + { + *host_condition = true; + } + if private_cidr.is_none() { + if let Some(ref raw) = leaf.destination_cidr { + if let Ok(cidr) = raw.parse::() { + if cidr_touches_reserved_range(&cidr) { + *private_cidr = + Some((format!("{path}.destination_cidr"), cidr.to_string())); + } + } + } + } + } + } +} + +/// True when a CIDR overlaps the private/reserved address space. +/// +/// Both endpoints of the range are classified: a supernet such as +/// `0.0.0.0/0` or `128.0.0.0/1` encloses private/reserved space even though +/// its network address is not itself RFC 1918. IPv4-mapped IPv6 forms are +/// classified as their IPv4 equivalent by the shared helper. +fn cidr_touches_reserved_range(cidr: &ipnet::IpNet) -> bool { + is_reserved_or_private_ip(&cidr.network()) || is_reserved_or_private_ip(&cidr.broadcast()) +} + pub(crate) fn warn_protocol_aliases(config: &ConfigFile, warnings: &mut Vec) { if let Some(ref rules) = config.rules { for (i, rule) in rules.iter().enumerate() { diff --git a/crates/eggress-config/src/validate/tests.rs b/crates/eggress-config/src/validate/tests.rs index ed2dfd6f..a255d3d7 100644 --- a/crates/eggress-config/src/validate/tests.rs +++ b/crates/eggress-config/src/validate/tests.rs @@ -222,6 +222,7 @@ fn warn_non_loopback_admin() { bind: Some("0.0.0.0:9090".to_string()), enabled: None, metrics: None, + allowed_hosts: None, auth: None, pac: None, static_content: None, @@ -250,6 +251,7 @@ fn no_warn_loopback_admin() { bind: Some("127.0.0.1:9090".to_string()), enabled: None, metrics: None, + allowed_hosts: None, auth: None, pac: None, static_content: None, @@ -723,3 +725,390 @@ fn validate_trojan_fallback_valid_address_passes() { result.err() ); } + +// === Auth-without-TLS warning === + +fn authed_listener( + bind: &str, + protocols: &[&str], + tls: Option, + shadowsocks: Option, + trojan: Option, +) -> crate::model::ListenerConfig { + crate::model::ListenerConfig { + name: "proxy".to_string(), + bind: bind.to_string(), + protocols: protocols.iter().map(|p| (*p).to_string()).collect(), + reuse_port: None, + connection_limit: None, + auth: Some(crate::model::AuthConfig { + auth_type: "password".to_string(), + username: Some("proxyuser".to_string()), + password: Some("s3cr3t-value".to_string()), + password_env: None, + }), + udp_enabled: None, + udp: None, + tls, + shadowsocks, + ssr: None, + trojan, + transparent: None, + unix: None, + fixed_target: None, + local_bind: None, + } +} + +fn config_with_listeners(listeners: Vec) -> ConfigFile { + ConfigFile { + version: Some(1), + listeners: Some(listeners), + upstreams: None, + upstream_groups: None, + rules: None, + rules_file: None, + routing: None, + admin: None, + process: None, + timeouts: None, + reverse_servers: None, + reverse_clients: None, + } +} + +#[test] +fn warn_non_loopback_http_auth_without_tls() { + let config = config_with_listeners(vec![authed_listener( + "0.0.0.0:1080", + &["http"], + None, + None, + None, + )]); + let warnings = validate_config_security(&config); + let warning = warnings + .iter() + .find(|w| w.path == "listeners[0].tls") + .expect("auth without TLS must warn"); + assert!(warning.message.contains("0.0.0.0:1080")); + assert!(warning.message.contains("[listeners.tls]")); + // The warning must never echo the configured credential. + assert!(!warning.message.contains("proxyuser")); + assert!(!warning.message.contains("s3cr3t-value")); +} + +#[test] +fn warn_non_loopback_socks4_and_socks5_auth_without_tls() { + for protocol in ["socks4", "socks5"] { + let config = config_with_listeners(vec![authed_listener( + "0.0.0.0:1080", + &[protocol], + None, + None, + None, + )]); + let warnings = validate_config_security(&config); + assert!( + warnings.iter().any(|w| w.path == "listeners[0].tls"), + "protocol {protocol} with auth and no TLS must warn" + ); + } +} + +#[test] +fn no_warn_authed_http_with_tls() { + let config = config_with_listeners(vec![authed_listener( + "0.0.0.0:1080", + &["http"], + Some(crate::model::ListenerTlsConfig { + cert: "/path/cert.pem".to_string(), + key: "/path/key.pem".to_string(), + alpn: None, + }), + None, + None, + )]); + let warnings = validate_config_security(&config); + assert!( + warnings.is_empty(), + "TLS listener must not warn: {warnings:?}" + ); +} + +#[test] +fn no_warn_authed_shadowsocks_without_tls() { + let config = config_with_listeners(vec![authed_listener( + "0.0.0.0:8388", + &["shadowsocks"], + None, + Some(crate::model::ShadowsocksListenerConfig { + method: "aes-256-gcm".to_string(), + password: "ss-password".to_string(), + auth_prefix: None, + plugins: Vec::new(), + }), + None, + )]); + let warnings = validate_config_security(&config); + assert!( + warnings.is_empty(), + "Shadowsocks carries its own encryption: {warnings:?}" + ); +} + +#[test] +fn no_warn_authed_trojan_protocol_without_tls() { + // Trojan requires TLS structurally (a separate validation error), so it + // must never produce this warning. + let config = config_with_listeners(vec![authed_listener( + "0.0.0.0:443", + &["trojan"], + None, + None, + Some(crate::model::ListenerTrojanConfig { + password: "trojan-password".to_string(), + fallback: None, + }), + )]); + let warnings = validate_config_security(&config); + assert!( + warnings.is_empty(), + "Trojan must not produce the HTTP/SOCKS auth-without-TLS warning: {warnings:?}" + ); +} + +#[test] +fn no_warn_loopback_http_auth_without_tls() { + let config = config_with_listeners(vec![authed_listener( + "127.0.0.1:1080", + &["http"], + None, + None, + None, + )]); + let warnings = validate_config_security(&config); + assert!( + warnings.is_empty(), + "loopback bind must not warn: {warnings:?}" + ); +} + +// === Literal-IP-only CIDR warning === + +fn warnings_for(rules_toml: &str) -> Vec { + let config: ConfigFile = toml::from_str(rules_toml).expect("test config must parse"); + validate_config_security(&config) +} + +#[test] +fn warn_private_destination_cidr_reject_rule_without_host_condition() { + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "block-private" +reject = "blocked" + +[rules.match] +any_of = [ + { destination_cidr = "10.0.0.0/8" }, + { destination_cidr = "192.168.0.0/16" }, +] +"#, + ); + let warning = warnings + .iter() + .find(|w| w.path.starts_with("rules[0]")) + .unwrap_or_else(|| panic!("private CIDR reject rule must warn: {warnings:?}")); + assert_eq!(warning.path, "rules[0].match.any_of[0].destination_cidr"); + assert!(warning.message.contains("10.0.0.0/8")); + assert!(warning.message.contains("literal IP targets only")); + assert!(warning.message.contains("resolved by the upstream")); + assert!(warning.message.contains("allow_private_egress")); +} + +#[test] +fn warn_private_destination_cidr_inside_negation() { + // A negated CIDR is still literal-only: `not { destination_cidr }` cannot + // see a name that resolves into the range. + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "block-non-rfc1918" +reject = "access-denied" + +[rules.match] +not = { destination_cidr = "10.0.0.0/8" } +"#, + ); + assert!( + warnings + .iter() + .any(|w| w.path == "rules[0].match.not.destination_cidr"), + "negated private CIDR must warn: {warnings:?}" + ); +} + +#[test] +fn warn_private_ipv4_mapped_destination_cidr() { + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "block-mapped-private" +reject = "blocked" + +[rules.match] +destination_cidr = "::ffff:10.0.0.0/104" +"#, + ); + let warning = warnings + .iter() + .find(|w| w.path.starts_with("rules[0]")) + .unwrap_or_else(|| panic!("mapped private CIDR must warn: {warnings:?}")); + assert!(warning.message.contains("::ffff:10.0.0.0/104")); +} + +#[test] +fn no_warn_private_cidr_when_host_condition_present() { + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "block-internal-http" +reject = "blocked" + +[rules.match] +all = [ + { host_suffix = "internal.example" }, + { destination_cidr = "10.0.0.0/8" }, +] +"#, + ); + assert!( + warnings.is_empty(), + "a rule that also scopes names must not warn: {warnings:?}" + ); +} + +#[test] +fn no_warn_private_cidr_when_shortcut_host_condition_present() { + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "block-internal-literal" +host_regex = "^10\\." +reject = "blocked" + +[rules.match] +destination_cidr = "10.0.0.0/8" +"#, + ); + assert!( + warnings.is_empty(), + "a shortcut host condition must suppress the warning: {warnings:?}" + ); +} + +#[test] +fn no_warn_public_destination_cidr_reject_rule() { + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "block-doc-range" +reject = "blocked" + +[rules.match] +destination_cidr = "8.8.8.0/24" +"#, + ); + assert!( + warnings.is_empty(), + "a public range is not private-network policy: {warnings:?}" + ); +} + +#[test] +fn no_warn_private_cidr_for_non_reject_action() { + let warnings = warnings_for( + r#" +version = 1 + +[[rules]] +id = "direct-private" +direct = true + +[rules.match] +destination_cidr = "10.0.0.0/8" +"#, + ); + assert!( + warnings.is_empty(), + "only reject rules claim to block private networks: {warnings:?}" + ); +} + +#[test] +fn cidr_warning_does_not_echo_credentials_or_upstream_uri() { + let warnings = warnings_for( + r#" +version = 1 + +[[upstreams]] +id = "egress" +uri = "socks5://user:sup3rsecret@203.0.113.10:1080" + +[[rules]] +id = "block-private" +reject = "blocked" + +[rules.match] +destination_cidr = "10.0.0.0/8" +"#, + ); + let warning = warnings + .iter() + .find(|w| w.path.starts_with("rules[0]")) + .expect("private CIDR reject rule must warn"); + assert!(!warning.message.contains("sup3rsecret")); + assert!(!warning.message.contains("203.0.113.10")); + for warning in &warnings { + assert!(!warning.message.contains("sup3rsecret")); + } +} + +#[test] +fn warn_plaintext_non_loopback_admin_even_with_auth() { + let warnings = warnings_for( + r#" +version = 1 + +[admin] +bind = "0.0.0.0:9090" + +[admin.auth] +bearer_token = "adm1n-s3cret-token" +"#, + ); + let warning = warnings + .iter() + .find(|w| w.message.contains("plaintext HTTP")) + .unwrap_or_else(|| panic!("non-loopback admin must warn: {warnings:?}")); + assert_eq!(warning.path, "admin.bind"); + assert!(warning.message.contains("0.0.0.0:9090")); + assert!(warning.message.contains("allowed_hosts")); + assert!(warning.message.contains("VPN")); + for warning in &warnings { + assert!(!warning.message.contains("adm1n-s3cret-token")); + } +} diff --git a/crates/eggress-core/src/connector.rs b/crates/eggress-core/src/connector.rs index b21a9a8b..17fcbb31 100644 --- a/crates/eggress-core/src/connector.rs +++ b/crates/eggress-core/src/connector.rs @@ -20,14 +20,19 @@ use crate::{BoxStream, ConnectError, TargetAddr, TargetHost}; /// /// Rejected ranges: /// - IPv4: loopback (127.0.0.0/8), link-local (169.254.0.0/16), -/// private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), unspecified (0.0.0.0), +/// private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), +/// carrier-grade NAT (100.64.0.0/10), unspecified (0.0.0.0), /// broadcast (255.255.255.255), multicast (224.0.0.0/4), /// documentation (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24), /// benchmarking (198.18.0.0/15), reserved future (240.0.0.0/4), /// this-network (0.0.0.0/8) /// - IPv6: loopback (::1), link-local (fe80::/10), unique-local (fc00::/7), /// unspecified (::), multicast (ff00::/8), -/// documentation (2001:db8::/32), discard prefix (0100::/64) +/// documentation (2001:db8::/32), discard prefix (0100::/64), +/// NAT64 (64:ff9b::/96), 6to4 (2002::/16), Teredo (2001::/32), +/// benchmarking (2001:2::/48), ORCHID (2001:10::/28, 2001:20::/28) +/// +/// IPv4-mapped IPv6 addresses are classified as their embedded IPv4 address. pub fn is_reserved_or_private_ip(ip: &IpAddr) -> bool { match ip { IpAddr::V4(v4) => { @@ -37,6 +42,7 @@ pub fn is_reserved_or_private_ip(ip: &IpAddr) -> bool { || v4.is_unspecified() || v4.is_multicast() || v4.is_broadcast() + || is_v4_cgnat(v4) || is_v4_documentation(v4) || is_v4_benchmarking(v4) || is_v4_reserved(v4) @@ -56,6 +62,11 @@ pub fn is_reserved_or_private_ip(ip: &IpAddr) -> bool { || is_unicast_link_local_v6(v6) || is_unique_local_v6(v6) || is_v6_discard_prefix(v6) + || is_v6_nat64(v6) + || is_v6_6to4(v6) + || is_v6_teredo(v6) + || is_v6_benchmarking(v6) + || is_v6_orchid(v6) } } } @@ -83,6 +94,14 @@ fn is_v4_this_network(ip: &std::net::Ipv4Addr) -> bool { ip.octets()[0] == 0 } +/// Check if an IPv4 address is in the 100.64.0.0/10 carrier-grade NAT range +/// (RFC 6598). These are not reachable from the public Internet and are +/// commonly used for provider or overlay-network addressing. +fn is_v4_cgnat(ip: &std::net::Ipv4Addr) -> bool { + let octets = ip.octets(); + octets[0] == 100 && (octets[1] & 0xc0) == 0x40 +} + /// Check if an IPv4 address is in any of the documentation ranges /// (TEST-NET-1: 192.0.2.0/24, TEST-NET-2: 198.51.100.0/24, /// TEST-NET-3: 203.0.113.0/24, 192.88.99.0/24). @@ -113,6 +132,53 @@ fn is_v6_documentation(ip: &Ipv6Addr) -> bool { octets[0] == 0x20 && octets[1] == 0x01 && octets[2] == 0x0d && octets[3] == 0xb8 } +/// Check if an IPv6 address is in the 64:ff9b::/96 well-known NAT64 prefix +/// (RFC 6052), which embeds an IPv4 destination in its last four bytes. +fn is_v6_nat64(ip: &Ipv6Addr) -> bool { + let octets = ip.octets(); + octets[0] == 0x00 + && octets[1] == 0x64 + && octets[2] == 0xff + && octets[3] == 0x9b + && octets[4..12].iter().all(|byte| *byte == 0) +} + +/// Check if an IPv6 address is in the 2002::/16 6to4 range (RFC 3056), which +/// embeds an IPv4 address in bits 16-47 of a publicly routed prefix. +fn is_v6_6to4(ip: &Ipv6Addr) -> bool { + let octets = ip.octets(); + octets[0] == 0x20 && octets[1] == 0x02 +} + +/// Check if an IPv6 address is in the 2001::/32 Teredo range (RFC 4380). +fn is_v6_teredo(ip: &Ipv6Addr) -> bool { + let octets = ip.octets(); + octets[0] == 0x20 && octets[1] == 0x01 && octets[2] == 0x00 && octets[3] == 0x00 +} + +/// Check if an IPv6 address is in the 2001:2::/48 benchmarking range +/// (RFC 5180). +fn is_v6_benchmarking(ip: &Ipv6Addr) -> bool { + let octets = ip.octets(); + octets[0] == 0x20 + && octets[1] == 0x01 + && octets[2] == 0x00 + && octets[3] == 0x02 + && octets[4] == 0x00 + && octets[5] == 0x00 +} + +/// Check if an IPv6 address is in an ORCHID range: 2001:10::/28 (RFC 4843, +/// deprecated) or 2001:20::/28 (ORCHIDv2, RFC 7343). ORCHIDs are +/// cryptographically generated identifiers, not routable endpoints. +fn is_v6_orchid(ip: &Ipv6Addr) -> bool { + let octets = ip.octets(); + if octets[0] != 0x20 || octets[1] != 0x01 || octets[2] != 0x00 { + return false; + } + matches!(octets[3] & 0xf0, 0x10 | 0x20) +} + /// Check if a resolved IP address represents a DNS rebinding risk. pub fn is_dns_rebinding_risk(ip: &IpAddr) -> bool { is_reserved_or_private_ip(ip) @@ -603,6 +669,71 @@ mod tests { assert!(is_reserved_or_private_ip(&IpAddr::V6(ip))); } + /// CGNAT, NAT64, 6to4, Teredo, and selected IETF special-purpose ranges + /// must classify as non-public so the DNS-rebinding and UDP private-egress + /// guards cannot be bypassed by a domain that resolves into them. + #[test] + fn reserved_special_purpose_ranges_table() { + let reserved = [ + // IPv4 CGNAT 100.64.0.0/10 (RFC 6598) including both edges. + "100.64.0.0", + "100.64.0.1", + "100.127.255.254", + // IPv6 NAT64 well-known prefix 64:ff9b::/96 (RFC 6052). + "64:ff9b::1", + "64:ff9b::808:808", + // IPv6 6to4 2002::/16 (RFC 3056). + "2002::1", + "2002:808:808::1", + // IPv6 Teredo 2001::/32 (RFC 4380). + "2001::1", + "2001:0:4136:e378:8000:63bf:3fff:fdd2", + // IPv6 benchmarking 2001:2::/48 (RFC 5180). + "2001:2::1", + "2001:2:0:ffff::1", + // ORCHID 2001:10::/28 (RFC 4843) and ORCHIDv2 2001:20::/28 (RFC 7343). + "2001:10::1", + "2001:1f::1", + "2001:20::1", + "2001:2f::1", + // IPv4-mapped forms of the new IPv4 range. + "::ffff:100.64.0.1", + "::ffff:100.127.255.254", + ]; + for text in reserved { + let ip = text + .parse::() + .unwrap_or_else(|_| panic!("bad fixture: {text}")); + assert!( + is_reserved_or_private_ip(&ip), + "{text} must be classified as reserved/private" + ); + } + + // Neighbouring public ranges must not be over-classified. + let public = [ + "100.63.255.255", + "100.128.0.0", + "8.8.8.8", + "1.1.1.1", + "2001:1::1", + "2001:3::1", + "2001:30::1", + "2003::1", + "2606:4700:4700::1111", + "::ffff:8.8.8.8", + ]; + for text in public { + let ip = text + .parse::() + .unwrap_or_else(|_| panic!("bad fixture: {text}")); + assert!( + !is_reserved_or_private_ip(&ip), + "{text} must remain a permitted public destination" + ); + } + } + #[tokio::test] async fn reject_domain_resolving_to_loopback() { let connector = DirectConnector; @@ -626,14 +757,26 @@ mod tests { async fn direct_connect_falls_back_to_next_resolved_address() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let good_addr = listener.local_addr().unwrap(); - let bad_addr = SocketAddr::new(good_addr.ip(), good_addr.port() + 1); + // Bind-and-release a second port instead of using `good_addr.port() + 1`: + // the adjacent port can be held by any other test in this binary that + // binds an ephemeral listener, which made the first connect succeed to + // the wrong socket and left the `accept` below waiting forever. + let bad_addr = { + let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = probe.local_addr().unwrap(); + drop(probe); + addr + }; let accept = tokio::spawn(async move { listener.accept().await.unwrap() }); let stream = connect_to_addrs(&[bad_addr, good_addr], None) .await .expect("second resolved address should be attempted"); drop(stream); - accept.await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(10), accept) + .await + .expect("listener should accept the fallback connection") + .unwrap(); } #[tokio::test] diff --git a/crates/eggress-pproxy-compat/src/args.rs b/crates/eggress-pproxy-compat/src/args.rs index 62044886..58178e5b 100644 --- a/crates/eggress-pproxy-compat/src/args.rs +++ b/crates/eggress-pproxy-compat/src/args.rs @@ -552,6 +552,25 @@ impl PproxyArgs { .unwrap_or_else(|| Duration::from_secs(86_400 * 30)) } + /// Startup advisory describing the pproxy-compatible auth-reuse cache. + /// + /// Callers emit this once before serving, and only when at least one + /// translated listener actually carries `[listeners.auth]`. The text names + /// the pproxy default (30 days / `2592000` s), the source-IP-only key, the + /// cross-listener sharing, and the escape hatches. It never includes a + /// listener URI or credential, so it is safe at the default log level. + pub fn auth_reuse_advisory(&self) -> String { + format!( + "pproxy-compatible authentication reuse is active for listener credentials: \ + the reuse cache is process-global, keyed only by source IP, and shared across \ + credentialed compatibility listeners (bounded, monotonic expiry). Reuse interval: \ + 2592000s (30 days) when --auth is omitted; effective for this process: {}s. \ + Set --auth 0 to disable practical reuse, or use native [listeners.auth] for \ + per-connection checks with no reuse cache.", + self.effective_auth_timeout().as_secs() + ) + } + /// Default tracing log level chosen from `-d` and `-v` verbosity flags. /// /// Resolution order (highest precedence first): @@ -1512,3 +1531,51 @@ mod tests { } } } + +#[cfg(test)] +mod auth_reuse_advisory_tests { + use super::*; + + #[test] + fn advisory_names_default_scope_and_escape_hatches() { + let args = PproxyArgs::parse(&["-l".into(), "socks5://127.0.0.1:1080".into()]).unwrap(); + let advisory = args.auth_reuse_advisory(); + assert!(advisory.contains("30 days"), "{advisory}"); + assert!(advisory.contains("2592000"), "{advisory}"); + assert!(advisory.contains("source IP"), "{advisory}"); + assert!( + advisory.contains("shared across"), + "must name cross-listener sharing: {advisory}" + ); + assert!(advisory.contains("process-global"), "{advisory}"); + assert!(advisory.contains("--auth 0"), "{advisory}"); + assert!(advisory.contains("[listeners.auth]"), "{advisory}"); + assert!( + advisory.contains("effective for this process: 2592000s"), + "omitted --auth must report the 30-day default: {advisory}" + ); + // The advisory is static text: it never echoes listener URIs or + // credentials. + assert!(!advisory.contains("socks5://"), "{advisory}"); + assert!(!advisory.contains(":1080"), "{advisory}"); + } + + #[test] + fn advisory_reports_explicit_auth_interval() { + let args = PproxyArgs::parse(&[ + "-l".into(), + "http://user:secret@127.0.0.1:8080".into(), + "--auth".into(), + "0".into(), + ]) + .unwrap(); + let advisory = args.auth_reuse_advisory(); + assert!( + advisory.contains("effective for this process: 0s"), + "--auth 0 must be reported as the effective interval: {advisory}" + ); + assert!(!advisory.contains("secret"), "{advisory}"); + assert!(!advisory.contains("user"), "{advisory}"); + assert!(!advisory.contains("127.0.0.1"), "{advisory}"); + } +} diff --git a/crates/eggress-pproxy-compat/src/lib.rs b/crates/eggress-pproxy-compat/src/lib.rs index 972b3e81..213fddf5 100644 --- a/crates/eggress-pproxy-compat/src/lib.rs +++ b/crates/eggress-pproxy-compat/src/lib.rs @@ -26,7 +26,7 @@ pub use translate::{ translate_pproxy_args_to_native, translate_to_runtime_config, CombinedTranslation, NativeTranslation, }; -pub use uri::{PproxyChain, PproxyPluginSpec, PproxyUri}; +pub use uri::{redact_argv_for_annotation, PproxyChain, PproxyPluginSpec, PproxyUri}; pub use warnings::{CompatWarning, TranslationOutput, UnsupportedFeature}; #[cfg(test)] diff --git a/crates/eggress-pproxy-compat/src/translate/intermediates.rs b/crates/eggress-pproxy-compat/src/translate/intermediates.rs index 6bacda3d..24baaf8b 100644 --- a/crates/eggress-pproxy-compat/src/translate/intermediates.rs +++ b/crates/eggress-pproxy-compat/src/translate/intermediates.rs @@ -88,7 +88,8 @@ pub(crate) fn build_intermediates( output = output.with_warning( "auth-timeout", format!( - "--auth {}s enables pproxy-compatible source-IP authentication reuse", + "--auth {}s sets the pproxy-compatible source-IP re-authentication reuse interval; \ + listener credentials themselves come from the listener URI", auth.as_secs() ), ); @@ -852,13 +853,16 @@ pub(crate) fn build_intermediates( let mut udp_upstream_ids = Vec::new(); let mut udp_routes: Vec = Vec::new(); for (idx, remote_str) in udp_remotes.iter().enumerate() { + // Redact the raw `-ur` value before it reaches a diagnostic: UDP + // remotes carry socks5/ss credentials and the error is user-visible. + let redacted_remote = crate::uri::redact_uri_for_error(remote_str); let remote_chain = crate::uri::parse_pproxy_chain(remote_str).map_err(|e| CompatError::InvalidArgs { - message: format!("invalid UDP remote URI '{}': {}", remote_str, e), + message: format!("invalid UDP remote URI '{redacted_remote}': {e}"), })?; let Some(remote_uri) = remote_chain.hops.first() else { return Err(CompatError::InvalidArgs { - message: format!("invalid UDP remote URI '{remote_str}': no proxy hop"), + message: format!("invalid UDP remote URI '{redacted_remote}': no proxy hop"), }); }; diff --git a/crates/eggress-pproxy-compat/src/translate/model.rs b/crates/eggress-pproxy-compat/src/translate/model.rs index 664ccb4e..8d7393ad 100644 --- a/crates/eggress-pproxy-compat/src/translate/model.rs +++ b/crates/eggress-pproxy-compat/src/translate/model.rs @@ -156,7 +156,7 @@ pub(crate) struct ConfigToml { pub(crate) admin: Option, } -#[derive(Debug, serde::Serialize, Clone)] +#[derive(serde::Serialize, Clone)] pub(crate) struct ReverseServerToml { pub(crate) id: String, pub(crate) control_bind: String, @@ -168,7 +168,39 @@ pub(crate) struct ReverseServerToml { pub(crate) pproxy_compat: bool, } -#[derive(Debug, serde::Serialize, Clone)] +/// Placeholder used by custom `Debug` impls for secret-bearing fields. +/// +/// Prints `****` (no quotes) so `Some(RedactedSecret)` renders as +/// `Some(****)`. Serialization is unaffected: the real value is only +/// replaced on the diagnostic path. +struct RedactedSecret; + +impl std::fmt::Debug for RedactedSecret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("****") + } +} + +// Hand-written `Debug`: the derived version would print `auth_password` +// verbatim. Serialization keeps the real credential because generated TOML +// must stay runnable. +impl std::fmt::Debug for ReverseServerToml { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ReverseServerToml") + .field("id", &self.id) + .field("control_bind", &self.control_bind) + .field("external_bind", &self.external_bind) + .field("auth_username", &self.auth_username) + .field( + "auth_password", + &self.auth_password.as_ref().map(|_| RedactedSecret), + ) + .field("pproxy_compat", &self.pproxy_compat) + .finish() + } +} + +#[derive(serde::Serialize, Clone)] pub(crate) struct ReverseClientToml { pub(crate) id: String, pub(crate) server_addr: String, @@ -183,6 +215,28 @@ pub(crate) struct ReverseClientToml { pub(crate) pproxy_compat: bool, } +// Same rationale as `ReverseServerToml`: `server_uri` and `auth_password` +// are secret-bearing, so `Debug` must never print the raw values. +impl std::fmt::Debug for ReverseClientToml { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ReverseClientToml") + .field("id", &self.id) + .field("server_addr", &self.server_addr) + .field( + "server_uri", + &self.server_uri.as_ref().map(|_| RedactedSecret), + ) + .field("auth_username", &self.auth_username) + .field( + "auth_password", + &self.auth_password.as_ref().map(|_| RedactedSecret), + ) + .field("parallel_connections", &self.parallel_connections) + .field("pproxy_compat", &self.pproxy_compat) + .finish() + } +} + #[derive(Debug, serde::Serialize, Clone)] pub(crate) struct HealthToml { pub(crate) interval: String, diff --git a/crates/eggress-pproxy-compat/src/translate/native.rs b/crates/eggress-pproxy-compat/src/translate/native.rs index 746d3658..a0d14c25 100644 --- a/crates/eggress-pproxy-compat/src/translate/native.rs +++ b/crates/eggress-pproxy-compat/src/translate/native.rs @@ -441,6 +441,7 @@ pub(crate) fn intermediates_to_config_file( bind: None, enabled: None, metrics: None, + allowed_hosts: None, auth: None, pac: Some(model::PacConfigToml { path: intermediates.pac_path.clone(), diff --git a/crates/eggress-pproxy-compat/src/translate/tests.rs b/crates/eggress-pproxy-compat/src/translate/tests.rs index 2d9edb68..30334359 100644 --- a/crates/eggress-pproxy-compat/src/translate/tests.rs +++ b/crates/eggress-pproxy-compat/src/translate/tests.rs @@ -1278,3 +1278,99 @@ fn test_translate_trojan_upstream_still_works() { ); assert!(output.toml.contains("trojan://secret@proxy.example:443")); } + +#[test] +fn udp_remote_errors_redact_credentials() { + // Regression: the raw `-ur` value used to be interpolated into the + // error, leaking socks5/ss credentials into user-visible diagnostics. + for (remote, expected_redacted) in [ + ( + "socks5://user:pass@127.0.0.1:notaport", + "socks5://****:****@127.0.0.1:notaport", + ), + ("socks5://user:p@ss@[::1", "socks5://****:****@[::1"), + ("tunnel://user:pass@{bad}", "tunnel://****:****@{bad}"), + ] { + let args = PproxyArgs::parse(&[ + "-l".into(), + "socks5://127.0.0.1:1080".into(), + "-ul".into(), + ":1081".into(), + "-ur".into(), + remote.into(), + ]) + .unwrap(); + let error = translate_pproxy_args(&args).unwrap_err(); + let message = error.to_string(); + assert!( + message.contains(expected_redacted), + "expected redacted remote in '{message}'" + ); + assert!( + !message.contains("pass"), + "error leaked a password: {message}" + ); + assert!( + !message.contains("user:"), + "error leaked a username: {message}" + ); + } +} + +#[test] +fn udp_remote_error_redacts_percent_and_bracket_passwords() { + for remote in [ + "socks5://user:p%40ss@127.0.0.1:0:1", + "socks5://user:p[a]ss@127.0.0.1:0:1", + ] { + let args = PproxyArgs::parse(&[ + "-l".into(), + "socks5://127.0.0.1:1080".into(), + "-ul".into(), + ":1081".into(), + "-ur".into(), + remote.into(), + ]) + .unwrap(); + let message = translate_pproxy_args(&args).unwrap_err().to_string(); + assert!(!message.contains("p%40ss"), "leaked password: {message}"); + assert!(!message.contains("p[a]ss"), "leaked password: {message}"); + assert!( + message.contains("****:****@127.0.0.1"), + "expected redacted remote, got: {message}" + ); + } +} + +#[test] +fn compat_ir_debug_redacts_reverse_auth_password() { + use super::model::{ReverseClientToml, ReverseServerToml}; + + let server = ReverseServerToml { + id: "rs".to_string(), + control_bind: "0.0.0.0:9443".to_string(), + external_bind: "0.0.0.0:9443".to_string(), + auth_username: Some("tunnel".to_string()), + auth_password: Some("s3cret-server".to_string()), + pproxy_compat: true, + }; + let debug = format!("{server:?}"); + assert!(debug.contains("auth_password: Some(****)"), "{debug}"); + assert!(!debug.contains("s3cret-server"), "{debug}"); + + let client = ReverseClientToml { + id: "rc".to_string(), + server_addr: "proxy.example:9443".to_string(), + server_uri: Some("socks5://tunnel:s3cret-client@proxy.example:9443".to_string()), + auth_username: Some("tunnel".to_string()), + auth_password: Some("s3cret-client".to_string()), + parallel_connections: Some(2), + pproxy_compat: true, + }; + let debug = format!("{client:?}"); + assert!(debug.contains("auth_password: Some(****)"), "{debug}"); + assert!(!debug.contains("s3cret-client"), "{debug}"); + // Serialization still carries the real value (generated TOML must run). + let json = serde_json::to_string(&client).unwrap(); + assert!(json.contains("s3cret-client"), "{json}"); +} diff --git a/crates/eggress-pproxy-compat/src/uri.rs b/crates/eggress-pproxy-compat/src/uri.rs index f40372e0..a7820a64 100644 --- a/crates/eggress-pproxy-compat/src/uri.rs +++ b/crates/eggress-pproxy-compat/src/uri.rs @@ -224,22 +224,83 @@ fn redact_unix_path(path: &str) -> String { } } -/// Redact secret-bearing URI input before embedding it in error messages. -fn redact_uri_for_error(uri: &str) -> String { - // Strip userinfo (`user:pass@`) and fragment auth; keep the remainder for - // diagnostics. Bound length so huge inputs cannot blow up logs. - // Uses the canonical bracket-aware last-`@` separator so a `@` inside - // the password does not leak a fragment into the redacted output. - let mut out = uri.to_string(); - if let Some(scheme_end) = out.find("://") { +/// Placeholder for a redacted userinfo span. +/// +/// Passwords are indistinguishable from usernames once redacted, but keeping +/// the `user:pass` shape signals that both parts were present. +fn userinfo_placeholder(userinfo: &str) -> &'static str { + if userinfo.contains(':') { + "****:****@" + } else { + "****@" + } +} + +/// Replace userinfo (`user:pass@`) with a placeholder on every `scheme://` hop. +/// +/// Hop-aware so chained input (`socks5://u:p@a__http://u:p@b`) redacts both +/// hops instead of collapsing the first one. The scan is bounded to each +/// hop's authority so an `@` in a query/path is never treated as userinfo. +/// Uses the canonical bracket-aware last-`@` separator so an `@` inside the +/// password stays inside the redacted span; an unmatched `[`/`{` falls back +/// to the last raw `@` so malformed input can never echo credentials. +fn redact_userinfo_in_hops(input: &str) -> String { + let mut out = String::with_capacity(input.len().min(288)); + let mut rest = input; + loop { + let Some(scheme_end) = rest.find("://") else { + out.push_str(rest); + break; + }; let after = scheme_end + 3; - if let Some(at) = uri_syntax::find_userinfo_separator(&out[after..]) { - out.replace_range(after..after + at + 1, "****:****@"); - } + out.push_str(&rest[..after]); + let remainder = &rest[after..]; + // Authority ends at the first path/query/fragment delimiter. + let hard_end = remainder.find(['/', '?', '#']).unwrap_or(remainder.len()); + let authority = &remainder[..hard_end]; + let Some(at) = + uri_syntax::find_userinfo_separator(authority).or_else(|| authority.rfind('@')) + else { + // No credentials in this hop; re-emit the authority verbatim. + out.push_str(authority); + rest = &remainder[hard_end..]; + continue; + }; + // A `__` after the userinfo separator starts the next chained hop + // (or is part of a hostname). Splitting there is safe because the + // host/tail is re-emitted verbatim, and it lets the next iteration + // redact the following hop's userinfo. + let host_end = authority[at + 1..] + .find("__") + .map(|idx| at + 1 + idx) + .unwrap_or(authority.len()); + out.push_str(userinfo_placeholder(&authority[..at])); + out.push_str(&authority[at + 1..host_end]); + rest = &remainder[host_end..]; } - if let Some((head, _)) = out.split_once('#') { - out = format!("{head}#****"); + out +} + +/// Redact credentials in a single URI token. +/// +/// Userinfo becomes `****:****@` / `****@`; fragment auth (`#user:pass`) +/// becomes `#****` and everything after the first `#` is dropped so a +/// fragment can never leak. Everything else (scheme, host, port, query, +/// `__` chain separators) is preserved byte-for-byte. +pub(crate) fn redact_uri_token(token: &str) -> String { + let mut out = redact_userinfo_in_hops(token); + if let Some(hash) = out.find('#') { + out.truncate(hash); + out.push_str("#****"); } + out +} + +/// Redact secret-bearing URI input before embedding it in error messages. +pub(crate) fn redact_uri_for_error(uri: &str) -> String { + // Strip userinfo (`user:pass@`) and fragment auth; keep the remainder for + // diagnostics. Bound length so huge inputs cannot blow up logs. + let mut out = redact_uri_token(uri); if out.len() > 256 { out.truncate(256); out.push_str("..."); @@ -247,6 +308,25 @@ fn redact_uri_for_error(uri: &str) -> String { out } +/// Redact credentials from a raw compatibility argv slice for annotation. +/// +/// Flags and non-URI tokens are preserved verbatim. Tokens containing a +/// `scheme://` hop are redacted per [`redact_uri_token`], so a reproduction +/// line keeps its flags, `__` chain separators, and query strings while +/// never echoing a username, password, or fragment credential. +pub fn redact_argv_for_annotation(args: &[String]) -> String { + args.iter() + .map(|arg| { + if arg.contains("://") { + redact_uri_token(arg) + } else { + arg.clone() + } + }) + .collect::>() + .join(" ") +} + /// Shared host formatting (bracket IPv6 literals). /// /// Delegates to [`eggress_uri::syntax::format_host`] so native and @@ -1539,4 +1619,94 @@ mod tests { Some("example.com:443") ); } + + #[test] + fn test_redact_uri_for_error_hides_credentials() { + assert_eq!( + redact_uri_for_error("socks5://user:pass@127.0.0.1:1080"), + "socks5://****:****@127.0.0.1:1080" + ); + // Last-`@` separator keeps a password containing `@` inside the span. + assert_eq!( + redact_uri_for_error("http://user:p@ss@proxy:8080"), + "http://****:****@proxy:8080" + ); + // Bracketed password + IPv6 host. + assert_eq!( + redact_uri_for_error("socks5://user:p[a]ss@[::1]:1080"), + "socks5://****:****@[::1]:1080" + ); + // Unmatched bracket falls back to the last raw `@` (never leaks). + assert_eq!( + redact_uri_for_error("socks5://user:p[a@host:1080"), + "socks5://****:****@host:1080" + ); + // Percent-escaped delimiter bytes stay inside the redacted span. + assert_eq!( + redact_uri_for_error("http://us%40er:pa%3Ass@proxy:8080"), + "http://****:****@proxy:8080" + ); + // Username-only userinfo keeps the short placeholder. + assert_eq!( + redact_uri_for_error("socks5://user@proxy:1080"), + "socks5://****@proxy:1080" + ); + // Chained hops and query strings survive redaction. + assert_eq!( + redact_uri_for_error("socks5://u:p@a:1__http://x:y@b:2?rule=a__b"), + "socks5://****:****@a:1__http://****:****@b:2?rule=a__b" + ); + // Fragment auth is replaced wholesale. + assert_eq!( + redact_uri_for_error("http://proxy:8080#user:pass"), + "http://proxy:8080#****" + ); + // Non-credential and non-URI input are unchanged. + assert_eq!(redact_uri_for_error("file:///tmp/x"), "file:///tmp/x"); + assert_eq!(redact_uri_for_error("not a uri"), "not a uri"); + assert_eq!( + redact_uri_for_error("socks5://[::1]:1080"), + "socks5://[::1]:1080" + ); + // Oversized input is bounded and still hides the secret. + let long = format!("socks5://user:{}@host:1080", "s".repeat(400)); + let redacted = redact_uri_for_error(&long); + assert!(redacted.len() <= 259, "redaction must bound length"); + assert!(!redacted.contains(&"s".repeat(16))); + } + + #[test] + fn test_redact_argv_for_annotation_preserves_flags_and_chains() { + let args: Vec = [ + "-l", + "socks5://user:pass@127.0.0.1:1080", + "-r", + "http://user:pass@a:8080__socks5://b:1080?rule=x__y", + "--auth", + "30", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let redacted = redact_argv_for_annotation(&args); + assert_eq!( + redacted, + "-l socks5://****:****@127.0.0.1:1080 \ + -r http://****:****@a:8080__socks5://b:1080?rule=x__y --auth 30" + ); + assert!(!redacted.contains("user")); + assert!(!redacted.contains("pass")); + } + + #[test] + fn test_redact_argv_for_annotation_username_only_and_fragments() { + let args: Vec = ["-l", "socks5://user@proxy:1080#u:p", "-r", "direct://"] + .iter() + .map(|s| s.to_string()) + .collect(); + let redacted = redact_argv_for_annotation(&args); + assert_eq!(redacted, "-l socks5://****@proxy:1080#**** -r direct://"); + assert!(!redacted.contains("user")); + assert!(!redacted.contains("u:p")); + } } diff --git a/crates/eggress-routing/src/lib.rs b/crates/eggress-routing/src/lib.rs index ac10ce67..fb5ffc03 100644 --- a/crates/eggress-routing/src/lib.rs +++ b/crates/eggress-routing/src/lib.rs @@ -202,6 +202,72 @@ mod tests { assert!(!MatchExpr::DestinationCidr(cidr).matches(&req)); } + #[test] + fn ipv4_mapped_destination_matches_ipv4_cidr() { + // `ipnet` returns false across address families, so a dual-stack + // client sending the mapped form must still be matched against the + // IPv4 rule. + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let mapped: IpAddr = "::ffff:10.0.0.1".parse().unwrap(); + assert!(matches!(mapped, IpAddr::V6(_)), "literal must stay mapped"); + let target = target_ip(mapped, 80); + let req = make_request(&target, None, "l", ProtocolId::Http, &ANON); + assert!(MatchExpr::DestinationCidr(cidr).matches(&req)); + } + + #[test] + fn ipv4_mapped_destination_outside_ipv4_cidr_no_match() { + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let mapped: IpAddr = "::ffff:192.168.1.1".parse().unwrap(); + let target = target_ip(mapped, 80); + let req = make_request(&target, None, "l", ProtocolId::Http, &ANON); + assert!(!MatchExpr::DestinationCidr(cidr).matches(&req)); + } + + #[test] + fn ipv4_cidr_does_not_match_unrelated_native_ipv6() { + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let target = target_ip("2001:db8::1".parse().unwrap(), 80); + let req = make_request(&target, None, "l", ProtocolId::Http, &ANON); + assert!(!MatchExpr::DestinationCidr(cidr).matches(&req)); + } + + #[test] + fn native_ipv6_cidr_does_not_match_ipv4() { + let cidr: ipnet::IpNet = "2001:db8::/32".parse().unwrap(); + let target = target_ip(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)), 80); + let req = make_request(&target, None, "l", ProtocolId::Http, &ANON); + assert!(!MatchExpr::DestinationCidr(cidr).matches(&req)); + } + + #[test] + fn mapped_destination_cannot_bypass_negated_cidr() { + // `not { destination_cidr = "10.0.0.0/8" }` must not match a mapped + // address that canonicalizes into 10.0.0.0/8. + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let mapped: IpAddr = "::ffff:10.1.2.3".parse().unwrap(); + let target = target_ip(mapped, 80); + let req = make_request(&target, None, "l", ProtocolId::Http, &ANON); + let negated = MatchExpr::Not(Box::new(MatchExpr::DestinationCidr(cidr))); + assert!(!negated.matches(&req)); + } + + #[test] + fn mapped_destination_canonicalization_does_not_rewrite_explanation() { + // Canonicalization is local to the CIDR comparison: the reported + // target must stay exactly what the client supplied. + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let mapped: IpAddr = "::ffff:10.0.0.1".parse().unwrap(); + let target = target_ip(mapped, 80); + let req = make_request(&target, None, "l", ProtocolId::Http, &ANON); + assert!(MatchExpr::DestinationCidr(cidr).matches(&req)); + assert!(matches!(target.host, TargetHost::Ip(IpAddr::V6(_)))); + + let router = Router::new(vec![], RouteActionSpec::Direct); + let explanation = router.explain(&req, 1); + assert_eq!(explanation.target, "[::ffff:10.0.0.1]:80"); + } + #[test] fn port_exact_match() { let target = target_domain("example.com", 443); @@ -313,6 +379,44 @@ mod tests { assert!(!MatchExpr::SourceCidr(cidr).matches(&req)); } + #[test] + fn ipv4_mapped_source_matches_ipv4_source_cidr() { + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let source: SocketAddr = "[::ffff:10.1.2.3]:5000".parse().unwrap(); + assert!(matches!(source.ip(), IpAddr::V6(_))); + let target = target_domain("example.com", 80); + let req = make_request(&target, Some(source), "l", ProtocolId::Http, &ANON); + assert!(MatchExpr::SourceCidr(cidr).matches(&req)); + } + + #[test] + fn ipv4_mapped_source_outside_ipv4_cidr_no_match() { + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let source: SocketAddr = "[::ffff:192.0.2.10]:5000".parse().unwrap(); + let target = target_domain("example.com", 80); + let req = make_request(&target, Some(source), "l", ProtocolId::Http, &ANON); + assert!(!MatchExpr::SourceCidr(cidr).matches(&req)); + } + + #[test] + fn native_ipv6_source_cidr_still_matches() { + let cidr: ipnet::IpNet = "2001:db8::/32".parse().unwrap(); + let source: SocketAddr = "[2001:db8::5]:5000".parse().unwrap(); + let target = target_domain("example.com", 80); + let req = make_request(&target, Some(source), "l", ProtocolId::Http, &ANON); + assert!(MatchExpr::SourceCidr(cidr).matches(&req)); + } + + #[test] + fn mapped_source_cannot_bypass_negated_source_cidr() { + let cidr: ipnet::IpNet = "10.0.0.0/8".parse().unwrap(); + let source: SocketAddr = "[::ffff:10.1.2.3]:5000".parse().unwrap(); + let target = target_domain("example.com", 80); + let req = make_request(&target, Some(source), "l", ProtocolId::Http, &ANON); + let negated = MatchExpr::Not(Box::new(MatchExpr::SourceCidr(cidr))); + assert!(!negated.matches(&req)); + } + #[test] fn listener_match() { let target = target_domain("example.com", 80); diff --git a/crates/eggress-routing/src/matcher.rs b/crates/eggress-routing/src/matcher.rs index 6902818c..b9bbad05 100644 --- a/crates/eggress-routing/src/matcher.rs +++ b/crates/eggress-routing/src/matcher.rs @@ -122,6 +122,23 @@ pub fn normalize_host_for_exact(host: &str) -> String { } } +/// Canonicalize an address for CIDR comparison. +/// +/// `ipnet::IpNet::contains` refuses cross-family comparisons, so an +/// IPv4-mapped IPv6 literal (`::ffff:a.b.c.d`) would otherwise never match an +/// IPv4 CIDR rule. A dual-stack client could then bypass a private-range rule +/// by sending the mapped form. +/// +/// The value is canonicalized only for the comparison: the target and source +/// carried by the route request — and therefore the values reported by +/// `route explain` — are never rewritten. +fn canonical_ip(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4), + v4 => v4, + } +} + fn target_host_str(host: &TargetHost) -> Cow<'_, str> { match host { TargetHost::Domain(domain) => Cow::Borrowed(domain), @@ -189,8 +206,10 @@ impl MatchExpr { } MatchExpr::DestinationCidr(cidr) => { if let TargetHost::Ip(ip) = &request.target.host { - cidr.contains(ip) + cidr.contains(&canonical_ip(*ip)) } else { + // CIDR rules are literal-IP-only by contract: no DNS + // resolution happens during route evaluation. false } } @@ -201,7 +220,7 @@ impl MatchExpr { } MatchExpr::SourceCidr(cidr) => { if let Some(addr) = request.source { - cidr.contains(&addr.ip()) + cidr.contains(&canonical_ip(addr.ip())) } else { false } diff --git a/crates/eggress-runtime/src/supervisor.rs b/crates/eggress-runtime/src/supervisor.rs index fd4cce80..86923ec3 100644 --- a/crates/eggress-runtime/src/supervisor.rs +++ b/crates/eggress-runtime/src/supervisor.rs @@ -1871,6 +1871,53 @@ enabled = false assert!(result.unwrap_err().contains("admin")); } + #[test] + fn reload_rejects_admin_allowed_hosts_change() { + // The admin allowlist is fixed when the admin task starts, so a + // change must require a restart instead of silently keeping the old + // (possibly wider) policy. + let config1 = r#" +version = 1 + +[[listeners]] +name = "http-in" +bind = "127.0.0.1:8080" +protocols = ["http"] + +[admin] +bind = "127.0.0.1:9090" +enabled = false +"#; + let config2 = r#" +version = 1 + +[[listeners]] +name = "http-in" +bind = "127.0.0.1:8080" +protocols = ["http"] + +[admin] +bind = "127.0.0.1:9090" +enabled = false +allowed_hosts = ["admin.example"] +"#; + let f1 = write_config(config1); + let f2 = write_config(config2); + let sup = ServiceSupervisor::start(f1.path().to_str().unwrap()).unwrap(); + let new_config = + eggress_config::compile::load_and_compile(f2.path().to_str().unwrap()).unwrap(); + + let snap = sup.state.snapshot.load(); + let result = classify_reload_config( + &snap.listeners, + &snap.timeouts, + snap.admin.as_ref(), + &new_config, + ); + let error = result.expect_err("admin allowed_hosts change should be rejected"); + assert!(error.contains("allowed_hosts"), "unexpected error: {error}"); + } + #[test] fn reload_rejects_listener_count_change() { let config1 = r#" diff --git a/crates/eggress-runtime/src/supervisor/reload.rs b/crates/eggress-runtime/src/supervisor/reload.rs index f0ad3762..5a712583 100644 --- a/crates/eggress-runtime/src/supervisor/reload.rs +++ b/crates/eggress-runtime/src/supervisor/reload.rs @@ -321,13 +321,28 @@ pub fn classify_reload_config( return Err("timeout configuration changed; restart required".to_string()); } - let old_admin_endpoint = old_admin.map(|admin| (admin.enabled, admin.bind.as_str())); - let new_admin_endpoint = new_config - .admin - .as_ref() - .map(|admin| (admin.enabled, admin.bind.as_str())); + // `allowed_hosts` is part of the admin listener's security policy and is + // fixed when the admin task starts, so a change to it requires the same + // restart as a bind change. Silently keeping the old allowlist would leave + // the running server out of step with the configuration on disk. + let old_admin_endpoint = old_admin.map(|admin| { + ( + admin.enabled, + admin.bind.as_str(), + admin.allowed_hosts.as_slice(), + ) + }); + let new_admin_endpoint = new_config.admin.as_ref().map(|admin| { + ( + admin.enabled, + admin.bind.as_str(), + admin.allowed_hosts.as_slice(), + ) + }); if old_admin_endpoint != new_admin_endpoint { - return Err("admin endpoint bind configuration changed; restart required".to_string()); + return Err( + "admin endpoint bind/allowed_hosts configuration changed; restart required".to_string(), + ); } Ok(()) diff --git a/crates/eggress-runtime/src/supervisor/services.rs b/crates/eggress-runtime/src/supervisor/services.rs index b4b7bf98..81cc35c5 100644 --- a/crates/eggress-runtime/src/supervisor/services.rs +++ b/crates/eggress-runtime/src/supervisor/services.rs @@ -351,6 +351,9 @@ pub(crate) async fn prebind_and_spawn_admin( } } let admin_auth = cfg.auth.clone(); + // `admin.bind` (and therefore `allowed_hosts`) is not hot-reloaded; + // the supervisor is restarted to change either. + let admin_allowed_hosts = cfg.allowed_hosts.clone(); let metrics = metrics_registry.clone(); admin_tasks.spawn(async move { let admin_state = eggress_admin::AdminState { @@ -366,6 +369,7 @@ pub(crate) async fn prebind_and_spawn_admin( reverse_registry: std::sync::Arc::new(eggress_admin::ReverseRegistry::new()), metrics_enabled, auth: admin_auth, + allowed_hosts: admin_allowed_hosts, }; if let Err(e) = server.run(admin_state).await { tracing::error!("admin server error: {e}"); diff --git a/crates/eggress-runtime/tests/admin.rs b/crates/eggress-runtime/tests/admin.rs index ea198c47..14cc80e1 100644 --- a/crates/eggress-runtime/tests/admin.rs +++ b/crates/eggress-runtime/tests/admin.rs @@ -44,7 +44,7 @@ async fn http_get(addr: &str, path: &str) -> (u16, String) { async fn http_post(addr: &str, path: &str, body: &str) -> (u16, String) { let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); let request = format!( - "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len() ); tokio::io::AsyncWriteExt::write_all(&mut stream, request.as_bytes()) @@ -135,6 +135,7 @@ fn test_state_with_listeners() -> AdminState { reverse_registry: Arc::new(eggress_admin::ReverseRegistry::new()), metrics_enabled: true, auth: None, + allowed_hosts: eggress_config::compile::derive_allowed_hosts("127.0.0.1:9090"), } } @@ -536,6 +537,16 @@ enabled = true "source=10.1.2.3 should match internal-only rule" ); + // An IPv4-mapped IPv6 source is canonicalized before the CIDR comparison, + // so it cannot bypass the IPv4 source rule. + let mapped_body = r#"{"target":"example.com:443","listener":"http-in","protocol":"http","source":"[::ffff:10.1.2.3]:5000"}"#; + let (_status, body) = http_post(&admin_addr, "/-/route-explain", mapped_body).await; + let json: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!( + json["matched_rule"], "internal-only", + "mapped IPv6 source should match the IPv4 source CIDR rule" + ); + let external_body = r#"{"target":"example.com:443","listener":"http-in","protocol":"http","source":"192.0.2.10:5000"}"#; let (_status, body) = http_post(&admin_addr, "/-/route-explain", external_body).await; let json: serde_json::Value = serde_json::from_str(&body).unwrap(); @@ -843,3 +854,149 @@ async fn admin_rejects_oversized_post_body() { "oversized POST body should be rejected with 413, got status {status}" ); } + +async fn http_raw(addr: &str, request: &str) -> (u16, String) { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + tokio::io::AsyncWriteExt::write_all(&mut stream, request.as_bytes()) + .await + .unwrap(); + tokio::io::AsyncWriteExt::flush(&mut stream).await.unwrap(); + + let mut response = Vec::new(); + loop { + let mut buf = [0u8; 4096]; + match tokio::io::AsyncReadExt::read(&mut stream, &mut buf).await { + Ok(0) => break, + Ok(n) => response.extend_from_slice(&buf[..n]), + Err(_) => break, + } + } + let response = String::from_utf8_lossy(&response); + let status_line = response.lines().next().unwrap_or(""); + let status = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let body = response.split("\r\n\r\n").nth(1).unwrap_or("").to_string(); + (status, body) +} + +#[tokio::test] +async fn admin_host_origin_and_content_type_policy_from_config() { + use std::io::Write as _; + use std::sync::atomic::Ordering; + use std::time::Duration; + + let config = r#" +version = 1 + +[[listeners]] +name = "http-in" +bind = "127.0.0.1:0" +protocols = ["http"] + +[[rules]] +id = "only" +any = true +direct = true + +[admin] +bind = "127.0.0.1:0" +enabled = true +allowed_hosts = ["admin.example"] +"#; + let _supervisor_guard = supervisor_test_guard().await; + let mut f = tempfile::NamedTempFile::new().unwrap(); + f.write_all(config.as_bytes()).unwrap(); + f.flush().unwrap(); + let path = f.path().to_str().unwrap().to_string(); + + let mut sup = eggress_runtime::ServiceSupervisor::start(&path).unwrap(); + let token = sup.shutdown_token(); + struct AutoShutdown(tokio_util::sync::CancellationToken); + impl Drop for AutoShutdown { + fn drop(&mut self) { + self.0.cancel(); + } + } + let _shutdown = AutoShutdown(token.clone()); + let state = sup.state().clone(); + let jh = tokio::task::spawn_blocking(move || sup.run()); + + for _ in 0..50 { + if state.readiness.load(Ordering::Relaxed) { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert!(state.readiness.load(Ordering::Relaxed)); + + let admin_addr = state + .admin_local_addr + .lock() + .unwrap() + .expect("admin should have bound") + .to_string(); + let request_body = r#"{"target":"example.com:443","listener":"http-in","protocol":"http"}"#; + + // 1. A DNS-rebinding style Host is rejected even though the request is a + // plain read of routing topology. + let request = concat!( + "GET /-/routes HTTP/1.1\r\n", + "Host: attacker.example\r\n", + "Connection: close\r\n\r\n", + ); + let (status, body) = http_raw(&admin_addr, request).await; + assert_eq!(status, 400, "attacker Host must be rejected"); + assert_eq!(body, "bad request"); + assert!(!body.contains("attacker")); + assert!(!body.contains("only")); + + // 2. The configured host is accepted (port-insensitive). + let request = concat!( + "GET /-/routes HTTP/1.1\r\n", + "Host: admin.example:9090\r\n", + "Connection: close\r\n\r\n", + ); + let (status, body) = http_raw(&admin_addr, request).await; + assert_eq!(status, 200, "configured host must be accepted: {body}"); + + // 3. route-explain requires a JSON content type. + let request = format!( + "POST /-/route-explain HTTP/1.1\r\nHost: admin.example\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{request_body}", + request_body.len() + ); + let (status, _) = http_raw(&admin_addr, &request).await; + assert_eq!(status, 415, "missing JSON content type must be rejected"); + + // 4. A cross-origin POST is rejected; the rejected origin is not echoed. + let request = format!( + "POST /-/route-explain HTTP/1.1\r\nHost: admin.example\r\n\ + Content-Type: application/json\r\nOrigin: https://attacker.example\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{request_body}", + request_body.len() + ); + let (status, body) = http_raw(&admin_addr, &request).await; + assert_eq!(status, 403, "cross-origin POST must be rejected"); + assert!( + !body.contains("attacker"), + "origin must not be echoed: {body}" + ); + + // 5. A same-origin POST with JSON still works. + let request = format!( + "POST /-/route-explain HTTP/1.1\r\nHost: admin.example\r\n\ + Content-Type: application/json\r\nOrigin: http://admin.example\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{request_body}", + request_body.len() + ); + let (status, body) = http_raw(&admin_addr, &request).await; + assert_eq!(status, 200, "same-origin POST must succeed: {body}"); + let json: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(json["matched_rule"], "only"); + + token.cancel(); + jh.await.ok(); +} diff --git a/crates/eggress-runtime/tests/observability.rs b/crates/eggress-runtime/tests/observability.rs index d9d1cdd9..e24b906b 100644 --- a/crates/eggress-runtime/tests/observability.rs +++ b/crates/eggress-runtime/tests/observability.rs @@ -54,7 +54,7 @@ async fn http_get(addr: &str, path: &str) -> (u16, String) { async fn http_post(addr: &str, path: &str, body: &str) -> (u16, String) { let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); let request = format!( - "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + "POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len() ); tokio::io::AsyncWriteExt::write_all(&mut stream, request.as_bytes()) diff --git a/crates/eggress-server/src/accept/handlers.rs b/crates/eggress-server/src/accept/handlers.rs index ef843215..c2c0e8aa 100644 --- a/crates/eggress-server/src/accept/handlers.rs +++ b/crates/eggress-server/src/accept/handlers.rs @@ -148,29 +148,42 @@ pub(crate) async fn accept_socks4( port: request.addr.port(), } }; - let cached = cached_identity(auth, peer_ip); - if cached.is_none() { - if let Some((username, _, _)) = auth_credentials(auth) { + let identity = match (cached_identity(auth, peer_ip), auth_credentials(auth)) { + // A cache hit is proof of an earlier full-credential authentication on + // this source IP; it does not re-verify a user ID. + (Some(identity), _) => identity, + (None, Some((username, password, _))) => { + // pproxy 2.7.9 carries the listener credential in the SOCKS4 user + // ID and compares it against the full `user:pass` string. SOCKS4 + // has no separate password field, so the password is enforced here + // or not at all. use subtle::ConstantTimeEq; - let user_ok: bool = request.user_id.as_bytes().ct_eq(username.as_bytes()).into(); - if !user_ok { + use zeroize::Zeroize; + let mut expected = Vec::with_capacity(username.len() + 1 + password.len()); + expected.extend_from_slice(username.as_bytes()); + expected.push(b':'); + expected.extend_from_slice(password.as_bytes()); + let credentials_ok: bool = request.user_id.as_bytes().ct_eq(expected.as_slice()).into(); + expected.zeroize(); + if !credentials_ok { + // Generic failure: neither the user ID nor the configured + // credential is echoed. return Err(AcceptError::AuthenticationFailed); } + let identity = ClientIdentity::Username(username.to_string()); + // Only a fully authenticated SOCKS4 session may seed the shared + // IP-reuse cache. + record_authenticated(auth, peer_ip, &identity); + identity } - } - let identity = cached.unwrap_or({ - if request.user_id.is_empty() { - ClientIdentity::Anonymous - } else { - ClientIdentity::Opaque(request.user_id) + (None, None) => { + if request.user_id.is_empty() { + ClientIdentity::Anonymous + } else { + ClientIdentity::Opaque(request.user_id) + } } - }); - if matches!( - identity, - ClientIdentity::Opaque(_) | ClientIdentity::Username(_) - ) { - record_authenticated(auth, peer_ip, &identity); - } + }; let stream: BoxStream = Box::new(tokio::io::join(reader, writer)); Ok(AcceptedSession::Tunnel(PendingTunnel { diff --git a/crates/eggress-server/src/accept/tests.rs b/crates/eggress-server/src/accept/tests.rs index ee21a940..6ac77fc7 100644 --- a/crates/eggress-server/src/accept/tests.rs +++ b/crates/eggress-server/src/accept/tests.rs @@ -441,6 +441,181 @@ async fn test_tls_client_hello_not_interpreted_as_http() { server_jh.await.unwrap(); } +// === SOCKS4 full-credential authentication tests === + +/// Drive one SOCKS4 CONNECT attempt with `user_id` in the user-ID field and +/// return the accept result. `peer` is reported as the connection's source IP +/// so the auth-reuse cache can be exercised. +async fn socks4_auth_attempt( + auth: &InboundAuthentication, + peer: Option, + user_id: &str, +) -> Result { + let protocols: Vec = vec![ProtocolId::Http, ProtocolId::Socks4, ProtocolId::Socks5]; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + let user_id = user_id.to_string(); + let client_jh = tokio::spawn(async move { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + // VN=0x04, CD=CONNECT, DSTPORT=80, DSTIP=10.0.0.1 + stream + .write_all(&[0x04, 0x01, 0x00, 0x50, 10, 0, 0, 1]) + .await + .unwrap(); + stream.write_all(user_id.as_bytes()).await.unwrap(); + stream.write_all(&[0x00]).await.unwrap(); + stream.flush().await.unwrap(); + }); + + let (stream, _) = listener.accept().await.unwrap(); + let boxed: BoxStream = Box::new(stream); + let result = + accept_with_fixed_target_for_peer(boxed, &protocols, auth, None, None, None, None, peer) + .await; + client_jh.await.unwrap(); + result +} + +fn socks4_auth_with_cache(cache: &Arc) -> InboundAuthentication { + InboundAuthentication::UsernamePasswordWithReuse { + username: "user".to_string(), + password: "secret".to_string(), + reuse: Arc::clone(cache), + } +} + +#[tokio::test] +async fn test_socks4_auth_full_credential_accepted() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let peer: IpAddr = "203.0.113.9".parse().unwrap(); + + let session = socks4_auth_attempt(&auth, Some(peer), "user:secret") + .await + .expect("full pproxy credential must be accepted"); + match session { + AcceptedSession::Tunnel(pending) => { + assert_eq!(pending.protocol, TunnelProtocol::Socks4); + assert_eq!(pending.target.port, 80); + assert_eq!( + pending.identity, + ClientIdentity::Username("user".to_string()), + "identity must be derived from the authenticated username" + ); + } + _ => panic!("expected tunnel"), + } + assert_eq!( + cache.lookup(peer), + Some(ClientIdentity::Username("user".to_string())), + "a fully authenticated SOCKS4 session seeds the reuse cache" + ); +} + +#[tokio::test] +async fn test_socks4_auth_username_only_rejected() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let peer: IpAddr = "203.0.113.10".parse().unwrap(); + + let result = socks4_auth_attempt(&auth, Some(peer), "user").await; + assert!(matches!(result, Err(AcceptError::AuthenticationFailed))); + assert!( + cache.is_empty(), + "a username-only SOCKS4 attempt must never seed the reuse cache" + ); +} + +#[tokio::test] +async fn test_socks4_auth_wrong_password_rejected() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let peer: IpAddr = "203.0.113.11".parse().unwrap(); + + let result = socks4_auth_attempt(&auth, Some(peer), "user:wrong").await; + assert!(matches!(result, Err(AcceptError::AuthenticationFailed))); + assert!(cache.is_empty(), "failed auth must not seed the cache"); +} + +#[tokio::test] +async fn test_socks4_auth_empty_user_id_rejected() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let peer: IpAddr = "203.0.113.12".parse().unwrap(); + + let result = socks4_auth_attempt(&auth, Some(peer), "").await; + assert!(matches!(result, Err(AcceptError::AuthenticationFailed))); + assert!(cache.is_empty(), "failed auth must not seed the cache"); +} + +#[tokio::test] +async fn test_socks4_auth_failure_does_not_leak_credentials() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let peer: IpAddr = "203.0.113.13".parse().unwrap(); + + let result = socks4_auth_attempt(&auth, Some(peer), "user:wrong").await; + let error = result.err().expect("wrong password must be rejected"); + let rendered = format!("{error}"); + assert_eq!(rendered, "authentication failed"); + assert!(!rendered.contains("user")); + assert!(!rendered.contains("secret")); + assert!(!rendered.contains("wrong")); +} + +#[tokio::test] +async fn test_socks4_auth_rejected_attempt_does_not_authorize_retry() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let peer: IpAddr = "203.0.113.14".parse().unwrap(); + + for user_id in ["user", "user:wrong", ""] { + let result = socks4_auth_attempt(&auth, Some(peer), user_id).await; + assert!( + matches!(result, Err(AcceptError::AuthenticationFailed)), + "user ID {user_id:?} must be rejected" + ); + assert!(cache.is_empty()); + } + + // The same source IP is still authenticated only by the full credential. + let session = socks4_auth_attempt(&auth, Some(peer), "user:secret") + .await + .expect("full credential must still be accepted after failures"); + drop(session); +} + +#[tokio::test] +async fn test_socks4_auth_reuse_cache_is_peer_scoped() { + let cache = Arc::new(AuthReuseCache::new(Duration::from_secs(60))); + let auth = socks4_auth_with_cache(&cache); + let authenticated: IpAddr = "203.0.113.15".parse().unwrap(); + let other: IpAddr = "203.0.113.16".parse().unwrap(); + + socks4_auth_attempt(&auth, Some(authenticated), "user:secret") + .await + .expect("full credential must be accepted"); + + // Same source IP, no user ID: authorized by the earlier authentication and + // reported with the authenticated username identity. + let reused = socks4_auth_attempt(&auth, Some(authenticated), "") + .await + .expect("authenticated source IP is reused"); + match reused { + AcceptedSession::Tunnel(pending) => assert_eq!( + pending.identity, + ClientIdentity::Username("user".to_string()) + ), + _ => panic!("expected tunnel"), + } + + // A different source IP gets nothing from the cache. + let foreign = socks4_auth_attempt(&auth, Some(other), "").await; + assert!(matches!(foreign, Err(AcceptError::AuthenticationFailed))); + assert_eq!(cache.len(), 1); +} + // === Authentication tests === #[tokio::test] diff --git a/crates/eggress-system-proxy/src/inspection.rs b/crates/eggress-system-proxy/src/inspection.rs index 60a008c1..d77865c0 100644 --- a/crates/eggress-system-proxy/src/inspection.rs +++ b/crates/eggress-system-proxy/src/inspection.rs @@ -55,15 +55,62 @@ pub struct InspectionResult { /// Capability reports for all system proxy backends. pub capabilities: Vec, /// Current proxy settings (if readable). + /// + /// Kept for in-process callers that need the unredacted values, but never + /// serialized: OS and environment settings can carry `user:pass@` + /// credentials, and `eggress system-proxy inspect --json` is a + /// copy/paste-able diagnostic surface. JSON output therefore carries only + /// [`Self::redacted_settings`]. + #[serde(default, skip_serializing)] pub settings: Option, - /// Redacted version of settings (safe for logging). + /// Redacted version of settings (safe for logging and JSON output). + /// + /// Always derived from [`Self::settings`] by + /// [`InspectionResult::new`]/`inspect_system_proxy`, so it is populated + /// whenever raw settings exist. pub redacted_settings: Option, /// Whether apply/revert is supported on this platform. pub apply_supported: bool, - /// Commands that would be used for apply (dry-run). + /// Commands that would be used for apply (dry-run, redacted). pub dry_run_commands: Vec, } +impl InspectionResult { + /// Build an inspection result, deriving the redacted settings copy. + /// + /// This is the only constructor used by inspection so `redacted_settings` + /// can never be missing while raw `settings` are present. + pub fn new( + platform: String, + capabilities: Vec, + settings: Option, + apply_supported: bool, + dry_run_commands: Vec, + ) -> Self { + let redacted_settings = settings.as_ref().map(redact_settings); + Self { + platform, + capabilities, + settings, + redacted_settings, + apply_supported, + dry_run_commands, + } + } +} + +/// Owner-safe copy of settings: URI/credential-bearing values are redacted. +fn redact_settings(settings: &SystemProxySettings) -> SystemProxySettings { + SystemProxySettings { + source: settings.source.clone(), + http_proxy: settings.http_proxy.as_ref().map(|v| redact_proxy_value(v)), + https_proxy: settings.https_proxy.as_ref().map(|v| redact_proxy_value(v)), + socks_proxy: settings.socks_proxy.as_ref().map(|v| redact_proxy_value(v)), + no_proxy: settings.no_proxy.clone(), + raw: redact_proxy_settings(&settings.raw), + } +} + impl fmt::Display for InspectionResult { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "Platform: {}", self.platform)?; @@ -119,14 +166,7 @@ pub fn inspect_system_proxy_with_runner(runner: &dyn CommandRunner) -> Inspectio _ => inspect_env_only(runner), }; - let redacted_settings = settings.as_ref().map(|s| SystemProxySettings { - source: s.source.clone(), - http_proxy: s.http_proxy.as_ref().map(|v| redact_proxy_value(v)), - https_proxy: s.https_proxy.as_ref().map(|v| redact_proxy_value(v)), - socks_proxy: s.socks_proxy.as_ref().map(|v| redact_proxy_value(v)), - no_proxy: s.no_proxy.clone(), - raw: redact_proxy_settings(&s.raw), - }); + let redacted_settings = settings.as_ref().map(redact_settings); let apply_supported = capabilities.iter().any(|c| { matches!(c.status, SystemProxyStatus::Available) @@ -139,7 +179,10 @@ pub fn inspect_system_proxy_with_runner(runner: &dyn CommandRunner) -> Inspectio ) }); - let dry_run_commands = generate_dry_run_commands(&platform, settings.as_ref()); + // Generate the display-only dry-run commands from the redacted copy: + // backends embed the proxy value verbatim, so using raw settings here + // would leak `user:pass@` through `--json` and the human report. + let dry_run_commands = generate_dry_run_commands(&platform, redacted_settings.as_ref()); InspectionResult { platform, @@ -279,6 +322,89 @@ mod tests { assert!(json.contains("\"platform\":\"test\"")); } + /// JSON output is the diagnostic surface: raw settings (which can carry + /// `user:pass@` from OS/environment proxy configuration) must never be + /// serialized, while in-process callers keep them. + #[test] + fn inspection_result_json_omits_raw_credentials() { + let mut raw = std::collections::HashMap::new(); + raw.insert( + "http_proxy".to_string(), + "http://user:pass@proxy:8080".to_string(), + ); + raw.insert( + "HTTPS_PROXY".to_string(), + "http://user:pass@proxy:8443".to_string(), + ); + let settings = SystemProxySettings { + source: "environment".to_string(), + http_proxy: Some("http://user:pass@proxy:8080".to_string()), + https_proxy: Some("http://user:pass@proxy:8443".to_string()), + socks_proxy: Some("socks5://admin:secret@proxy:1080".to_string()), + no_proxy: Some("localhost".to_string()), + raw, + }; + let result = InspectionResult::new( + "linux".to_string(), + Vec::new(), + Some(settings), + false, + Vec::new(), + ); + assert!( + result.settings.is_some(), + "raw settings stay available to in-process callers" + ); + assert!( + result + .redacted_settings + .as_ref() + .and_then(|s| s.http_proxy.as_deref()) + == Some("http://****@proxy:8080"), + "redacted settings are derived whenever settings exist" + ); + + let json = serde_json::to_string(&result).unwrap(); + assert!(!json.contains("user:pass@"), "{json}"); + assert!(!json.contains("admin:secret@"), "{json}"); + assert!( + !json.contains("\"settings\""), + "raw settings must not be serialized: {json}" + ); + assert!(json.contains("\"redacted_settings\""), "{json}"); + assert!(json.contains("****@proxy:8080"), "{json}"); + + // The redacted-only shape still deserializes. + let round_trip: InspectionResult = serde_json::from_str(&json).unwrap(); + assert!(round_trip.settings.is_none()); + assert!(round_trip.redacted_settings.is_some()); + } + + /// Dry-run commands are display-only and must be built from the redacted + /// copy: backends embed the proxy value verbatim. + #[test] + fn dry_run_commands_use_redacted_values() { + let settings = SystemProxySettings { + source: "macos:networksetup:*Wi-Fi".to_string(), + http_proxy: Some("http://user:pass@proxy:8080".to_string()), + https_proxy: Some("http://user:pass@proxy:8443".to_string()), + socks_proxy: Some("socks5://admin:secret@proxy:1080".to_string()), + no_proxy: Some("localhost".to_string()), + raw: std::collections::HashMap::new(), + }; + let redacted = redact_settings(&settings); + for platform in ["macos", "windows", "linux"] { + let commands = generate_dry_run_commands(platform, Some(&redacted)); + for command in &commands { + let rendered = command.to_string(); + assert!( + !rendered.contains("user:pass@") && !rendered.contains("admin:secret@"), + "{platform} dry-run command leaked credentials: {rendered}" + ); + } + } + } + #[test] fn settings_display_format() { let settings = SystemProxySettings { diff --git a/crates/eggress-transport-ssh/src/lib.rs b/crates/eggress-transport-ssh/src/lib.rs index eefc3bb5..d2f9aa18 100644 --- a/crates/eggress-transport-ssh/src/lib.rs +++ b/crates/eggress-transport-ssh/src/lib.rs @@ -126,50 +126,84 @@ pub enum SshHostKeyPolicy { InsecureCompatibility, } -impl russh::client::Handler for CompatClient { - type Error = russh::Error; - - async fn check_server_key( - &mut self, - server_public_key: &russh::keys::PublicKey, - ) -> Result { - Ok(match &self.host_key_policy { - SshHostKeyPolicy::KnownHosts => { - match russh::keys::check_known_hosts(&self.host, self.port, server_public_key) { - Ok(accepted) => accepted, - Err(error) => { - // A missing or unreadable known_hosts file must not be - // indistinguishable from a key mismatch. - tracing::warn!( - host = %self.host, - port = self.port, - %error, - "known_hosts lookup failed; rejecting host key" - ); - false - } +/// Decide whether a plain server host key is acceptable under `policy`. +/// +/// This is the whole host-key trust decision, kept out of the `russh` callback +/// so it can be unit-tested without a live session. A lookup error (unreadable +/// or malformed known_hosts, or a changed key) is logged and rejected; it never +/// degrades into `InsecureCompatibility`. +fn verify_host_key( + host: &str, + port: u16, + policy: &SshHostKeyPolicy, + server_public_key: &russh::keys::PublicKey, +) -> bool { + match policy { + SshHostKeyPolicy::KnownHosts => { + match russh::keys::check_known_hosts(host, port, server_public_key) { + Ok(accepted) => accepted, + Err(error) => { + // A missing or unreadable known_hosts file must not be + // indistinguishable from a key mismatch. + tracing::warn!( + host = %host, + port = port, + %error, + "known_hosts lookup failed; rejecting host key" + ); + false } } - SshHostKeyPolicy::KnownHostsFile(path) => match russh::keys::check_known_hosts_path( - &self.host, - self.port, - server_public_key, - path, - ) { + } + SshHostKeyPolicy::KnownHostsFile(path) => { + match russh::keys::check_known_hosts_path(host, port, server_public_key, path) { Ok(accepted) => accepted, Err(error) => { tracing::warn!( - host = %self.host, - port = self.port, + host = %host, + port = port, known_hosts = %path.display(), %error, "known_hosts lookup failed; rejecting host key" ); false } - }, - SshHostKeyPolicy::InsecureCompatibility => true, - }) + } + } + SshHostKeyPolicy::InsecureCompatibility => true, + } +} + +impl russh::client::Handler for CompatClient { + type Error = russh::Error; + + async fn check_server_key( + &mut self, + server_public_key: &russh::keys::PublicKeyOrCertificate, + ) -> Result { + // `russh` 0.65 reports certificate host keys separately from plain + // host keys. Eggress has never accepted SSH certificate host keys: the + // pre-0.65 graph could not even parse one, so the handshake failed + // before a policy decision. Rejecting here keeps that fail-closed + // behaviour instead of projecting a certificate onto a plain key, and + // it applies to every policy including insecure compatibility. + let server_public_key = match server_public_key { + russh::keys::PublicKeyOrCertificate::PublicKey { key, .. } => key, + russh::keys::PublicKeyOrCertificate::Certificate(_) => { + tracing::warn!( + host = %self.host, + port = self.port, + "SSH server presented a certificate host key; certificate host keys are not supported" + ); + return Ok(false); + } + }; + Ok(verify_host_key( + &self.host, + self.port, + &self.host_key_policy, + server_public_key, + )) } #[allow(clippy::too_many_arguments)] @@ -570,3 +604,146 @@ async fn connect_authenticated_with_config( } Ok(session) } + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + /// Public test vectors. They are host *public* keys and authorize nothing. + const HOST_KEY_A: &str = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBwetC7SGNq9kJMmuSzhc5wn7U9GiYrQdsOSemUfu8rK"; + const HOST_KEY_B: &str = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG13LBHUOjmMmz1H4YO3A0sMYlX2X9Q8BSrN/4wR6TZZ"; + + fn public_key(openssh: &str) -> russh::keys::PublicKey { + russh::keys::PublicKey::from_openssh(openssh).expect("static test key parses") + } + + fn known_hosts_entry(host: &str, port: u16, key: &str) -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("known_hosts"); + std::fs::write(&path, format!("[{host}]:{port} {key}\n")).expect("write known_hosts"); + (dir, path) + } + + fn session_key(policy: SshHostKeyPolicy) -> SshSessionKey { + SshSessionKey { + host: "ssh.example".to_string(), + port: 2222, + username: "operator".to_string(), + auth: SshAuth::Password("hunter2".to_string()), + hop_index: 0, + policy, + } + } + + #[test] + fn ssh_auth_debug_never_shows_secrets() { + let password = SshAuth::Password("hunter2".to_string()); + let private_key = SshAuth::PrivateKey("/home/operator/.ssh/id_ed25519".to_string()); + for (auth, secret) in [ + (&password, "hunter2"), + (&private_key, "/home/operator/.ssh/id_ed25519"), + ] { + let rendered = format!("{auth:?}"); + assert!(rendered.contains("****"), "{rendered}"); + assert!(!rendered.contains(secret), "{rendered}"); + } + } + + #[test] + fn session_key_debug_never_shows_secrets() { + let rendered = format!("{:?}", session_key(SshHostKeyPolicy::InsecureCompatibility)); + assert!(rendered.contains("****"), "{rendered}"); + assert!(!rendered.contains("hunter2"), "{rendered}"); + } + + #[test] + fn session_key_is_scoped_by_host_key_policy() { + let known = session_key(SshHostKeyPolicy::KnownHosts); + let insecure = session_key(SshHostKeyPolicy::InsecureCompatibility); + assert_ne!(known, insecure); + let keys = HashSet::from([known, insecure]); + assert_eq!( + keys.len(), + 2, + "a session authenticated under one policy must not collide with another" + ); + } + + #[test] + fn known_hosts_file_accepts_matching_key_and_rejects_mismatch() { + let (_dir, path) = known_hosts_entry("127.0.0.1", 2222, HOST_KEY_A); + let policy = SshHostKeyPolicy::KnownHostsFile(path); + assert!(verify_host_key( + "127.0.0.1", + 2222, + &policy, + &public_key(HOST_KEY_A) + )); + assert!( + !verify_host_key("127.0.0.1", 2222, &policy, &public_key(HOST_KEY_B)), + "a changed host key must be rejected" + ); + } + + #[test] + fn missing_known_hosts_file_rejects_host_key() { + let dir = tempfile::tempdir().expect("temp dir"); + let policy = SshHostKeyPolicy::KnownHostsFile(dir.path().join("absent_known_hosts")); + assert!( + !verify_host_key("127.0.0.1", 2222, &policy, &public_key(HOST_KEY_A)), + "an absent known_hosts file must fail closed" + ); + } + + #[test] + fn default_known_hosts_policy_rejects_unrecorded_host() { + // A reserved `.invalid` name cannot be recorded in a real known_hosts + // file, so the default policy is exercised without reading a match. + let policy = SshHostKeyPolicy::KnownHosts; + assert!(!verify_host_key( + "eggress-ssh-policy.invalid", + 65022, + &policy, + &public_key(HOST_KEY_A) + )); + } + + #[test] + fn insecure_compatibility_accepts_any_plain_key() { + let policy = SshHostKeyPolicy::InsecureCompatibility; + for key in [HOST_KEY_A, HOST_KEY_B] { + assert!(verify_host_key( + "127.0.0.1", + 2222, + &policy, + &public_key(key) + )); + } + } + + #[test] + fn cache_policy_accessors_match_their_constructors() { + assert_eq!( + SshSessionCache::new().policy(), + SshHostKeyPolicy::KnownHosts + ); + let path = PathBuf::from("known_hosts"); + assert_eq!( + SshSessionCache::with_known_hosts(path.clone()).policy(), + SshHostKeyPolicy::KnownHostsFile(path) + ); + } + + #[cfg(feature = "pproxy-compat")] + #[test] + fn compatibility_cache_constructs_the_insecure_policy() { + assert_eq!( + SshSessionCache::new_compatibility().policy(), + SshHostKeyPolicy::InsecureCompatibility + ); + } +} diff --git a/crates/eggress-transport-tls/src/client.rs b/crates/eggress-transport-tls/src/client.rs index f833284a..ac39f09b 100644 --- a/crates/eggress-transport-tls/src/client.rs +++ b/crates/eggress-transport-tls/src/client.rs @@ -12,7 +12,8 @@ static DEFAULT_H2_CLIENT_CONFIG: OnceLock> = OnceLock::new(); /// Return the process-shared verified client configuration for ordinary TLS. /// -/// The configuration contains only immutable public system roots and no +/// The configuration contains only the immutable bundled Mozilla root set +/// (from `webpki-roots`, not the operating-system store) and no /// destination-specific state. Callers that need custom roots, client /// identity, or a caller-owned override must continue to use the builder. /// @@ -166,7 +167,14 @@ impl TlsClientConfigBuilder { } } - /// Load system root certificates (via webpki-roots). + /// Extend the root store with the bundled Mozilla root certificate set + /// published by the `webpki-roots` crate. + /// + /// The historical method name notwithstanding, this is **not** the + /// operating-system trust store: the roots are compiled into the binary + /// and change only when the `webpki-roots` dependency is updated. + /// [`TlsClientConfigBuilder::with_custom_ca_pem`] *replaces* this set + /// rather than extending it. pub fn with_system_roots(mut self) -> Result { self.root_store .extend(webpki_roots::TLS_SERVER_ROOTS.iter().map(|r| r.to_owned())); @@ -371,12 +379,17 @@ mod tests { #[test] fn builder_system_roots() { init(); - let config = TlsClientConfigBuilder::new() - .with_system_roots() - .unwrap() - .build() - .unwrap(); - // Config built successfully with system roots + let builder = TlsClientConfigBuilder::new().with_system_roots().unwrap(); + // The default trust set is the bundled `webpki-roots` store: it must + // be non-empty and match the compiled-in root count exactly, so an + // accidental empty/foreign root set cannot pass unnoticed. + assert!(!builder.root_store.is_empty()); + assert_eq!( + builder.root_store.len(), + webpki_roots::TLS_SERVER_ROOTS.len() + ); + let config = builder.build().unwrap(); + // Config built successfully with the bundled roots assert!(config.alpn_protocols.is_empty()); } @@ -461,6 +474,47 @@ mod tests { server_handle.await.unwrap(); } + /// The shared default configuration must stay on the strict verifier + /// path: a peer that only presents a self-signed certificate is + /// rejected. This is the regression guard for the advisory remediation; + /// a silent insecure fallback would let the handshake succeed. + #[tokio::test] + async fn default_verified_config_rejects_self_signed_server() { + init(); + let (cert_pem, key_pem) = crate::self_signed_cert(); + + let server_config = crate::TlsServerConfigBuilder::new() + .with_certificate_pem(cert_pem.as_bytes()) + .unwrap() + .with_key_pem(key_pem.as_bytes()) + .unwrap() + .build() + .unwrap(); + + let client_config = crate::default_client_config().unwrap(); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + let server_handle = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let boxed: eggress_core::BoxStream = Box::new(stream); + // The client aborts after certificate verification fails; the + // server side is expected to error and its error is dropped. + let _ = crate::tls_accept(boxed, server_config).await; + }); + + let tcp = tokio::net::TcpStream::connect(addr).await.unwrap(); + let boxed: eggress_core::BoxStream = Box::new(tcp); + let result = crate::tls_connect(boxed, client_config, "localhost").await; + assert!( + result.is_err(), + "default client config must not accept a self-signed certificate" + ); + + server_handle.abort(); + } + #[test] fn builder_with_alpn() { init(); diff --git a/crates/eggress-udp/src/direct.rs b/crates/eggress-udp/src/direct.rs index cc67640f..811748e1 100644 --- a/crates/eggress-udp/src/direct.rs +++ b/crates/eggress-udp/src/direct.rs @@ -5,6 +5,7 @@ use std::time::Instant; use tokio::net::UdpSocket; use crate::error::UdpError; +use eggress_core::connector::is_reserved_or_private_ip; use eggress_protocol_socks::socks5::server::SocksAddr; pub struct UdpTargetFlow { @@ -18,9 +19,19 @@ pub struct UdpTargetFlow { } impl UdpTargetFlow { - pub async fn new(target: SocksAddr, local_bind: SocketAddr) -> Result { + /// Open a direct datagram flow to `target`. + /// + /// `allow_private_egress` carries the listener's destination policy into + /// the post-DNS check: with the policy restrictive, every answer of the + /// single `lookup_host` call is filtered and only a permitted address is + /// connected. + pub async fn new( + target: SocksAddr, + local_bind: SocketAddr, + allow_private_egress: bool, + ) -> Result { let socket = UdpSocket::bind(local_bind).await?; - let resolved = resolve_target(&target).await?; + let resolved = resolve_target(&target, allow_private_egress).await?; socket.connect(resolved).await?; Ok(Self { target, @@ -61,12 +72,39 @@ impl UdpTargetFlow { } } -async fn resolve_target(target: &SocksAddr) -> Result { +async fn resolve_target( + target: &SocksAddr, + allow_private_egress: bool, +) -> Result { let addr_str = format!("{}:{}", target.host_str(), target.port()); - let mut addrs = tokio::net::lookup_host(&addr_str) + let addrs: Vec = tokio::net::lookup_host(&addr_str) .await - .map_err(UdpError::Io)?; - addrs.next().ok_or(UdpError::UnresolvedTarget) + .map_err(UdpError::Io)? + .collect(); + select_resolved_addr(&addrs, allow_private_egress) +} + +/// Apply the destination policy to the answers of one resolution. +/// +/// With `allow_private_egress` the first answer is used unchanged (pproxy +/// compatibility). Otherwise every answer is filtered through the shared +/// special-purpose/private classifier and the first permitted address is +/// chosen, so a mixed public/private answer set cannot smuggle a private +/// destination through as the first answer. A fully private/reserved answer +/// set fails closed without creating a flow. +fn select_resolved_addr( + addrs: &[SocketAddr], + allow_private_egress: bool, +) -> Result { + let first = addrs.first().ok_or(UdpError::UnresolvedTarget)?; + if allow_private_egress { + return Ok(*first); + } + addrs + .iter() + .copied() + .find(|addr| !is_reserved_or_private_ip(&addr.ip())) + .ok_or(UdpError::PrivateEgressBlocked) } pub fn encode_response(target: &SocksAddr, payload: &[u8]) -> Result, UdpError> { @@ -90,6 +128,7 @@ mod tests { let flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); @@ -108,6 +147,7 @@ mod tests { let flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); @@ -132,6 +172,7 @@ mod tests { let flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); @@ -166,19 +207,121 @@ mod tests { async fn resolve_target_ipv4() { use std::net::IpAddr; let target = SocksAddr::IPv4([127, 0, 0, 1], 8080); - let resolved = resolve_target(&target).await.unwrap(); + let resolved = resolve_target(&target, true).await.unwrap(); assert_eq!( resolved, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) ); } + /// `allow_private_egress = false` must filter every answer of the one + /// lookup, not truncate to the first answer. A private-only answer set + /// fails closed instead of connecting. + #[test] + fn restrictive_policy_selects_first_permitted_answer() { + let private = SocketAddr::from(([127, 0, 0, 1], 9999)); + let public = SocketAddr::from(([8, 8, 8, 8], 9999)); + let cgnat = SocketAddr::from(([100, 64, 0, 1], 9999)); + + assert_eq!( + select_resolved_addr(&[public, private], false).unwrap(), + public, + "public answer must be chosen over a preceding private answer" + ); + assert_eq!( + select_resolved_addr(&[cgnat, public], false).unwrap(), + public, + "CGNAT answers must be filtered before connecting" + ); + assert_eq!( + select_resolved_addr(&[private], false) + .unwrap_err() + .to_string(), + UdpError::PrivateEgressBlocked.to_string() + ); + assert!(matches!( + select_resolved_addr(&[], false), + Err(UdpError::UnresolvedTarget) + )); + } + + #[test] + fn permissive_policy_keeps_first_answer() { + let private = SocketAddr::from(([127, 0, 0, 1], 9999)); + let public = SocketAddr::from(([8, 8, 8, 8], 9999)); + assert_eq!( + select_resolved_addr(&[private, public], true).unwrap(), + private + ); + assert_eq!(select_resolved_addr(&[public], true).unwrap(), public); + } + + /// A domain whose answers are all private is dropped before any socket is + /// connected, so no datagram reaches a local echo server. + #[tokio::test] + async fn private_domain_is_dropped_when_policy_disallows() { + let (echo_addr, received) = start_counting_echo_server().await; + let result = UdpTargetFlow::new( + SocksAddr::Domain("localhost".to_string(), echo_addr.port()), + "127.0.0.1:0".parse().unwrap(), + false, + ) + .await; + + assert!( + matches!(result, Err(UdpError::PrivateEgressBlocked)), + "private-resolving domain must be rejected by the post-DNS policy" + ); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert_eq!( + received.load(Ordering::Relaxed), + 0, + "no datagram may reach the private target" + ); + } + + /// The same target is accepted when the operator permits private egress. + #[tokio::test] + async fn private_domain_is_allowed_when_policy_permits() { + let (echo_addr, received) = start_counting_echo_server().await; + // The numeric domain form keeps a real `lookup_host` call (domain + // branch) while staying independent of the host resolver's family + // preference. + let flow = UdpTargetFlow::new( + SocksAddr::Domain("127.0.0.1".to_string(), echo_addr.port()), + "127.0.0.1:0".parse().unwrap(), + true, + ) + .await + .expect("permissive policy must keep private UDP egress working"); + + flow.send(b"permitted").await.unwrap(); + let mut buf = [0u8; 64]; + let n = flow.recv(&mut buf).await.unwrap(); + assert_eq!(&buf[..n], b"permitted"); + assert_eq!(received.load(Ordering::Relaxed), 1); + } + + /// A public destination still resolves and is selected under the + /// restrictive policy without any external DNS dependency. + #[tokio::test] + async fn public_domain_still_resolves_when_policy_disallows_private() { + use std::net::IpAddr; + let target = SocksAddr::Domain("8.8.8.8".to_string(), 53); + let resolved = resolve_target(&target, false).await.unwrap(); + assert_eq!( + resolved, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 53) + ); + } + #[tokio::test] async fn flow_touch_updates_time() { let echo_addr = start_udp_echo_server().await; let mut flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); @@ -200,4 +343,19 @@ mod tests { }); addr } + + async fn start_counting_echo_server() -> (SocketAddr, Arc) { + let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = socket.local_addr().unwrap(); + let received = Arc::new(AtomicU64::new(0)); + let counter = Arc::clone(&received); + tokio::spawn(async move { + let mut buf = [0u8; 65535]; + while let Ok((n, peer)) = socket.recv_from(&mut buf).await { + counter.fetch_add(1, Ordering::Relaxed); + let _ = socket.send_to(&buf[..n], peer).await; + } + }); + (addr, received) + } } diff --git a/crates/eggress-udp/src/error.rs b/crates/eggress-udp/src/error.rs index ad4a9fdd..0fc10151 100644 --- a/crates/eggress-udp/src/error.rs +++ b/crates/eggress-udp/src/error.rs @@ -28,6 +28,8 @@ pub enum UdpError { UnspecifiedTarget, #[error("port zero not allowed")] PortZero, + #[error("private network egress not allowed")] + PrivateEgressBlocked, #[error("{0}")] Other(String), } diff --git a/crates/eggress-udp/src/relay.rs b/crates/eggress-udp/src/relay.rs index 1515e431..8eea8870 100644 --- a/crates/eggress-udp/src/relay.rs +++ b/crates/eggress-udp/src/relay.rs @@ -541,7 +541,23 @@ async fn handle_client_datagram( e.into_mut() } std::collections::hash_map::Entry::Vacant(e) => { - let flow = UdpTargetFlow::new(request.target.clone(), config.upstream_udp_bind).await?; + // The post-DNS destination policy runs here: a domain whose + // answers are all private/reserved fails closed and drops this + // datagram instead of creating a flow. + let flow = match UdpTargetFlow::new( + request.target.clone(), + config.upstream_udp_bind, + config.allow_private_egress, + ) + .await + { + Ok(flow) => flow, + Err(error) => { + tracing::debug!(%error, "failed to create direct UDP target flow"); + config.udp_metrics.record_dropped(); + return Ok(()); + } + }; let target_addr_clone = request.target.clone(); let flow_response_tx = response_tx.clone(); @@ -885,6 +901,15 @@ mod tests { pkt } + fn domain_socks5_packet(domain: &str, port: u16, payload: &[u8]) -> Vec { + let mut pkt = vec![0x00, 0x00, 0x00, 0x03]; + pkt.push(domain.len() as u8); + pkt.extend_from_slice(domain.as_bytes()); + pkt.extend_from_slice(&port.to_be_bytes()); + pkt.extend_from_slice(payload); + pkt + } + async fn start_udp_echo() -> SocketAddr { let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); let addr = socket.local_addr().unwrap(); @@ -897,6 +922,115 @@ mod tests { addr } + async fn start_counting_udp_echo() -> (SocketAddr, Arc) { + let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = socket.local_addr().unwrap(); + let received = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let counter = Arc::clone(&received); + tokio::spawn(async move { + let mut buf = [0u8; 65535]; + while let Ok((n, peer)) = socket.recv_from(&mut buf).await { + counter.fetch_add(1, Ordering::Relaxed); + let _ = socket.send_to(&buf[..n], peer).await; + } + }); + (addr, received) + } + + /// SOCKS5 UDP ASSOCIATE direct path: `allow_private_egress = false` must + /// drop a domain target whose answers are private, record the dropped + /// metric, and never send a datagram to the resolved destination. + #[tokio::test] + async fn relay_private_domain_dropped_when_policy_disallows() { + let (echo_addr, received) = start_counting_udp_echo().await; + let assoc = test_assoc(); + let relay_socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let relay_addr = relay_socket.local_addr().unwrap(); + + let udp_metrics = Arc::new(UdpMetrics::new()); + let mut config = relay_config(direct_router()); + config.udp_metrics = udp_metrics.clone(); + config.allow_private_egress = false; + let cancel = CancellationToken::new(); + + let relay_cancel = cancel.clone(); + let relay_assoc = assoc.clone(); + let relay_sock = relay_socket.clone(); + let relay_handle = tokio::spawn(async move { + udp_relay_loop(relay_sock, relay_assoc, config, relay_cancel).await + }); + + let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + client_socket.connect(relay_addr).await.unwrap(); + + let pkt = domain_socks5_packet("localhost", echo_addr.port(), b"private domain"); + client_socket.send(&pkt).await.unwrap(); + + let mut recv_buf = [0u8; 65535]; + let response = tokio::time::timeout( + std::time::Duration::from_millis(300), + client_socket.recv(&mut recv_buf), + ) + .await; + assert!( + response.is_err(), + "private-resolving target must be dropped" + ); + assert_eq!( + udp_metrics.dropped_packets.load(Ordering::Relaxed), + 1, + "post-DNS policy rejection must count as a dropped datagram" + ); + assert_eq!( + received.load(Ordering::Relaxed), + 0, + "no datagram may reach the private target" + ); + + cancel.cancel(); + relay_handle.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn relay_private_domain_allowed_when_policy_permits() { + let echo_addr = start_udp_echo().await; + let assoc = test_assoc(); + let relay_socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let relay_addr = relay_socket.local_addr().unwrap(); + + let config = relay_config(direct_router()); + assert!(config.allow_private_egress); + let cancel = CancellationToken::new(); + + let relay_cancel = cancel.clone(); + let relay_assoc = assoc.clone(); + let relay_sock = relay_socket.clone(); + let relay_handle = tokio::spawn(async move { + udp_relay_loop(relay_sock, relay_assoc, config, relay_cancel).await + }); + + let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + client_socket.connect(relay_addr).await.unwrap(); + + // Numeric domain form keeps a real lookup while staying resolver-family + // independent. + let pkt = domain_socks5_packet("127.0.0.1", echo_addr.port(), b"permitted"); + client_socket.send(&pkt).await.unwrap(); + + let mut recv_buf = [0u8; 65535]; + let n = tokio::time::timeout(std::time::Duration::from_secs(2), async { + client_socket.recv(&mut recv_buf).await + }) + .await + .expect("permissive policy must keep private UDP egress working") + .expect("recv should succeed"); + let resp = decode_packet(&recv_buf[..n], &UdpLimits::default()).unwrap(); + assert_eq!(resp.payload, b"permitted"); + + cancel.cancel(); + relay_handle.await.unwrap().unwrap(); + } + #[tokio::test] async fn relay_echo_ipv4() { let echo_addr = start_udp_echo().await; diff --git a/crates/eggress-udp/src/security.rs b/crates/eggress-udp/src/security.rs index c33e1a5f..7d2ab9a0 100644 --- a/crates/eggress-udp/src/security.rs +++ b/crates/eggress-udp/src/security.rs @@ -1,5 +1,6 @@ -use std::net::{Ipv4Addr, Ipv6Addr}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use eggress_core::connector::is_reserved_or_private_ip; use eggress_protocol_socks::socks5::server::SocksAddr; use crate::error::UdpError; @@ -55,25 +56,21 @@ fn validate_target_shape(target: &SocksAddr, reject_loopback: bool) -> Result<() } fn is_private_ipv4(ip: &Ipv4Addr) -> bool { - ip.is_private() || ip.is_loopback() || ip.is_link_local() + is_reserved_or_private_ip(&IpAddr::V4(*ip)) } fn is_private_ipv6(ip: &Ipv6Addr) -> bool { - if let Some(v4) = ip.to_ipv4_mapped() { - return is_private_ipv4(&v4); - } - let octets = ip.octets(); - // fe80::/10 is the link-local unicast prefix - if ip.is_loopback() || (octets[0] == 0xfe && (octets[1] & 0xc0) == 0x80) { - return true; - } - // fc00::/7 are unique-local addresses (fc00::/8 + fd00::/8) - if (octets[0] & 0xfe) == 0xfc { - return true; - } - false + is_reserved_or_private_ip(&IpAddr::V6(*ip)) } +/// Validate a datagram destination before a flow is created. +/// +/// Shape checks (port zero, multicast, broadcast, unspecified, and loopback +/// when `allow_private_egress` is false) always run. Literal private/reserved +/// addresses are rejected here when the policy is restrictive; domain targets +/// cannot be judged yet and are enforced post-DNS by +/// `direct::resolve_target`, which filters every resolved address through the +/// same shared classifier before connecting. pub fn validate_standalone_target( target: &SocksAddr, allow_private_egress: bool, @@ -83,26 +80,19 @@ pub fn validate_standalone_target( if !allow_private_egress { match target { SocksAddr::IPv4(addr, _) => { - let ip = Ipv4Addr::from(*addr); - if is_private_ipv4(&ip) { - return Err(UdpError::Other( - "private network egress not allowed".to_string(), - )); + if is_private_ipv4(&Ipv4Addr::from(*addr)) { + return Err(UdpError::PrivateEgressBlocked); } } SocksAddr::IPv6(addr, _) => { - let ip = Ipv6Addr::from(*addr); - if is_private_ipv6(&ip) { - return Err(UdpError::Other( - "private network egress not allowed".to_string(), - )); + if is_private_ipv6(&Ipv6Addr::from(*addr)) { + return Err(UdpError::PrivateEgressBlocked); } } - // Domain targets are deferred: the true private-egress check - // happens post-DNS in `eggress_core::connector::is_reserved_or_private_ip`. - // This pre-check is best-effort; TOCTOU between validation and lookup - // is accepted and documented (B-07). - _ => {} + // A domain carries no address yet; the resolved-address policy is + // applied by `direct::resolve_target` (single lookup, all answers + // filtered). + SocksAddr::Domain(..) => {} } } @@ -299,10 +289,78 @@ mod tests { #[test] fn allow_public_ipv6_egress() { + // 2606:4700:4700::1111 is globally reachable (not documentation or + // another special-purpose range). + let target = SocksAddr::IPv6( + [ + 0x26, 0x06, 0x47, 0x00, 0x47, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0x11, 0x11, + ], + 80, + ); + assert!(validate_standalone_target(&target, false).is_ok()); + } + + #[test] + fn reject_documentation_ipv6_egress() { + // 2001:db8::/32 previously slipped past the UDP-local classifier. let target = SocksAddr::IPv6( [0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 80, ); + assert!(matches!( + validate_standalone_target(&target, false), + Err(UdpError::PrivateEgressBlocked) + )); + assert!(validate_standalone_target(&target, true).is_ok()); + } + + #[test] + fn reject_cgnat_ipv4_egress() { + let target = SocksAddr::IPv4([100, 64, 0, 1], 8080); + assert!(matches!( + validate_standalone_target(&target, false), + Err(UdpError::PrivateEgressBlocked) + )); + assert!(validate_standalone_target(&target, true).is_ok()); + } + + #[test] + fn reject_nat64_and_teredo_egress() { + let nat64 = SocksAddr::IPv6( + "64:ff9b::808:808" + .parse::() + .unwrap() + .octets(), + 53, + ); + let teredo = SocksAddr::IPv6( + "2001:0:4136:e378:8000:63bf:3fff:fdd2" + .parse::() + .unwrap() + .octets(), + 53, + ); + let sixtofour = SocksAddr::IPv6( + "2002:808:808::1" + .parse::() + .unwrap() + .octets(), + 53, + ); + for target in [nat64, teredo, sixtofour] { + assert!(matches!( + validate_standalone_target(&target, false), + Err(UdpError::PrivateEgressBlocked) + )); + assert!(validate_standalone_target(&target, true).is_ok()); + } + } + + #[test] + fn domain_target_passes_pre_check_and_is_checked_post_dns() { + // A domain carries no address at validation time; the post-DNS policy + // in `direct::resolve_target` owns the resolved-address decision. + let target = SocksAddr::Domain("example.com".to_string(), 80); assert!(validate_standalone_target(&target, false).is_ok()); } diff --git a/crates/eggress-udp/src/standalone.rs b/crates/eggress-udp/src/standalone.rs index f4c59f49..2a601876 100644 --- a/crates/eggress-udp/src/standalone.rs +++ b/crates/eggress-udp/src/standalone.rs @@ -619,7 +619,12 @@ async fn build_direct_flow( target: SocksAddr, cancel: &CancellationToken, ) -> Result { - let flow = UdpTargetFlow::new(target.clone(), local_udp_bind_addr()).await?; + let flow = UdpTargetFlow::new( + target.clone(), + local_udp_bind_addr(), + config.allow_private_egress, + ) + .await?; let target_idle_timeout = config.limits.target_idle_timeout; let flow_response_tx = response_tx.clone(); diff --git a/crates/eggress-udp/src/standalone_shadowsocks.rs b/crates/eggress-udp/src/standalone_shadowsocks.rs index 57892d3f..ff09172b 100644 --- a/crates/eggress-udp/src/standalone_shadowsocks.rs +++ b/crates/eggress-udp/src/standalone_shadowsocks.rs @@ -634,7 +634,12 @@ async fn build_direct_flow( response_tx: &tokio::sync::mpsc::Sender, target: SocksAddr, ) -> Result { - let flow = UdpTargetFlow::new(target.clone(), local_udp_bind_addr()).await?; + let flow = UdpTargetFlow::new( + target.clone(), + local_udp_bind_addr(), + config.allow_private_egress, + ) + .await?; let target_idle_timeout = config.limits.target_idle_timeout; let flow_response_tx = response_tx.clone(); @@ -734,6 +739,84 @@ mod tests { encode_pproxy_udp_packet(method, password, target, payload, &salt).unwrap() } + async fn start_counting_udp_echo() -> (SocketAddr, Arc) { + let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = socket.local_addr().unwrap(); + let received = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let counter = Arc::clone(&received); + tokio::spawn(async move { + let mut buf = [0u8; 65535]; + while let Ok((n, peer)) = socket.recv_from(&mut buf).await { + counter.fetch_add(1, Ordering::Relaxed); + let _ = socket.send_to(&buf[..n], peer).await; + } + }); + (addr, received) + } + + /// Standalone Shadowsocks UDP: `allow_private_egress = false` must drop a + /// domain target whose answers are private, record the rejection, and never + /// send a datagram to the resolved destination. + #[tokio::test] + async fn shadowsocks_standalone_private_domain_dropped_when_policy_disallows() { + let (echo_addr, received) = start_counting_udp_echo().await; + let relay_socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let relay_addr = relay_socket.local_addr().unwrap(); + + let udp_metrics = Arc::new(UdpMetrics::new()); + let mut config = shadowsocks_config(direct_router()); + config.udp_metrics = udp_metrics.clone(); + config.allow_private_egress = false; + let cancel = CancellationToken::new(); + + let relay_cancel = cancel.clone(); + let relay_sock = relay_socket.clone(); + let relay_handle = tokio::spawn(async move { + shadowsocks_standalone_udp_relay(relay_sock, config, relay_cancel).await + }); + + let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + client_socket.connect(relay_addr).await.unwrap(); + + let target = TargetAddr { + host: TargetHost::Domain("localhost".to_string()), + port: echo_addr.port(), + }; + let pkt = encode_ss_packet( + eggress_protocol_shadowsocks::CipherMethod::Aes256Gcm, + b"test-password-123456", + &target, + b"private domain", + ); + client_socket.send(&pkt).await.unwrap(); + + let mut recv_buf = [0u8; 65535]; + let response = tokio::time::timeout( + std::time::Duration::from_millis(300), + client_socket.recv(&mut recv_buf), + ) + .await; + assert!( + response.is_err(), + "private-resolving target must be dropped" + ); + assert_eq!( + udp_metrics + .standalone_rejected_datagrams + .load(Ordering::Relaxed), + 1, + "post-DNS policy rejection must count as a rejected datagram" + ); + assert_eq!( + received.load(Ordering::Relaxed), + 0, + "no datagram may reach the private target" + ); + + cancel.cancel(); + relay_handle.await.unwrap().unwrap(); + } + #[tokio::test] async fn shadowsocks_standalone_echo_ipv4() { let echo_addr = start_udp_echo().await; diff --git a/crates/eggress-udp/tests/standalone_udp.rs b/crates/eggress-udp/tests/standalone_udp.rs index 78b6c39c..69c4653c 100644 --- a/crates/eggress-udp/tests/standalone_udp.rs +++ b/crates/eggress-udp/tests/standalone_udp.rs @@ -162,6 +162,113 @@ async fn standalone_udp_domain_target_echo() { relay_handle.await.unwrap().unwrap(); } +/// Standalone SOCKS5 UDP: `allow_private_egress = false` must drop a domain +/// target whose resolved answers are private, record the rejection, and never +/// send a datagram to the resolved destination. +#[tokio::test] +async fn standalone_udp_private_domain_dropped_when_policy_disallows() { + let (echo_addr, received) = start_counting_udp_echo().await; + let relay_socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let relay_addr = relay_socket.local_addr().unwrap(); + + let udp_metrics = Arc::new(UdpMetrics::new()); + let mut config = standalone_config_with_metrics(direct_router(), udp_metrics.clone()); + config.allow_private_egress = false; + let cancel = CancellationToken::new(); + + let relay_cancel = cancel.clone(); + let relay_sock = relay_socket.clone(); + let relay_handle = + tokio::spawn(async move { standalone_udp_relay(relay_sock, config, relay_cancel).await }); + + let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + client_socket.connect(relay_addr).await.unwrap(); + + let pkt = domain_socks5_packet("localhost", echo_addr.port(), b"private domain"); + client_socket.send(&pkt).await.unwrap(); + + let mut recv_buf = [0u8; 65535]; + let response = tokio::time::timeout( + std::time::Duration::from_millis(300), + client_socket.recv(&mut recv_buf), + ) + .await; + assert!( + response.is_err(), + "private-resolving target must be dropped" + ); + assert_eq!( + udp_metrics + .standalone_rejected_datagrams + .load(Ordering::Relaxed), + 1, + "post-DNS policy rejection must count as a rejected datagram" + ); + assert_eq!( + received.load(Ordering::Relaxed), + 0, + "no datagram may reach the private target" + ); + + cancel.cancel(); + relay_handle.await.unwrap().unwrap(); +} + +/// The same target works with the pproxy-compatible default +/// `allow_private_egress = true`. +#[tokio::test] +async fn standalone_udp_private_domain_allowed_when_policy_permits() { + let echo_addr = start_udp_echo().await; + let relay_socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let relay_addr = relay_socket.local_addr().unwrap(); + + let config = standalone_config(direct_router()); + assert!(config.allow_private_egress); + let cancel = CancellationToken::new(); + + let relay_cancel = cancel.clone(); + let relay_sock = relay_socket.clone(); + let relay_handle = + tokio::spawn(async move { standalone_udp_relay(relay_sock, config, relay_cancel).await }); + + let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + client_socket.connect(relay_addr).await.unwrap(); + + // Numeric domain form keeps a real lookup while staying independent of the + // resolver's address-family preference. + let pkt = domain_socks5_packet("127.0.0.1", echo_addr.port(), b"permitted domain"); + client_socket.send(&pkt).await.unwrap(); + + let mut recv_buf = [0u8; 65535]; + let n = tokio::time::timeout(std::time::Duration::from_secs(2), async { + client_socket.recv(&mut recv_buf).await + }) + .await + .expect("permissive policy must keep private UDP egress working") + .expect("recv should succeed"); + + let resp = decode_packet(&recv_buf[..n], &UdpLimits::default()).unwrap(); + assert_eq!(resp.payload, b"permitted domain"); + + cancel.cancel(); + relay_handle.await.unwrap().unwrap(); +} + +async fn start_counting_udp_echo() -> (std::net::SocketAddr, Arc) { + let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = socket.local_addr().unwrap(); + let received = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let counter = Arc::clone(&received); + tokio::spawn(async move { + let mut buf = [0u8; 65535]; + while let Ok((n, peer)) = socket.recv_from(&mut buf).await { + counter.fetch_add(1, Ordering::Relaxed); + let _ = socket.send_to(&buf[..n], peer).await; + } + }); + (addr, received) +} + #[tokio::test] async fn standalone_udp_malformed_short_datagram() { let relay_socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); diff --git a/crates/eggress-udp/tests/udp_integration.rs b/crates/eggress-udp/tests/udp_integration.rs index dc5b6807..542f0eb0 100644 --- a/crates/eggress-udp/tests/udp_integration.rs +++ b/crates/eggress-udp/tests/udp_integration.rs @@ -18,6 +18,7 @@ async fn direct_flow_ipv4_echo() { let flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); @@ -35,6 +36,7 @@ async fn direct_flow_multiple_packets() { let flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); @@ -57,6 +59,7 @@ async fn direct_flow_metrics_tracking() { let flow = UdpTargetFlow::new( SocksAddr::IPv4([127, 0, 0, 1], echo_addr.port()), "127.0.0.1:0".parse().unwrap(), + true, ) .await .unwrap(); diff --git a/deny.toml b/deny.toml index 630aefe3..3af4220b 100644 --- a/deny.toml +++ b/deny.toml @@ -1,8 +1,48 @@ [graph] targets = [] +# Review the all-features dependency graph of every workspace member. +# +# `all-features` is required because optional-only dependencies (`russh`, +# QUIC/H3, the `eggup`/`zip` updater subtree) are otherwise dropped from the +# advisory/bans/licenses/sources checks. +# +# This section cannot widen the graph roots: the root manifest here is the +# `eggress-bench` package (not a virtual manifest), so `cargo deny` treats it +# as the sole root unless the invocation adds the global `--workspace` flag. +# The gate therefore runs as `cargo deny --workspace check`; a bare +# `cargo deny check` silently omits `eggress-cli` (and therefore `zip`) and +# prints a misleading "advisories ok". Feature slicing still applies to builds +# and tests (`docs/CI_STATUS.md`); it does not restrict what is audited. +all-features = true [advisories] -ignore = [] +ignore = [ + # Upstream-blocked `zip 6.0.0` (Delivery M004 / Security S5). + # + # Path: root `eggress-cli` -> `eggup-archive 0.1.2` (and 0.2.0) -> + # `zip = "6.0.0"`. `eggup-archive` also carries the `zip` crate for its + # bounded Windows `.zip` extractor, so a lockfile update alone cannot + # remove it, and the direct `zip` dependency in `eggress-cli` is + # dev-only (test archive fixtures). + # + # Why the interim risk is acceptable: Eggup's extractor never calls + # `ZipArchive::extract`/`ZipStreamReader::extract` (the APIs named by + # these advisories). It walks entries itself, rejects symlinks, non-file + # entries, `enclosed_name() == None`, and `..`/absolute paths, and reads + # members through object-bound handles under finite size limits. Eggress + # additionally verifies the whole archive SHA-256 before extraction. + # + # Removal condition: delete these four entries (do not carry them + # forward) as soon as an `eggup-archive` release depending on + # `zip >= 9.0.0` is adopted. + # + # Owner: Delivery M004. Reviewed 2026-11-16. Re-review by 2027-05-01 + # even if no upstream release has landed; do not renew silently. + "RUSTSEC-2026-0367", + "RUSTSEC-2026-0368", + "RUSTSEC-2026-0369", + "RUSTSEC-2026-0429", +] # `rustls-pemfile` (RUSTSEC-2025-0134) was replaced by `rustls-pki-types` PEM # APIs (`CertificateDer::pem_slice_iter`, `PrivatePkcs8KeyDer::from_pem_slice`) @@ -12,6 +52,9 @@ ignore = [] allow = [ "MIT", "Apache-2.0", + # `target-lexicon` (build-dependency of `pyo3-build-config` in + # `eggress-python`) ships under the Apache-2.0 LLVM exception. + "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause", "BSD-3-Clause", "ISC", diff --git a/docs/CI_STATUS.md b/docs/CI_STATUS.md index 6625a398..12ceebc5 100644 --- a/docs/CI_STATUS.md +++ b/docs/CI_STATUS.md @@ -8,10 +8,10 @@ Egress uses deliberately small hosted CI. GitHub Actions is a smoke signal for o The repository has four hosted workflows: -- `.github/workflows/ci.yml`: one Ubuntu Rust job running format, Clippy, the default workspace test suite, bounded optional-compat and embed/outbound feature-boundary compile checks, a required local OpenSSH embed runtime regression, and fuzz-target compilation. The job installs `openssh-server` immediately before that runtime gate. A second `updater-matrix` job (ubuntu/macos/windows) runs `cargo test -p eggress-cli --locked --bin eggress update::` plus the `release_contract` / `cli_exit_codes` suites. +- `.github/workflows/ci.yml`: one Ubuntu Rust job running format, Clippy, the default workspace test suite, bounded optional-compat and embed/outbound feature-boundary compile checks, a required local OpenSSH embed runtime regression, and fuzz-target compilation. The job installs `openssh-server` immediately before that runtime gate. A second `updater-matrix` job (ubuntu/macos/windows) runs `cargo test -p eggress-cli --locked --bin eggress update::` plus the `release_contract` / `cli_exit_codes` suites. A third `advisories` job installs a pinned `cargo-deny` (`cargo install cargo-deny --locked --version 0.19.0`) and runs `cargo deny --workspace check`. - `.github/workflows/python-test.yml`: one path-scoped Ubuntu/Python 3.12 smoke job for the Python binding and compatibility packages. - `.github/workflows/publish-python.yml`: a real release path, not a smoke job. It fires on every `v*` tag push, validates the tag against the workspace version, builds ten `cp39-abi3` wheel families (Linux x86_64/aarch64/armv7l GNU + musl, macOS x86_64/arm64, Windows x86_64/ARM64) plus an sdist, smoke-tests them (native per-platform smokes, musl/ARMv7 execution smokes, exhaustive 3.9–3.15 compat smoke on Linux x86_64), and publishes to PyPI through the protected `pypi` GitHub environment (TestPyPI only via manual dispatch). -- `.github/workflows/release-binaries.yml`: a real release path, not a smoke job. It fires on every `v*` tag push (or manual dispatch against an existing tag), validates the tag with `scripts/release-preflight.sh`, builds the five canonical `eggress-cli` target archives with default features, smoke-tests both executables natively, and creates/updates the GitHub Release with archives, SHA-256 sidecars, and installers. Ordinary CI never builds this matrix. +- `.github/workflows/release-binaries.yml`: a real release path, not a smoke job. It fires on every `v*` tag push (or manual dispatch against an existing tag), validates the tag with `scripts/release-preflight.sh`, then runs the dependency advisory gate (`cargo deny --workspace check`) so a tag cannot ship with an unreviewed advisory, builds the five canonical `eggress-cli` target archives with default features, smoke-tests both executables natively, and creates/updates the GitHub Release with archives, SHA-256 sidecars, and installers. Ordinary CI never builds this matrix. There are no crates-publishing workflows, cross-platform ordinary-CI matrices, or mandatory compatibility-evidence uploads. Pushing a version tag is a release action; ordinary pushes never publish anything. @@ -102,7 +102,7 @@ Run these only when their trigger condition applies: | Check | Trigger | |---|---| -| `cargo deny check` | Dependency, feature, or license-policy changes; release preparation | +| `cargo deny --workspace check` | Dependency, feature, or license-policy changes; release preparation; CI `advisories` job and release preflight | | `cargo audit --ignore RUSTSEC-2023-0071` | Dependency changes; release preparation | | optional-compat compile gate above | SSH, QUIC/H3, SSR/`pproxy-legacy`, legacy-crypto, or daemon code paths | | pproxy differential/oracle suites | Compatibility behavior, manifests, URI translation, or pproxy namespace changes | @@ -113,6 +113,8 @@ Run these only when their trigger condition applies: The commands remain documented in `docs/TESTING.md`, `docs/DIFFERENTIAL_TESTING.md`, and `AGENTS.md`. Their existence does not make them routine merge gates. +The advisory gate runs `cargo deny --workspace check`, not a bare `cargo deny check`: the root manifest is the `eggress-bench` package (not a virtual manifest), so a root-only graph silently omits `eggress-cli` — and with it `eggup-archive -> zip` — and prints a misleading `advisories ok`. `deny.toml` sets `[graph] all-features = true` so optional-only dependencies (`russh`, QUIC/H3, the `zip` subtree) are scanned as well. `deny.toml` carries exactly four commented `zip 6.0.0` ignores; add nothing to that list without the same owner/removal-condition treatment. + ## Evidence and completion records Ordinary implementation work requires a clear commit message and passing relevant tests. It does not require generated parity reports, uploaded workflow artifacts, large completion documents, screenshots, or copied command transcripts. diff --git a/docs/CONFIG_REFERENCE.md b/docs/CONFIG_REFERENCE.md index f88ce06b..bfd54e7d 100644 --- a/docs/CONFIG_REFERENCE.md +++ b/docs/CONFIG_REFERENCE.md @@ -524,14 +524,22 @@ Leaf matchers: | `destination_port` | u16 | Exact port | | `destination_port_range` | `[u16; 2]` | Port range `[min, max]` | | `destination_port_set` | `[u16]` | Set of ports | -| `destination_cidr` | string | CIDR match on target | -| `source_cidr` | string | CIDR match on client source | +| `destination_cidr` | string | CIDR match on the literal target IP | +| `source_cidr` | string | CIDR match on the literal client source IP | | `source_port` | u16 | Client source port | | `listener` | string | Listener name | | `protocol` | string | `http`, `socks4`, `socks5` | | `identity` | string | Client identity (username) | | `transport` | string | `tcp` or `udp` | +CIDR rules match literal IP addresses only — no DNS resolution happens during +route evaluation, so a domain target never matches `destination_cidr` (even +when the name resolves into the range), and an upstream group resolves names +remotely. IPv4-mapped IPv6 literals (`::ffff:10.0.0.1`) are canonicalized +before matching and therefore match the equivalent IPv4 CIDR. A `reject` rule +that uses a private/reserved `destination_cidr` without a host condition emits +a non-fatal warning: such a rule is not a complete private-network ACL. + --- ## `[routing]` @@ -551,9 +559,32 @@ Value can be `"direct"`, `"reject"`, or a group ID reference. | `bind` | string | `"127.0.0.1:9090"` | Admin HTTP bind address | | `enabled` | bool | false | Enable admin server | | `metrics` | bool | false | Enable `/metrics` endpoint | +| `allowed_hosts` | `[string]` | bind-derived | Extra `Host` values accepted by the admin server | | `pac` | table | none | PAC file configuration | | `static_content` | table array | none | Static content routes | +`allowed_hosts` defends against DNS rebinding: the admin server rejects a +request whose `Host` header is not allowlisted (generic `400`, checked before +authentication and before any body is read). Entries are host names or IP +literals, optionally with a port; matching is case-insensitive and +port-insensitive, IPv6 may be bracketed, and wildcards are rejected. + +The effective allowlist is the configured entries plus defaults derived from +`bind`: + +- loopback or wildcard bind: the bind host, `localhost`, `127.0.0.1`, `::1` + (so `http://127.0.0.1:9090` works with no configuration); +- any other non-loopback bind: the bind host and `localhost`. + +When admin is reached through a reverse proxy or a DNS name, list that host +explicitly. `X-Forwarded-Host` is ignored. `POST /-/route-explain` also requires +`Content-Type: application/json` and, when an `Origin` header is present, an +allowlisted origin host; `Origin: null` is rejected unless `null` is listed. + +Admin listens on plaintext HTTP (there is no native admin TLS). A non-loopback +bind emits a warning; use loopback with a VPN/SSH tunnel or a TLS-terminating +reverse proxy. Non-loopback admin binds additionally require authentication. + ### `[admin.auth]` Configure exactly one authentication method for non-loopback admin binds. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 4d790472..d05abd95 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -225,6 +225,20 @@ Behavior: background update checks, and never falls back to Cargo/source builds. Unwritable destinations and unsupported prebuilt targets fail before mutation with an actionable message. +- Requires only a **trusted system `curl`**: `/usr/bin/curl` or `/bin/curl` + on Unix, `%SystemRoot%\System32\curl.exe` on Windows. `PATH` is not scanned, + a symlinked or group/other-writable tool is refused, and a missing trusted + binary fails before anything is downloaded. SHA-256 is computed in-process, + so `sha256sum`/`shasum` are not needed and cannot influence verification. +- Uses a private staging directory: one unpredictable, owner-only (`0700`) + directory per run, `create_new` download files that never overwrite or follow + a symlink, and a second hash of the archive immediately before extraction. A + planted or replaced staging path fails the update closed and leaves the + installed pair untouched. +- Every update URL is HTTPS (`curl` also runs with `--proto =https + --tlsv1.2`). Release binaries ignore `EGRESS_UPDATE_BASE_URL` and reject + `file://`; that offline fixture hook exists only in test builds or builds + with the non-default `update-fixtures` cargo feature. - Does not touch a Python environment. There is no background update check. Re-running the installer (latest or pinned) remains a supported equivalent; @@ -300,3 +314,11 @@ glibc the build runner happens to provide. - `eggress update` reports a missing/mismatched sibling `pproxy`: reinstall with the bootstrap installer to repair the version-aligned pair, then update normally. +- `eggress update` reports no trusted `curl`: install `curl` as a system + package so it exists at `/usr/bin/curl` or `/bin/curl` + (`%SystemRoot%\System32\curl.exe` on Windows). A `curl` found only earlier on + `PATH` is intentionally ignored; use the bootstrap installer if the platform + has no system `curl`. +- `eggress update` reports a refused staging path: another update transaction + (or a planted path) owns that file. Nothing was replaced — rerun the update; + a persistent failure means the temp directory is not private to your user. diff --git a/docs/PPROXY_MIGRATION.md b/docs/PPROXY_MIGRATION.md index 270cce27..4253d21b 100644 --- a/docs/PPROXY_MIGRATION.md +++ b/docs/PPROXY_MIGRATION.md @@ -105,6 +105,29 @@ authoritative per-scheme status rather than a duplicated table here. -r http://proxy1:8080 -r socks5://proxy2:1080 ``` +### Listener credentials and `--auth` + +Listener credentials belong to the listener URI. pproxy's documented form is the +fragment (`-l http://0.0.0.0:8080#user:pass`); Eggress also accepts userinfo +(`-l http://user:pass@0.0.0.0:8080`). The translator emits `[listeners.auth]` +from those credentials whether or not `--auth` is present, so `--auth` is **not** +what turns authentication on. + +`--auth SECONDS` is the source-IP re-authentication **reuse interval** for +credentials that came from the listener URI. The pproxy default is `2592000` +seconds (30 days), including when the flag is omitted. Reuse is process-global, +keyed only by client IP, and shared across every credentialed compatibility +listener; compatibility startup prints one warning that names the default, the +IP-only key, and the shared cache. + +Migration choices: + +- keep pproxy behavior: rely on the URI credentials and the default 30-day + reuse interval, and bind to loopback or a trusted network; +- tighten reuse: pass `--auth 0` so clients re-authenticate per connection; +- remove reuse entirely: migrate to native `[listeners.auth]`, which verifies + every connection and has no IP-keyed cache. + ## Common pproxy Commands -> Eggress Equivalents ### pproxy @@ -164,8 +187,10 @@ the notes below call out the boundaries users most often misread: - **`-d`, `-v`, `--ssl`, `-b`, `--reuse`, `--pac`, `--get`, `--auth`, `--test`** — parsed with compatibility or native-equivalent semantics (tracing defaults, TLS config, reject rules, `SO_REUSEPORT`, admin - PAC/static content, bounded auth reuse, in-process upstream test). See - `cli.*` entries in the manifest for the exact tier. + PAC/static content, bounded source-IP auth reuse with a 30-day default, + in-process upstream test). `--auth` changes only the reuse interval, not + whether authentication happens. See `cli.*` entries in the manifest for the + exact tier. - **SSH** — upstream-only behind the opt-in `ssh` feature; listeners are refused. Host-key acceptance is warning-bearing to match pproxy's permissive behavior. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index efa66328..d8d237c7 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -10,8 +10,10 @@ pre-transition phase records are provenance under `plans/archive/phase-records/` ## Current Status -All core milestones are complete. The Rust-native CLI and runtime are -production-ready with broad pproxy 2.7.9 behavioral compatibility. See the +All core capability milestones are complete. A 2026-11-16 security audit opened +a bounded corrective program (see below); it restores existing security +invariants and is not a new capability phase. The Rust-native CLI and runtime +remain production-ready with broad pproxy 2.7.9 behavioral compatibility. See the active [compatibility matrix](parity/PPROXY_PRACTICAL_COMPATIBILITY_MATRIX.md) and [capability manifest](parity/pproxy_capability_manifest.toml). @@ -74,6 +76,53 @@ crates.io, GitHub Release with the five prebuilt CLI archives + installers). The workspace is at 1.0.12; the next version bump follows the lockstep procedure in `docs/release/RELEASE_PROCESS.md`. +### Closed maintenance — security remediation (2026-11-16 audit) + +A 2026-11-16 security audit opened a bounded corrective program at +[`plans/subsystems/security-hardening-roadmap.md`](../plans/subsystems/security-hardening-roadmap.md); +it is implemented and closed as of 2026-11-16. It restored existing security +invariants without adding proxy capabilities or changing pproxy compatibility +tiers. + +- **S1/TLS** — bundled roots included a distrusted emSign root and the webpki + verifier accepted known-compromised intermediates (CVE-2026-111943). rustls, + rustls-webpki, webpki-roots, rustls-platform-verifier, quinn, and tokio now + resolve to fixed versions + ([closure](../plans/closure/transports/004-status.md)). +- **S2/SSH** — optional `ssh` moved to `russh 0.65.2`, clearing + RUSTSEC-2026-0492/-0495 and the `crypto-bigint`/`ctutils` path with known-hosts + policy and OpenSSH regression intact + ([closure](../plans/closure/transports/005-status.md)). +- **S3/SOCKS4+UDP** — SOCKS4 enforces the full pproxy `user:pass` user ID and + no longer seeds the reuse cache on a username-only match; UDP applies + `allow_private_egress` after DNS on every locally resolving path; CGNAT, + NAT64, 6to4, Teredo, and selected IETF special-purpose ranges are classified; + non-loopback auth without TLS warns + ([closure](../plans/closure/protocols-edge/003-status.md)). +- **S4/CIDR+admin** — IPv4-mapped IPv6 is canonicalized before CIDR matching, + the literal-IP-only CIDR contract is documented and warned about, and admin + validates `Host`/`Origin`/JSON `Content-Type` with a non-loopback plaintext + warning + ([closure](../plans/closure/routing-health-observability/003-status.md)). +- **S5/updater+gate** — release builds ignore `EGRESS_UPDATE_BASE_URL` and + reject `file://`, SHA-256 is computed in-process, `curl` resolves only from + fixed system locations, staging is private/create-new with a closed + verify/extract window, `system-proxy inspect --json` is redacted, and + `cargo deny --workspace check` runs in CI and release preflight + ([closure](../plans/closure/delivery/004-status.md)). +- **S6/compat** — the pproxy `--auth` reuse contract is documented and warned + about, and UDP remote errors, `translate --annotate`, and the reverse compat + IR redact credentials + ([closure](../plans/closure/parity-compat/003-status.md)). + +The workspace `fmt`/`clippy`/`test` gate, the documented feature slices, the +embed OpenSSH regression, and `cargo deny --workspace check` all pass. The only +remaining audit item is the four `zip 6.0.0` advisories in the updater graph, +tracked as a narrow, commented `deny.toml` exception with an owner and review +date pending an upstream `eggup-archive` release with `zip >= 9.0.0`. No version +bump, tag, or publication was authorized; `v1.0.12` remains the current +published release. + ### Active maintenance — Eggup archive/pair self-update convergence Delivery M003 is registered at diff --git a/docs/SECURITY_REVIEW.md b/docs/SECURITY_REVIEW.md index 1016869f..ab0932fa 100644 --- a/docs/SECURITY_REVIEW.md +++ b/docs/SECURITY_REVIEW.md @@ -148,10 +148,13 @@ Adversaries may include malicious clients on the network, compromised upstream p - Jump chains through reverse are not supported. - On-wire version is fixed at "user:pass + 1-byte handshake + bidirectional TCP relay" -- no versioning or upgrade path. -**TLS Insecure Mode** (`eggress-transport-tls/src/client.rs:49-51`): -- `with_insecure()` creates an `InsecureVerifier` that accepts any certificate. +**TLS Insecure Mode** (`eggress-transport-tls` client builder): +- `with_insecure()` creates an `InsecureVerifier` that accepts any certificate and any handshake signature without validation. - Documented as "for testing only — never use in production." -- Not exposed in configuration; only available via programmatic API. +- **Reachable from configuration, not API-only.** The native URI grammar accepts `?insecure` / `?insecure=true` per hop, and `eggress-cli` and `eggress-runtime` compile the `insecure-tls` feature unconditionally, so such chains load and execute in shipped CLI builds. +- Config compilation emits one warning per upstream that selects it, naming the upstream plus the affected hop indexes and protocols only — endpoints, credentials, and the source URI are never echoed — before any chain executes. +- It stays explicit: no build, root-load, or handshake error falls back to insecure verification, and `tls_override` combined with a per-hop `insecure=true` fails closed. +- Insecure QUIC/H3 remains behind the separate `insecure-quic` feature; config compilation rejects insecure QUIC/H3 hops in default builds. **Unsupported Protocol/Transport Combinations** (`eggress-core/src/capability.rs`): - `classify_upstream_chain()` explicitly reports `UnsupportedProtocol` or `UnsupportedChain` for: @@ -278,6 +281,46 @@ Adversaries may include malicious clients on the network, compromised upstream p - `/target`, `/dist`, `crates/eggress-python/dist/`, `*.so`, `*.pyc`, `__pycache__/`, `*.egg-info/`, `.venv/` are all gitignored. - Built wheels and sdist archives are not committed to the repository. +### Self-Update and Distribution Trust + +`eggress update` is the only command that writes executables, so its inputs are +treated as untrusted: + +- **Authority**: discover, download, verify, stage, execute, replace — in that + order. Release discovery accepts only an exact `vX.Y.Z` stable tag from the + GitHub Releases API; there is no prerelease, branch, or alternate-source + fallback. +- **URL policy**: every update URL must be `https://` and `curl` additionally + runs with `--proto =https --tlsv1.2`. The `file://` + `EGRESS_UPDATE_BASE_URL` + offline fixture hook is compiled only for tests or the non-default + `update-fixtures` feature; release/default binaries never read that variable + and reject every non-HTTPS URL. +- **Tool trust**: `curl` is resolved only from fixed system locations + (`/usr/bin/curl`, then `/bin/curl`; `%SystemRoot%\System32\curl.exe` on + Windows). `PATH` is never scanned, and a symlinked, non-regular, or + group/other-writable candidate is refused. The SHA-256 digest of the archive + is computed in-process with `sha2`; `sha256sum`/`shasum` are not consulted, + so a `PATH`-planted tool cannot influence the integrity decision. A missing + or untrusted tool fails before any download or mutation. +- **Staging**: one unpredictable, owner-only (`0700`) directory per transaction, + created atomically. Output files are opened with `create_new` (no overwrite, + no symlink following) and `curl` writes into that already-open handle rather + than re-resolving a path. The archive is re-hashed immediately before + extraction, so a post-verification replacement fails closed. +- **Output**: the `.sha256` sidecar remains the integrity gate; both staged + executables must report exactly the release tag and agree with each other + before the pair is replaced. `system-proxy inspect --json` serializes only + redacted settings, so OS/environment `user:pass@` proxy credentials cannot be + copied out of diagnostics. +- **Privilege**: no `sudo`/UAC escalation, no shell/PATH mutation, no Cargo or + source fallback, no background checks. The updater never executes downloaded + data — only the staged, checksum-verified pair is run for version checks. + +**Supply chain**: CI and the release preflight run `cargo deny --workspace check` +over the all-features graph (advisories, bans, licenses, sources). The only +advisory ignores are the four tracked `zip 6.0.0` IDs inherited through +`eggup-archive`; they carry an owner and a removal condition in `deny.toml`. + ### Resource Management **Task Leaks on Malformed Clients**: @@ -308,12 +351,12 @@ Adversaries may include malicious clients on the network, compromised upstream p 5. **Input size limits**: HTTP request/response heads are bounded (32KB, 128 headers). 6. **Config validation**: Duplicate names, invalid references, and incompatible protocol/transport combos are rejected at load time. 7. **Capability classification**: Explicit `UnsupportedProtocol`/`UnsupportedChain` results prevent silent fallback to unsupported modes. -8. **TLS certificate verification**: System root store by default; insecure mode is API-only with documentation warnings. +8. **TLS certificate verification**: Bundled Mozilla root set via `webpki-roots` by default (not the OS certificate store); insecure mode is explicit, warned at config compile, documented, and never used as a fallback. 9. **Admin loopback default**: Admin server binds to `127.0.0.1` unless explicitly configured otherwise. 10. **No `unsafe` code**: Workspace-wide `unsafe_code = "deny"` prevents memory safety issues. 11. **No OpenSSL dependency**: Uses `rustls` with `ring` crypto provider, eliminating C FFI attack surface. 12. **Atomic config reload**: `ArcSwap` for lock-free reads; only hot-reloadable fields are swapped. -13. **Unsupported protocol diagnostics**: pproxy compat layer produces structured `UnsupportedFeature` errors for SSH listeners, SSH upstreams when the optional feature is absent, Unix (upstream), and other unsupported protocols. No silent fallback to direct or different protocols. The optional SSH compatibility path accepts host keys only to match pproxy and emits a warning. +13. **Unsupported protocol diagnostics**: pproxy compat layer produces structured `UnsupportedFeature` errors for SSH listeners, SSH upstreams when the optional feature is absent, Unix (upstream), and other unsupported protocols. No silent fallback to direct or different protocols. The optional SSH compatibility path accepts host keys only to match pproxy and emits a warning. The optional SSH transport is pinned to `russh` 0.65.x (closing RUSTSEC-2026-0492/-0495 and the `crypto-bigint`/`ctutils` timing advisories); verified policies require a `known_hosts` match, a lookup error fails closed, and certificate host keys are rejected rather than projected onto a plain key. 14. **Python binding security**: Exception strings do not leak raw Rust errors; `repr()` uses Python class names; translation warnings redact credentials; no import-time side effects; context manager ensures cleanup. 15. **Transparent proxy privilege separation**: Transparent proxy requires explicit `CAP_NET_ADMIN` or root; the listener validates `SO_ORIGINAL_DST` availability at startup and fails fast if unavailable. 16. **Transparent proxy loop prevention**: Connections destined to the proxy's own listen address are rejected to prevent forwarding loops. diff --git a/docs/URI_GRAMMAR.md b/docs/URI_GRAMMAR.md index 9c5685b5..27f9f0b9 100644 --- a/docs/URI_GRAMMAR.md +++ b/docs/URI_GRAMMAR.md @@ -36,6 +36,22 @@ Rules: `__` separates hops (`___` rejected as duplicate separator); unbracketed `@`; credentials are percent-decoded; SSH defaults to port 22; port 0 rejected (except Unix); unmatched brackets fail closed. +## Query parameters + +`?rule=` selects a routing rule for the hop. + +`?insecure` (equivalently `?insecure=true`) marks the hop as an explicit +certificate-verification bypass: the TLS peer certificate for that hop is not +validated. It is reachable from configuration, not only from the API — +`eggress-cli` and `eggress-runtime` compile the `insecure-tls` feature +unconditionally. Configuration compilation warns once per upstream that +selects it, naming the upstream id plus the affected hop indexes and protocols +only (never endpoints, credentials, or the source URI), before any chain +executes. Insecure QUIC/H3 hops additionally require the `insecure-quic` build +feature and are rejected at config compile by default. A verification, build, +or root-load failure never falls back to this mode: the hop either verifies or +fails closes. + ## Example URI Format ``` @@ -48,6 +64,7 @@ http://[::1]:8080 http://[2001:db8::1]:1080 http://proxy:8080?rule=regex http+tls://proxy:443 +socks5+tls://proxy:1080?insecure shadowsocks://aes-256-gcm:secret@proxy:8388 trojan://password@proxy:443 ``` diff --git a/docs/cli/PPROXY_CLI_INVENTORY.md b/docs/cli/PPROXY_CLI_INVENTORY.md index 43f1c3d1..8abe8fc8 100644 --- a/docs/cli/PPROXY_CLI_INVENTORY.md +++ b/docs/cli/PPROXY_CLI_INVENTORY.md @@ -20,7 +20,7 @@ on `pproxy.server.main` at the pinned oracle commit. | `--ssl SSLFILE` | one | optional | listener certificate/key configuration | | `--pac PAC` | one | optional | admin PAC route | | `--get GETS` | one | repeatable | admin static content (`PATH,FILE`) | -| `--auth AUTHTIME` | integer | default `2592000` | bounded source-IP auth reuse when listener credentials exist | +| `--auth AUTHTIME` | integer | default `2592000` | source-IP re-authentication reuse interval for listener-URI credentials; `0` disables practical reuse | | `--sys` | flag | false | apply after bind and restore on shutdown/failure | | `--reuse` | flag | false | set SO_REUSEPORT before TCP bind where supported | | `--daemon` | flag | false | parsed, then rejected before startup (exit 5) | @@ -34,6 +34,15 @@ unknown options, malformed URI values, and unsupported options fail before any listener or system-proxy side effect. Parser errors use exit code 2; unsupported features use exit code 5. +Listener credentials are not a flag: they come from the listener URI +(`-l http://:8080#user:pass` in pproxy's fragment form, or +`-l http://user:pass@:8080` userinfo). `[listeners.auth]` is generated from +them, and `--auth AUTHTIME` only sets the source-IP re-authentication reuse +interval (default `2592000` seconds / 30 days when omitted; `0` disables +practical reuse). The compatibility process emits one startup warning +describing the process-global, source-IP-keyed, cross-listener cache; the +warning never contains listener URIs or credentials. + `-d` and `-v` follow argparse count semantics, including repeated separate flags and short clusters such as `-dd`, `-vv`, and `-dv`. Explicit `RUST_LOG` controls tracing filtering; compatibility verbosity events use the existing diff --git a/docs/release/RELEASE_PROCESS.md b/docs/release/RELEASE_PROCESS.md index 2b31d364..e3a34210 100644 --- a/docs/release/RELEASE_PROCESS.md +++ b/docs/release/RELEASE_PROCESS.md @@ -51,10 +51,17 @@ cargo test --workspace --locked Run dependency and advisory checks because release inputs are changing: ```bash -cargo deny check +cargo deny --workspace check cargo audit --ignore RUSTSEC-2023-0071 ``` +`--workspace` is not optional: the root manifest is the `eggress-bench` +package, so a bare `cargo deny check` roots the graph there and silently skips +`eggress-cli` (and `eggup-archive -> zip`), printing a misleading +`advisories ok`. `deny.toml` audits the all-features graph and carries only the +tracked `zip 6.0.0` ignores; the release workflow runs the same command in its +preflight job, so a tag cannot ship with an unreviewed advisory. + Run specialized interoperability, Python, performance, or cross-platform checks only when the release contains relevant changes or makes claims that depend on them. The selection policy is in `docs/TESTING.md`. For example, a release containing SSH/embed changes must run the required OpenSSH embed regression (`EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat --test ssh`); a skipped fixture is not release evidence for such a version. ## 2. Check package metadata diff --git a/docs/security/OPEN_PROXY_PREVENTION.md b/docs/security/OPEN_PROXY_PREVENTION.md index a368a8ee..58accaff 100644 --- a/docs/security/OPEN_PROXY_PREVENTION.md +++ b/docs/security/OPEN_PROXY_PREVENTION.md @@ -16,6 +16,11 @@ Config validation emits warnings for non-loopback binds without authentication: - **Admin server**: Warning if `bind` is not loopback - **Reverse control**: Warning if `control_bind` is not loopback and no auth +It also warns when a non-loopback listener has password authentication, no +`[listeners.tls]`, and an HTTP/SOCKS protocol in its protocol set, because the +credential would otherwise cross the network in clear. The warning is advisory +only: the configuration still loads and runs. + ### Loopback Detection A bind address is considered loopback if it resolves to `127.x.x.x` or `::1`. @@ -35,21 +40,32 @@ A listener is considered authenticated if it has any of: - No built-in authentication - Client IP logged at connection time - Config validation warns on non-loopback +- Config validation warns when password auth is configured without TLS ### SOCKS4/4a -- No built-in authentication +- Optional username/password via `[listeners.auth]` +- The credential is carried in the SOCKS4 user-ID field as the full + `user:pass` string, matching pproxy 2.7.9 (`userid in users`, where `users` + holds `user:pass` strings); SOCKS4 has no separate password field, so a + username-only user ID is rejected +- A rejected attempt fails before any tunnel is created and never seeds the + auth-reuse cache; only a full-credential success is cached, and the cached + identity is the authenticated username - Config validation warns on non-loopback +- Config validation warns when password auth is configured without TLS ### SOCKS5 -- Optional username/password auth +- Optional username/password auth (RFC 1929, constant-time compare) - Config validation warns on non-loopback if no auth +- Config validation warns when password auth is configured without TLS ### Shadowsocks - Built-in password authentication via AEAD -- No warning needed — cryptographically authenticated +- No warning needed — cryptographically authenticated; the auth-without-TLS + warning does not apply ## Administrative Controls @@ -71,9 +87,23 @@ Config validation tests verify: - Non-loopback listener without auth produces warning - Loopback listener does not produce warning - Authed listener does not produce warning +- Non-loopback HTTP/SOCKS4/SOCKS5 password auth without TLS produces the + auth-without-TLS warning (`listeners[].tls` path) and the message never + echoes the username or password +- Authed listener with `[listeners.tls]` does not produce the auth-without-TLS + warning +- Authed Shadowsocks and Trojan listeners do not produce the auth-without-TLS + warning +- Loopback HTTP password auth without TLS does not produce the + auth-without-TLS warning - Non-loopback admin produces warning - Loopback admin does not produce warning - Non-loopback reverse control without auth produces warning - Authed reverse control does not produce warning -See `crates/eggress-config/src/validate.rs` tests. +SOCKS4 accept tests (`crates/eggress-server/src/accept/tests.rs`) verify the +full `user:pass` credential is accepted while username-only, wrong-password, +and empty user IDs are rejected without seeding the reuse cache. + +See `crates/eggress-config/src/validate/tests.rs` and +`crates/eggress-server/src/accept/tests.rs`. diff --git a/docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md b/docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md index aa3cfb31..4237738d 100644 --- a/docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md +++ b/docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md @@ -4,23 +4,47 @@ This document covers the security trade-offs when running Eggress in pproxy comp ## Open Proxy Risks in pproxy Compat Mode -### No Authentication by Default +### Authentication Comes From the Listener URI, Not `--auth` -pproxy accepts connections without authentication unless the user explicitly adds `--auth` to the command line. The eggress compat translator faithfully reproduces this: a pproxy-style `-l socks5://0.0.0.0:1080` without `--auth` generates a `[listeners]` block with no `[listeners.auth]`. +pproxy listener credentials are carried by the listener URI itself. pproxy's documented form is the URI fragment (`-l http://0.0.0.0:8080#user:pass`); Eggress also accepts userinfo (`-l http://user:pass@0.0.0.0:8080`). On HTTP/SOCKS-style listeners the compat translator copies those credentials into `[listeners.auth]` whenever the URI carries both a username and a password, whether or not `--auth` appears on the command line. (Shadowsocks and Trojan use the same URI fields for their protocol credentials instead.) A listener URI without credentials stays open, which is pproxy's default. + +`--auth N` is **not** an authentication switch. It sets the source-IP re-authentication **reuse interval** for credentials that came from the listener URI. The pproxy default is `2592000` seconds (30 days), including when the flag is omitted. **Contrast with eggress-native:** A hardened eggress config would include `[listeners.auth]` on any non-loopback listener and config validation would emit a warning. ```bash -# pproxy compat (no auth — open proxy) +# pproxy compat (no credentials — open proxy) eggress pproxy run -- -l socks5://0.0.0.0:1080 -# eggress-native (explicit auth) +# pproxy compat (credentials in the URI fragment, pproxy's documented form) +eggress pproxy run -- -l 'socks5://0.0.0.0:1080#user:pass' + +# eggress-native (explicit auth, no reuse cache) eggress --config hardened.toml # with [listeners.auth] configured ``` +### Source-IP Authentication Reuse (30-day default, process-global) + +When compatibility listeners carry credentials, pproxy remembers a successful authentication per client IP and skips re-authentication for `--auth` seconds. Eggress reproduces that behavior exactly, including its scope: + +- one reuse cache per compatibility process, bounded and monotonic-expiry; +- keyed **only by source IP** — not by listener, port, or username; +- shared across **all** credentialed compatibility listeners in that process. + +Consequences: + +- A client that authenticates once to any credentialed compatibility listener is trusted, for the reuse interval, by every other credentialed compatibility listener in the same process. +- `--auth N` changes only the interval; `--auth 0` disables practical reuse (entries expire immediately, so clients re-authenticate per connection). +- Compatibility startup emits one warning naming the 30-day default, the source-IP-only key, and the cross-listener cache. The warning never contains a listener URI or credential. +- The cache holds at most 4096 entries and evicts expired entries lazily, so client volume cannot grow it without bound. + +**Recommendation:** bind compatibility listeners to loopback or a trusted network, and prefer native `[listeners.auth]` for stricter deployments: native authentication verifies every connection and has no IP-keyed reuse cache. + +This reuse is the pinned `pproxy==2.7.9` behavior (`AuthTable._auth` keyed by IP with `authtime = 86400 * 30`). It is documented and warned about rather than changed, because changing it would break drop-in compatibility. + ### Non-Loopback Binds Without Warnings at Translate Time -The `pproxy translate` command generates TOML from pproxy arguments. It does not add `[listeners.auth]` unless `--auth` was in the original args. The generated TOML is valid and will produce config validation warnings at runtime, but the `translate` output itself does not include auth. +The `pproxy translate` command generates TOML from pproxy arguments. It copies listener credentials into `[listeners.auth]` when the listener URI carries them, but it never invents credentials that were not supplied, and `translate` itself does not run open-listener validation. Config validation emits open-listener warnings when the translated configuration is actually started. **Recommendation:** Always run `eggress pproxy check` after `translate` to review security warnings before starting the service. @@ -64,7 +88,8 @@ A strict mode could block both DNS-resolved and literal private IPs, but the def | Surface | pproxy compat default | Hardened eggress-native | |---------|----------------------|------------------------| -| Listener authentication | None (unless `--auth`) | `[listeners.auth]` required on non-loopback | +| Listener authentication | From listener URI credentials; none when the URI has none | `[listeners.auth]` required on non-loopback | +| Auth reuse | Process-global, source-IP keyed, 30-day default (`--auth`) | Per-connection verification, no reuse cache | | Admin server | Enabled by default with `--pac` | Disabled unless explicitly enabled | | Standalone UDP | Available via `-ul` | Disabled (only `socks5_udp_associate`) | | TLS on listeners | Only with `--ssl` | `[listeners.tls]` on internet-facing | @@ -159,7 +184,8 @@ Review diagnostics for any security warnings before starting. | Setting | pproxy compat generated | Hardened recommended | |---------|------------------------|---------------------| | `bind` on listeners | From `-l` arg (often `0.0.0.0`) | `127.0.0.1` or `0.0.0.0` with auth | -| `listeners.auth` | Only with `--auth` | Always on non-loopback | +| `listeners.auth` | From listener URI credentials (`#user:pass` or `user:pass@`) | Always on non-loopback | +| `auth` reuse interval | `--auth` seconds, default `2592000` (30 days), source-IP keyed | Native auth: per connection | | `listeners.tls` | Only with `--ssl` | Always on internet-facing | | `upstreams[].uri` | From `-r` arg | `+tls` suffix | | `admin.bind` | `127.0.0.1:9090` (default) | Same, or disabled | diff --git a/docs/security/SECURE_CONFIGURATION.md b/docs/security/SECURE_CONFIGURATION.md index 45870103..02bd50bf 100644 --- a/docs/security/SECURE_CONFIGURATION.md +++ b/docs/security/SECURE_CONFIGURATION.md @@ -27,11 +27,23 @@ password_env = "EGGRESS_PROXY_PASSWORD" | Protocol | Built-in Auth | Notes | |----------|--------------|-------| | HTTP CONNECT | Optional (`[listeners.auth]`) | No auth by default; warns on non-loopback | -| SOCKS4/4a | Optional (`[listeners.auth]`) | No auth by default; warns on non-loopback | +| SOCKS4/4a | Optional (`[listeners.auth]`) | Credential is the full `user:pass` string in the SOCKS4 user-ID field (pproxy 2.7.9 semantics); username-only user IDs are rejected; warns on non-loopback | | SOCKS5 | Optional (`[listeners.auth]`) | Username/password via SOCKS5 handshake | | Shadowsocks | Built-in (AEAD) | Cryptographic auth via shared password; no warning needed | | Trojan | Built-in (TLS SNI) | Password-only auth; upstream-only | +**Auth without TLS.** When a listener binds to a non-loopback address, has +`[listeners.auth]`, and offers HTTP, SOCKS4, or SOCKS5 without +`[listeners.tls]`, config validation emits a warning: the credential crosses +the network in clear. Add `[listeners.tls]`, bind to loopback, or terminate TLS +in a trusted tunnel. Shadowsocks and Trojan listeners are exempt (their own +layer encrypts and authenticates), and the configuration is never rejected for +this. + +SOCKS4 has no password field. A SOCKS4 client must send the complete +`username:password` string as the user ID, because the listener compares the raw +user ID against the configured pair before creating any tunnel. + ### 2. TLS Configuration Use TLS for any listener exposed to untrusted networks. Shadowsocks and Trojan provide built-in encryption; TLS adds transport security to HTTP and SOCKS listeners. @@ -50,11 +62,13 @@ id = "secure-upstream" uri = "socks5+tls://upstream.example:1080" ``` -**TLS insecure mode** (`with_insecure()`) accepts any certificate. It is only available via the programmatic API and documented as "for testing only." Never use in production. +**Upstream trust roots.** Outbound TLS verification uses the Mozilla root set bundled through the `webpki-roots` crate. That is *not* the operating-system certificate store: the roots are compiled into the binary and change only when Eggress itself is updated, so a private CA installed in the OS store is not trusted automatically. Custom roots are a programmatic surface (`TlsClientConfigBuilder::with_custom_ca_pem`, surfaced to chain execution as `tls_override`); supplying them *replaces* the bundled set rather than extending it, and there is no TOML key for outbound trust roots in this release. + +**TLS insecure mode** (`?insecure` / `?insecure=true` on a hop URI, or `with_insecure()` in code) accepts any certificate, and any handshake signature, without validation. It is documented as "for testing only" and must never be used in production. It is reachable from configuration in shipped CLI builds, not only from the programmatic API: `eggress-cli` and `eggress-runtime` compile the `insecure-tls` feature unconditionally. Configuration compilation emits one warning per upstream that selects it, naming the upstream and the affected hop indexes and protocols (never endpoints, credentials, or the source URI), before any chain executes. Insecure QUIC/H3 additionally requires the separate `insecure-quic` feature and is rejected at config compile in default builds. ### 3. Admin Endpoint Security -The admin server exposes `/-/status`, `/-/config`, `/-/routes`, `/-/upstreams`, and `/-/metrics`. Configure authentication for non-loopback access; configured credentials protect every endpoint. +The admin server exposes `/-/status`, `/-/config`, `/-/routes`, `/-/upstreams`, `/-/reverse`, and `/-/metrics`, plus a dry-run `POST /-/route-explain`. Configure authentication for non-loopback access; configured credentials protect every endpoint. **Default:** `127.0.0.1:9090` (loopback only). @@ -68,14 +82,36 @@ metrics = true bearer_token_env = "EGGRESS_ADMIN_TOKEN" ``` -If remote admin access is required: +**Plaintext transport.** The admin listener speaks plaintext HTTP/1.1: there is no native admin TLS, and the `eggress` admin client rejects `https://` admin URLs. A non-loopback bind therefore puts Basic/Bearer credentials, status, metrics, and routing topology on the network in clear, and emits a config warning (in addition to the existing "no auth" warning). Remote admin access belongs to one of: + +1. loopback plus SSH port forwarding or a VPN +2. OS-level firewall rules restricting who can reach the port +3. a TLS-terminating reverse proxy in front of a loopback bind + +**Host and Origin validation (`allowed_hosts`).** The admin server validates the `Host` header of every request to block DNS-rebinding reads: a page on an attacker origin can resolve its own name to `127.0.0.1` and fetch the loopback admin port, so the header — not the socket address — decides whether a request is acceptable. + +```toml +[admin] +bind = "127.0.0.1:9090" +# Required when admin is reached through a reverse proxy or a DNS name. +allowed_hosts = ["admin.example", "127.0.0.1"] +``` + +The effective allowlist is the configured entries **plus** defaults derived from `bind`: + +- loopback bind, or a wildcard bind (`0.0.0.0` / `::`): the bind host, `localhost`, `127.0.0.1`, and `::1`, so `curl http://127.0.0.1:9090/-/status` works without configuration +- any other non-loopback bind: the bind host and `localhost` + +Matching is case-insensitive and port-insensitive (`Host: Admin.Example:9090` matches `admin.example`), and bracketed IPv6 forms are normalized. A missing, unparseable, or unlisted `Host` returns a generic `400 Bad Request` before authentication and before any body is read; the rejected value is never echoed. `X-Forwarded-Host` is ignored — only the actual `Host` header counts. Wildcard entries (`*`) are rejected at config validation. + +`POST /-/route-explain` additionally requires `Content-Type: application/json` (media type only; parameters such as `; charset=utf-8` are ignored) and rejects an `Origin` whose host is not allowlisted. A browser-style `Origin: null` is rejected unless the literal entry `null` is added to `allowed_hosts`. Both checks run before the body is read. -1. Keep admin on loopback and use SSH port forwarding or a VPN -2. If you must bind to a non-loopback address, use OS-level firewall rules to restrict access -3. Consider disabling metrics (`metrics = false`) if not needed — metrics are exposed on the same admin endpoint +**Migration note:** if you reach admin through a reverse proxy or a DNS name, add that host to `allowed_hosts` before upgrading; otherwise the request fails closed with `400`. Non-loopback admin binds are rejected unless authentication is configured. +**CIDR rules are not a name-based ACL.** See [Private IP Blocking and CIDR Rules](#private-ip-blocking-and-cidr-rules): `destination_cidr` matches literal IP targets only. + ### 4. UDP Security Settings UDP associations are owned by TCP control connections and support SOCKS5 UDP ASSOCIATE. Key settings: @@ -128,7 +164,28 @@ See [REVERSE_SECURITY.md](REVERSE_SECURITY.md) for full details. Eggress does not have built-in IP allowlist/denylist on listeners. Use routing rules to control which destinations are accessible: -**DNS rebinding protection:** Eggress rejects DNS resolutions that resolve to private/reserved IP ranges (loopback, link-local, RFC 1918, etc.). This prevents DNS rebinding attacks. Literal private IP targets (e.g., `192.168.1.1`) are allowed for pproxy compatibility with local/LAN proxy usage. +**CIDR rules are literal-IP-only.** `destination_cidr` and `source_cidr` compare against the literal address a client supplied. Route evaluation never resolves a name, so: + +- a rule matching `10.0.0.0/8` does **not** block `internal.example` even when that name resolves to `10.1.2.3`; +- a request routed through an upstream group is resolved by the upstream, so no local CIDR check can see the address the upstream connects to; +- an IPv4-mapped IPv6 literal (`::ffff:10.0.0.1`) is canonicalized before matching, so it matches the same `10.0.0.0/8` rule as `10.0.0.1` and cannot be used to bypass one. + +Eggress emits a non-fatal config warning when a `reject` rule uses a private/reserved `destination_cidr` and no host condition, because that rule is not a complete private-network ACL. For name-based protection use the egress guard below or a trusted upstream; CIDR rules complement those controls, they do not replace them. + +**DNS rebinding protection:** Eggress rejects DNS resolutions that resolve to private/reserved IP ranges (loopback, link-local, RFC 1918, CGNAT `100.64.0.0/10`, IPv6 unique-local, NAT64 `64:ff9b::/96`, 6to4 `2002::/16`, Teredo `2001::/32`, documentation/benchmarking/ORCHID special-purpose blocks, and IPv4-mapped forms of the IPv4 ranges). This prevents DNS rebinding attacks. Literal private IP targets (e.g., `192.168.1.1`) are allowed for pproxy compatibility with local/LAN proxy usage. + +**UDP private egress:** `allow_private_egress` (default `true` for pproxy compatibility) governs the locally resolving UDP paths — standalone SOCKS5 UDP, SOCKS5 UDP ASSOCIATE, and standalone Shadowsocks UDP. When it is `false`, literal private/reserved datagram targets are rejected before a flow is created, and a domain target is checked after the single DNS lookup: every resolved address is filtered through the same private/reserved classifier and a resolution whose answers are all non-public is dropped (no datagram is sent, no flow is created). Setting it to `false` therefore closes domain-based private-network access, not just literal addresses: + +```toml +[[listeners]] +name = "udp-in" +bind = "127.0.0.1:1080" +protocols = ["socks5"] + +[listeners.udp] +enabled = true +allow_private_egress = false +``` ```toml # Block access to internal networks @@ -184,12 +241,46 @@ chown root:root /etc/eggress/config.toml Never commit config files with credentials to version control. +### 8. Self-Update Trust Boundary + +`eggress update` installs GitHub Release binaries only after checksum and staged +candidate verification. Its trust boundary is deliberately narrow: + +- **No source override.** Release and default builds ignore + `EGRESS_UPDATE_BASE_URL` and reject every non-HTTPS update URL. The + `file://` fixture hook exists only in test builds or builds with the + non-default `update-fixtures` cargo feature; never ship a binary built with + that feature. +- **Trusted tools only.** `curl` must exist at `/usr/bin/curl` or `/bin/curl` + (`%SystemRoot%\System32\curl.exe` on Windows). `PATH` is not scanned, and a + symlinked or group/other-writable tool is refused. SHA-256 is computed + in-process, so `sha256sum`/`shasum` are not required and cannot influence + verification. +- **Private staging.** Each transaction creates a fresh owner-only (`0700`) + temporary directory with unpredictable naming, opens its download outputs + with `create_new`, and re-hashes the archive immediately before extraction. + A pre-existing path or a post-verification replacement fails the update + closed; the installed pair is left untouched. +- **No privilege escalation.** The updater never invokes `sudo`/UAC and never + edits shell or `PATH` state. An unwritable install directory fails before the + download with a remediation message. +- **Advisories are gated.** CI and the release preflight run + `cargo deny --workspace check`. The only ignores are the tracked + `zip 6.0.0` advisories inherited from `eggup-archive`; they are listed with + their removal condition in `deny.toml`. + +For a fully operator-controlled deployment, prefer the OS package flow (install +to a root-owned directory, update through the package manager) and let +self-update remain a convenience for user-owned installations. + ## Default vs. Hardened Mode | Setting | Default | Hardened | |---------|---------|----------| | Admin bind | `127.0.0.1:9090` | `127.0.0.1:9090` (or VPN/firewall if remote) | | Admin auth | None | Network-level (loopback/VPN) | +| Admin transport | Plaintext HTTP on loopback | Loopback + SSH/VPN, or TLS-terminating proxy | +| Admin `allowed_hosts` | Bind-derived loopback names | Explicit proxy/DNS host name | | Listener auth | None | `[listeners.auth]` with password | | Listener bind | `127.0.0.1:8080` | `0.0.0.0:port` with auth, or loopback | | TLS on listener | None | `[listeners.tls]` with cert/key | @@ -208,6 +299,7 @@ Never commit config files with credentials to version control. - [ ] Authentication configured on all non-loopback listeners - [ ] Admin server on loopback (or behind VPN/firewall) +- [ ] `[admin] allowed_hosts` lists the host name when admin is proxied or addressed by name - [ ] TLS configured on listeners exposed to untrusted networks - [ ] Upstream connections use `+tls` or Shadowsocks - [ ] Reverse control channel has auth + loopback bind (or TLS) diff --git a/docs/security/THREAT_MODEL.md b/docs/security/THREAT_MODEL.md index eefb476e..44f27a6c 100644 --- a/docs/security/THREAT_MODEL.md +++ b/docs/security/THREAT_MODEL.md @@ -39,6 +39,7 @@ Uses Eggress as an open proxy by connecting to non-loopback listener or admin. - Default admin bind is `127.0.0.1:9090` - Config validation rejects non-loopback admin binds without authentication - Shadowsocks/TLS listeners provide built-in authentication +- Password-authenticated HTTP/SOCKS listeners on a non-loopback bind emit a non-fatal warning when no `[listeners.tls]` is configured, because the credential would otherwise cross the wire in clear - `unsafe_code = "deny"` prevents memory safety issues that could be exploited ### A2: Malicious Upstream Proxy @@ -47,6 +48,7 @@ Compromised or malicious upstream server that logs or modifies proxied traffic. **Mitigations:** - TLS transport for upstream connections (`socks5+tls://`, `http+tls://`) +- Upstream TLS verifies the peer against the bundled Mozilla root set (`webpki-roots`), not the OS certificate store; pinning a private CA replaces that set rather than extending it - Operator chooses trusted upstreams - Upstream traffic is inherently trust-dependent @@ -119,6 +121,31 @@ Attacker reading logs, metrics, or admin output for credentials. - Admin snapshots expose only metadata, not credentials - Metrics labels never contain raw URIs or passwords +### A10: DNS-Rebinding Web Page (admin surface) + +A page on an attacker-controlled origin resolves its own hostname to +`127.0.0.1` and issues same-origin requests to the local admin port. Without a +`Host` check the browser's request is indistinguishable from an operator's, so +`/-/status`, `/-/config`, `/-/routes`, `/-/upstreams`, `/-/reverse`, and +`/metrics` become readable and `POST /-/route-explain` becomes callable. + +**Mitigations:** +- The admin server validates the `Host` header against `[admin] allowed_hosts` + plus bind-derived defaults (`localhost`, `127.0.0.1`, `::1` for a loopback + bind) before authentication and before any request body is read; a missing, + unparseable, or unlisted host returns a generic `400 Bad Request` with no + echo of the value +- `X-Forwarded-Host` is ignored: only the actual `Host` header counts +- `POST /-/route-explain` requires `Content-Type: application/json` and rejects + an `Origin` whose host is not allowlisted (including `Origin: null` unless + the literal entry `null` is configured) +- The admin surface stays read-only apart from the dry-run `route-explain` + endpoint, so a successful rebinding read leaks topology, not state changes +- Non-loopback admin binds require authentication and additionally emit a + plaintext-HTTP warning; admin has no native TLS, so remote access belongs on + a VPN/SSH tunnel or behind a TLS-terminating reverse proxy whose host name is + listed in `allowed_hosts` + ## Entry Points | Entry Point | Protocol | Auth | Default Bind | @@ -127,7 +154,7 @@ Attacker reading logs, metrics, or admin output for credentials. | UDP listener | SOCKS5 UDP associate | Via TCP control | `127.0.0.1:0` | | Transparent listener | iptables REDIRECT / PF | None (OS-level) | N/A (kernel) | | Unix socket | SOCKS4/5, HTTP | Optional (OS perms) | `/var/run/eggress.sock` | -| Admin server | HTTP | None (loopback only) | `127.0.0.1:9090` | +| Admin server | HTTP | None (loopback only); `Host`/`Origin` allowlisted | `127.0.0.1:9090` | | Reverse control | Custom binary | Optional | Configurable | | Python embed | In-process | Application | N/A | @@ -149,3 +176,21 @@ Attacker reading logs, metrics, or admin output for credentials. 14. Graceful shutdown ordering (drain before cancel) 15. No secrets in Python package data 16. Config warnings for non-loopback binds without authentication +17. SOCKS4 listeners with `[listeners.auth]` require the full pproxy `user:pass` + string in the SOCKS4 user-ID field; a username-only or wrong-password + attempt fails before any tunnel is created and never seeds the shared + IP-reuse cache +18. `allow_private_egress = false` is applied after DNS on every locally + resolving UDP path (standalone SOCKS5 UDP, SOCKS5 UDP ASSOCIATE, standalone + Shadowsocks UDP): all answers of the single lookup are filtered through the + shared special-purpose/private classifier and a private-only resolution is + dropped without creating a flow +19. The shared special-purpose classifier covers CGNAT `100.64.0.0/10`, NAT64 + `64:ff9b::/96`, 6to4 `2002::/16`, Teredo `2001::/32`, IPv6 benchmarking + `2001:2::/48`, and ORCHID `2001:10::/28` / `2001:20::/28`, including + IPv4-mapped forms +20. Admin `Host`/`Origin` validation against `[admin] allowed_hosts` (plus + bind-derived loopback defaults) blocks DNS-rebinding reads; `route-explain` + additionally requires a JSON content type +21. IPv4-mapped IPv6 literals are canonicalized before `destination_cidr` / + `source_cidr` matching, so the mapped form cannot bypass an IPv4 CIDR rule diff --git a/plans/closure/README.md b/plans/closure/README.md index fe178dd3..a60a6142 100644 --- a/plans/closure/README.md +++ b/plans/closure/README.md @@ -4,7 +4,15 @@ This directory contains evidence-based completion records for implementation mil A closure record is not a retrospective summary alone. It is the gate that determines whether the corresponding subsystem milestone can be marked complete. -No new closure records are pending. Historical closure evidence lives in `plans/archive/phase-records/` and Git history. +The 2026-11-16 security-corrective records are current: + +- `transports/004-status.md` (S1 TLS trust/advisory), `transports/005-status.md` (S2 `russh` migration) +- `protocols-edge/003-status.md` (S3 SOCKS4/UDP policy) +- `routing-health-observability/003-status.md` (S4 CIDR/admin exposure) +- `delivery/004-status.md` (S5 updater/advisory gate) +- `parity-compat/003-status.md` (S6 auth reuse/redaction) + +Historical closure evidence lives in `plans/archive/phase-records/` and Git history. ## Layout and naming diff --git a/plans/closure/delivery/004-status.md b/plans/closure/delivery/004-status.md new file mode 100644 index 00000000..356b9b32 --- /dev/null +++ b/plans/closure/delivery/004-status.md @@ -0,0 +1,316 @@ +# Delivery Milestone 004 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` + +Source subsystem roadmap: + +- `plans/subsystems/delivery-roadmap.md#milestone-4--updater-trust-advisory-gate-and-credential-output-hardening` +- `plans/subsystems/security-hardening-roadmap.md#milestone-s5--updater-trust-advisory-gate-and-credential-output-hardening` + +Repository baseline reviewed: `ba64e166474ede7caeba736a885322323d965911` + +Implementation commits or pull requests: + +- none — this record covers an uncommitted working-tree implementation on + `feat/auto-20261116-652bb64d` (workspace `1.0.12`). No commit, tag, or release + was created. + +Outstanding condition (single): the workspace-wide `cargo fmt --all --check`, +`cargo clippy --workspace --all-targets`, and `cargo test --workspace --locked` +gate is run by the coordinator after all corrective waves land. This milestone +deliberately ran only the scoped verification listed in §4. + +## 1. Executive finding + +The updater now has one trust path for release builds: fixed-location `curl`, +in-process SHA-256, HTTPS-only URLs, a private per-transaction staging +directory, create-new download outputs, and a second archive hash immediately +before extraction. The `EGRESS_UPDATE_BASE_URL`/`file://` fixture hook is +compiled out of release/default builds and only exists under `cfg(test)` or the +new non-default `update-fixtures` feature. `eggress system-proxy inspect +--json` no longer serializes raw settings or credential-bearing dry-run +commands, and both CI and the release preflight run an advisory gate whose only +ignores are the four tracked `zip 6.0.0` advisories inherited from +`eggup-archive`. + +The advisory gate needed one correction beyond the plan's `[graph] +all-features = true`: the root manifest is the `eggress-bench` package (not a +virtual manifest), so `cargo deny check` roots the graph there and silently +omits `eggress-cli` — and therefore `eggup-archive -> zip` — while printing +`advisories ok`. The gate is therefore `cargo deny --workspace check`, and the +misleading pass mode is documented in `deny.toml`, `docs/CI_STATUS.md`, and +`docs/release/RELEASE_PROCESS.md`. With `--workspace`, the all-features graph +is actually scanned: `russh 0.65.2` and `zip 6.0.0` both appear, and the four +ignores match real crate nodes instead of warning `advisory was not +encountered`. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Release/default builds ignore `EGRESS_UPDATE_BASE_URL` | `update_base_url_override()` has a `#[cfg(not(any(test, feature = "update-fixtures")))]` body returning `None` (`crates/eggress-cli/src/update/mod.rs`); `tests/updater_trust.rs::default_build_ignores_update_base_url_and_rejects_file_urls` runs the real binary with a `file://` fixture base URL and a dead HTTPS proxy and asserts exit 7 with a discovery failure | pass | binary under test is built without `cfg(test)` | +| Release/default builds reject `file://` (and every non-HTTPS scheme) | `is_fixture_url()` is `false` in release/default builds; `curl_command()` rejects non-HTTPS URLs and keeps `--proto =https --tlsv1.2` for HTTPS; `download::tests::refuses_non_https_update_urls` | pass | `http://` rejection pre-existing and preserved | +| Fixture hook still usable for tests only | `update-fixtures` non-default feature + `cfg(test)`; `update_fixtures_feature_honors_file_base_url` passes with `--features update-fixtures` and does not exist without it | pass | `EGRESS_UPDATE_CURL` test override also feature-gated | +| No PATH-resolved hash authority | `verify::compute_sha256` hashes in-process with `sha2 0.10`; the `sha256sum`/`shasum` discovery and parsing path is deleted; `update::tests::path_tools_are_not_trusted` plants a fake `sha256sum` on `PATH` and still gets `ba7816bf…15ad` for `abc` | pass | no process spawn remains in the hash path | +| Known-vector SHA-256 evidence | `verify::tests::sha256_matches_known_vectors` covers empty (`e3b0c442…`), `abc` (`ba7816bf…`), and 1,000,000 × `a` (`cdc76e5c…`) | pass | multi-block streaming path included | +| Sidecar remains the gate | `verify::tests::sidecar_comparison_uses_the_in_process_digest` accepts a matching sidecar, rejects tampered bytes, and re-accepts restored bytes | pass | — | +| `curl` resolves from fixed trusted locations only | `trusted_curl_candidates()` = `/usr/bin/curl`, `/bin/curl` (Unix) or `%SystemRoot%\System32\curl.exe` + `C:\Windows\System32\curl.exe` (Windows); no `PATH` read; `find_curl()` fails closed with an actionable message | pass | `trusted_candidates_are_fixed_system_locations` asserts the exact Unix set | +| Untrusted tool metadata refused | `validate_trusted_executable()` rejects symlinks, non-regular files, and (Unix) group/other-writable modes; `rejects_symlinked_or_writable_tools` covers all three | pass | Windows relies on `System32` ACLs; no portable group/other metadata | +| PATH-only fake `curl` not selected | `update::tests::path_tools_are_not_trusted` puts a fake `curl` first in `PATH`; `find_curl()` never returns it | pass | — | +| Private, unpredictable staging | `staging_dir()` uses `tempfile::Builder` with an explicit `0o700` mode (the crate default is umask-derived `0755`); `staging_directory_is_private_and_unique` asserts mode `0700`, distinct paths, and that a second transaction does not disturb the first | pass | default temp root retained | +| Concurrent staging attempts | `concurrent_staging_attempts_do_not_share_a_directory` creates 8 concurrent staging dirs and asserts 8 unique paths | pass | — | +| Create-new, non-symlink output paths | `create_private_output()` uses `OpenOptions::create_new` (`O_CREAT\|O_EXCL`, mode `0600`) and `curl` writes into that handle via stdout; `staging_outputs_are_created_new_and_owner_only` and `pre_existing_symlink_at_archive_path_is_refused` | pass | a symlink at the archive path fails `UnsafeDestination` and the victim file is untouched | +| Post-verification replacement fails closed | second `verify::verify_archive` via `verify_archive_before_extraction()` immediately before `install_pair_via_eggup`; `post_verification_archive_replacement_fails_closed` swaps the archive after the first gate and asserts the "changed after checksum verification" failure with exit 1 | pass | extraction never runs | +| JSON output has no credentials | `InspectionResult.settings` is `#[serde(default, skip_serializing)]`; `InspectionResult::new` always derives `redacted_settings`; dry-run commands are generated from the redacted copy; `inspection_result_json_omits_raw_credentials` and `dry_run_commands_use_redacted_values` (macOS/Windows/Linux command shapes) | pass | raw settings stay available in-process | +| CLI JSON redaction evidence | `tests/system_proxy_inspect.rs` runs the binary with credential-bearing `http_proxy`/`https_proxy`/`all_proxy`, asserts no `settings` key, a present `redacted_settings`, and no `user:pass@`/`admin:secret@` in stdout or stderr | pass | also verified manually (§4) | +| Advisory gate in CI | `.github/workflows/ci.yml` `advisories` job: pinned `cargo install cargo-deny --locked --version 0.19.0` then `cargo deny --workspace check` | pass (workflow change; not executed here) | fourth workflow count unchanged | +| Advisory gate in release preflight | `.github/workflows/release-binaries.yml` preflight job runs the same install + `cargo deny --workspace check` immediately after `scripts/release-preflight.sh --tag …` | pass (workflow change; not executed here) | preflight timeout 5 → 20 min | +| Only tracked `zip` ignores | `deny.toml` `[advisories] ignore` holds exactly RUSTSEC-2026-0367/-0368/-0369/-0429 with dependency path, why `ZipArchive::extract` is unused, and the removal condition (`eggup-archive` on `zip >= 9.0.0`) | pass | no TLS/SSH/QUIC/rustix ignore | +| Optional-feature dependencies actually scanned | `deny.toml` `[graph] all-features = true` + `--workspace`; `cargo deny --workspace check advisories` reports zero `advisory-not-detected` warnings (each ignore matched a real `zip 6.0.0` node) and the graph shows `russh 0.65.2` | pass | bare `cargo deny check` was proven to omit `eggress-cli` | +| No release/tag | no commit, tag, or release performed | pass | — | + +## 3. Production implementation evidence + +- `crates/eggress-cli/Cargo.toml`: new non-default `update-fixtures = []` + feature; promoted `tempfile` from `[dev-dependencies]` to `[dependencies]` + (removed the duplicate dev entry); added `sha2 = "0.10"`. `zip` stays + dev-only — `grep -rn "zip::" crates/eggress-cli/src` matches only the + `#[cfg(test)]` archive-fixture helper in `update/eggup.rs`, so no production + `zip` edge was added or removed. +- `crates/eggress-cli/src/update/download.rs` (rewritten trust path): + `DownloadError::MissingCurl(String)` and `DownloadError::UnsafeDestination` + are new; `trusted_curl_candidates()`, `validate_trusted_executable()`, + `create_private_output()`, shared `curl_command()` with the HTTPS policy, and + feature-gated `is_fixture_url()`/`fixture_curl_override()`. Downloads now + redirect `curl` stdout into an already-opened `create_new` file handle + instead of passing `-o `. +- `crates/eggress-cli/src/update/verify.rs`: `compute_sha256` is in-process + `sha2` streaming with a 64 KiB buffer; the `std::process::Command` tool + discovery/parse path is deleted. +- `crates/eggress-cli/src/update/mod.rs`: `update_base_url_override()` is + cfg-gated; `staging_dir()` returns a `tempfile::TempDir` with an explicit + `0o700` mode; the transaction drops the guard to clean only its own tree; + `verify_archive_before_extraction()` re-hashes immediately before Eggup + extraction; `map_download_error` maps `UnsafeDestination` to the runtime + failure category. Module documentation lists the new hard guarantees. +- `crates/eggress-system-proxy/src/inspection.rs`: raw `settings` is + `#[serde(default, skip_serializing)]`, `InspectionResult::new` derives + `redacted_settings` via a shared `redact_settings()`, and inspection dry-run + commands are generated from the redacted copy so the serialized/human report + cannot carry `user:pass@`. +- `crates/eggress-cli/src/cli.rs`: `system-proxy inspect --json` help now states + that settings are emitted redacted only. +- `deny.toml`: `[graph] all-features = true` (with an explanation that + `--workspace` is the invocation-level requirement), four commented `zip` + ignores with owner/removal condition, and + `Apache-2.0 WITH LLVM-exception` allowed (`target-lexicon`, a build + dependency of `pyo3-build-config`, became visible only once the gate scanned + the whole workspace). +- `.github/workflows/ci.yml`: new `advisories` job (pinned `cargo-deny 0.19.0` + via `cargo install --locked`, then `cargo deny --workspace check`). +- `.github/workflows/release-binaries.yml`: advisory gate added to the + `preflight` job after the version/tag preflight (timeout 5 → 20 minutes). +- `scripts/release-preflight.sh`: header documents that the script stays + offline/version-only and that the advisory gate runs immediately after it in + the release workflow. No release-discovery, asset-naming, checksum-policy, + staged-version, exit-code, or no-sudo behavior changed. +- `Cargo.lock`: `rustix 1.1.4 -> 1.1.6` (RUSTSEC-2026-0486). + +Unplanned but required: `cargo deny --workspace check` exposed a +`licenses` rejection that a root-only graph could not see, and the +`tempfile` default mode was `0755` rather than `0700`. Both are recorded above +and in §10. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggress-cli update +cargo test -p eggress-cli --features update-fixtures update +cargo test -p eggress-cli --features update-fixtures --test updater_trust +cargo test -p eggress-cli --test system_proxy_inspect +cargo test -p eggress-system-proxy +cargo test -p eggress-cli --test cli_exit_codes +cargo clippy -p eggress-cli -p eggress-system-proxy --all-targets -- -D warnings +cargo fmt -p eggress-cli -p eggress-system-proxy +cargo audit --ignore RUSTSEC-2023-0071 +cargo deny --workspace check +``` + +### Results + +- `cargo test -p eggress-cli update`: 44 updater unit tests pass; the + default-build integration test + `default_build_ignores_update_base_url_and_rejects_file_urls` passes (exit 7, + `download failed`). No failures. The updater test subset was repeated three + times (`cargo test -p eggress-cli --bin eggress update::tests`, 8 tests each) + with no flakes, including the `PATH`-mutation test alongside the `tar`-based + fixture flows. +- `cargo test -p eggress-cli --features update-fixtures update`: 44 updater + unit tests pass; `update_fixtures_feature_honors_file_base_url` passes + (exit 0, `already the latest stable version`). No failures. +- `cargo test -p eggress-system-proxy`: 55 tests pass (includes the two new + redaction tests and the dry-run-command redaction test). +- `cargo test -p eggress-cli --test system_proxy_inspect`: 1 test passes. + Manual transcript: `eggress system-proxy inspect --json` with + `http_proxy=http://user:pass@proxy.invalid:8080` printed top-level keys + `['apply_supported','capabilities','dry_run_commands','platform','redacted_settings']`, + `has raw settings key: False`, `contains user:pass@: False`. +- `cargo test -p eggress-cli --test cli_exit_codes`: 5 tests pass. +- `cargo clippy -p eggress-cli -p eggress-system-proxy --all-targets -- -D warnings`: + clean, no diagnostics. +- `cargo fmt -p eggress-cli -p eggress-system-proxy`: applied; only this + milestone's files were rewritten (other corrective work in the same crates + kept its earlier mtimes). +- `cargo audit --ignore RUSTSEC-2023-0071`: `error: 4 vulnerabilities found!` + — exactly `RUSTSEC-2026-0429`, `-0367`, `-0368`, `-0369`, all `zip 6.0.0` + (`patched >= 9.0.0`), plus 1 allowed warning (`wnaf 0.14.0` yanked). + `RUSTSEC-2026-0486` (rustix) is gone after the 1.1.6 update. +- `cargo deny --workspace check`: `advisories ok, bans ok, licenses ok, + sources ok`; zero `advisory-not-detected` warnings (all four ignores matched + `zip 6.0.0` nodes); remaining output is warnings only (duplicate versions, + `wnaf` yanked, one unmatched `Unicode-DFS-2016` allowance). +- Proven negative control: `cargo deny check` (no `--workspace`) reports + `advisories ok` with four `advisory was not encountered` warnings and a graph + that contains neither `eggress-cli` nor `zip`; after enabling only + `[graph] all-features = true` the result was unchanged, which is why + `--workspace` is part of the gate. + +Not run here (deliberate scope): `cargo test --workspace`, `cargo clippy +--workspace`, `cargo fmt --all`, any `--all-features` build/test, and the +hosted workflows themselves. + +**Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — +`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace --locked`, the documented CLI/embed feature slices, the +embed OpenSSH regression (6/6), and `cargo deny --workspace check` +(advisories/bans/licenses/sources). `cargo audit --ignore RUSTSEC-2023-0071` +reports only the four tracked `zip 6.0.0` advisories. The condition recorded in +§11 is therefore satisfied. + +## 5. Invariant review + +- **Latest-stable-only discovery**: unchanged — `latest_release_api_url()`, + `parse_github_tag`, `parse_tag` untouched; fixtures only redirect the base. +- **Sidecar as integrity gate**: unchanged in contract, strengthened in + implementation (in-process hash, second hash before extraction). +- **Both staged executables executed and matched**: unchanged + (`verify_staged_pair` before commit). +- **Never `sudo`, no shell/PATH mutation, no Cargo/source fallback**: unchanged; + `release_contract` (unchanged) still asserts the no-escalation/no-fallback + property over `update/`. +- **Failed update leaves the installed pair untouched**: preserved by ordering + (tool + URL checks → download → hash → re-hash → extraction → staged + versions → commit) and covered by the existing fixture-mismatch test plus the + new TOCTOU test. +- **Pair replaced as one unit**: unchanged (`SiblingPairVerifier`, sibling + parent check). +- **No new runtime HTTP client**: unchanged; still trusted `curl` only. +- **No shell evaluation of downloaded data**: unchanged. +- **No release/tag**: none created. + +## 6. Failure and recovery review + +- **Missing/untrusted tool**: `find_curl()` fails before any download; the + error names the checked absolute locations. `compute_sha256` needs no tool. +- **Non-HTTPS URL**: rejected before output files are created. +- **Unsafe staging path**: `create_new` returns `UnsafeDestination`, mapped to + `EXIT_RUNTIME_FAILURE` (`Failed`), with the install untouched. +- **Concurrent updates**: independent private directories; the Eggup + `MutationLock` contention behavior is unchanged. +- **Cancellation/kill mid-download**: only the private temp tree is left; the + installed pair is never touched. `TempDir` drop removes only its own path. +- **Post-verification replacement**: second hash fails closed with the + "changed after checksum verification" detail and exit 1. +- **Checksum mismatch**: unchanged message and exit 1 with the old pair intact. +- **Extraction/commit failure**: unchanged Eggup disposition mapping + (`Committed` / `RolledBack` / `RecoveryRequired`). + +## 7. Migration and compatibility review + +- Release/default builds no longer honor `EGRESS_UPDATE_BASE_URL` or `file://`. + Any private fixture workflow must build with `--features update-fixtures` + (documented in `docs/INSTALLATION.md`). +- The user-visible updater flow (discover → download → verify → stage → + execute → replace) and messages are unchanged apart from the new + tool/staging diagnostics. +- `system-proxy inspect --json` is a deliberate public output change: raw + `settings` is no longer serialized; `redacted_settings` remains and is + always populated when settings exist. Human output is unchanged. Documented + in command help, `docs/INSTALLATION.md`, `docs/SECURITY_REVIEW.md`, and + `docs/security/SECURE_CONFIGURATION.md`. No documented consumer required raw + settings (the only in-repo consumer is the CLI renderer). +- No pproxy compatibility claim or manifest entry changed. +- No version bump and no release. + +## 8. Security review + +- Release redirection hooks are compiled out; the env var is not read at all in + release/default builds (not merely ignored after reading). +- Integrity decisions are in-process; `PATH` cannot supply the hasher or the + fetcher. +- Tool trust checks cover symlink, regular-file, and (Unix) group/other-writable + metadata; failures are structured and fail closed. +- Staging is owner-only, unpredictable, atomic, create-new, and re-verified + before extraction; no output path is re-resolved after the trust decision. +- Credential-bearing proxy settings, including dry-run command lines, cannot be + serialized by `system-proxy inspect --json`. +- Advisory gate now scans the real workspace graph; the exception list is + explicit, commented, and has a removal condition. No TLS/SSH/QUIC/rustix + advisories are ignored. + +## 9. Documentation and operations + +- `docs/INSTALLATION.md`: trusted-tool, private-staging, HTTPS-only, and + no-`sudo` updater behavior plus two troubleshooting entries. +- `docs/SECURITY_REVIEW.md`: new `Self-Update and Distribution Trust` surface + section. +- `docs/security/SECURE_CONFIGURATION.md`: new `8. Self-Update Trust Boundary` + section (no other section touched). +- `docs/CI_STATUS.md`: fourth-job inventory, `advisories` job, the + `--workspace` requirement, and the release workflow's advisory step. +- `docs/release/RELEASE_PROCESS.md`: advisory command in step 1 with the + `--workspace` rationale. +- `deny.toml`: annotated graph/advisory configuration and the license + allowance. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | Bare `cargo deny check` still prints `advisories ok` while skipping `eggress-cli`/`zip` (root-package graph) | A maintainer running the wrong command can believe the gate passed | Mitigated: CI/preflight/docs all use `cargo deny --workspace check`, and `deny.toml` documents the trap. Consider making `--workspace` the only documented form in `AGENTS.md` at the next docs pass. | +| low | `tempfile`'s default directory mode is umask-derived (`0755`), not `0700` | Would have left staged archives readable by other local users | Fixed: `staging_dir()` passes an explicit `0700` mode; asserted by test | +| low | `Apache-2.0 WITH LLVM-exception` (`target-lexicon`, via `pyo3-build-config`) had to be allow-listed once the gate scanned the whole workspace | Gate could not pass without it | Fixed in `deny.toml`; permissive license, no policy change | +| medium | Four `zip 6.0.0` advisories remain in the updater graph | Upstream `eggup-archive` blocker; Eggup's bounded extractor does not call the vulnerable `extract()` APIs and Eggress verifies the whole-archive SHA-256 first | Tracked as a narrow commented `deny.toml` exception; remove when `eggup-archive` depends on `zip >= 9.0.0` | +| low | Workspace-wide fmt/clippy/test gate not run in this wave | Cross-crate regressions outside the touched crates would be caught later | Coordinator runs it after all corrective waves | + +## 11. Roadmap disposition + +Milestone closed. The coordinator's workspace-wide format/lint/test gate passed +on 2026-11-16. + +Delivery M004 exit criteria are satisfied: default builds reject +`EGRESS_UPDATE_BASE_URL`/`file://`, no PATH hash authority remains, staging is +private/create-new/symlink-safe with a closed verify/extract window, JSON has no +credentials, the advisory gate runs in CI and the release preflight, and the +`zip` blocker is explicit, commented, and tracked with an owner and review date. +Security S5 is satisfied by the same evidence. + +## 12. Registry updates + +- `plans/registry.md` (not edited in this wave — owned elsewhere): change the + Delivery M004 plan row status from `ready` to `implemented` and point the + roadmap/closure links at `plans/closure/delivery/004-status.md`. The + `zip 6.0.0` blocked-work entry already exists and needs no change beyond + noting the gate exception is now enforced with `cargo deny --workspace check`. +- `plans/subsystems/delivery-roadmap.md`: M004 header, dependency-graph, and + milestone/status-table rows updated (done). +- `plans/subsystems/security-hardening-roadmap.md`: S5 requires no text change; + the milestone now has evidence. Coordinator may flip its status row if the + roadmap tracks one. +- No commit, tag, release, or registry mutation was performed by this wave. diff --git a/plans/closure/parity-compat/003-status.md b/plans/closure/parity-compat/003-status.md new file mode 100644 index 00000000..e75d6c7a --- /dev/null +++ b/plans/closure/parity-compat/003-status.md @@ -0,0 +1,320 @@ +# Parity Compat Milestone 003 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` + +Source subsystem roadmaps: + +- `plans/subsystems/parity-compat-roadmap.md` §7 Milestone 3, §12 milestone status +- `plans/subsystems/security-hardening-roadmap.md` §7 Milestone S6 + +Repository baseline reviewed: `ba64e16` (branch `feat/auto-20261116-652bb64d`, +workspace `1.0.12`) plus this pass's uncommitted working-tree changes + +Implementation commits or pull requests: + +- None. This pass is uncommitted working-tree work in the shared corrective + wave; no commit, tag, or publication was created by this milestone. + +## 1. Executive finding + +The pproxy-compatible authentication contract is now documented truthfully and +the compatibility surface no longer leaks credentials through the paths this +milestone owns. + +- `docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md`, + `docs/PPROXY_MIGRATION.md`, and `docs/cli/PPROXY_CLI_INVENTORY.md` now state + that listener credentials come from the listener URI (pproxy's `#user:pass` + fragment, or `user:pass@` userinfo), that the translator emits + `[listeners.auth]` from those credentials with no `--auth` involvement, and + that `--auth N` is only the source-IP **re-authentication reuse interval** + (`2592000` s / 30 days by default, including when omitted; `0` disables + practical reuse). +- Compatibility startup emits exactly one warning for the process-global, + source-IP-keyed, cross-listener reuse cache. It fires after translation and + `--test` early-return, before daemonization and serving, only when a + translated listener actually carries `[listeners.auth]`. The text is static + and contains no URI or credential. +- Invalid UDP remote (`-ur`) errors use the canonical + `redact_uri_for_error`, which is now hop-aware and authority-bounded, so + credentials never reach the diagnostic while the reason and endpoint survive. +- `eggress pproxy translate --annotate` renders its reproduction line through + `redact_argv_for_annotation`: flags, chain separators, and query strings are + preserved; userinfo becomes `****:****@` / `****@`; fragment auth becomes + `#****`. Generated TOML is unchanged and still contains the real credentials + needed to run. +- `eggress pproxy check --json` keeps its recognized display paths redacted + (`parsed_uris.listeners`/`remotes`, diagnostics). Its documented "raw" + fields (`raw_args`, `chain_info[].raw`) remain raw; see §10 for why that was + left to a contract decision rather than changed inside this milestone. +- `ReverseServerToml` and `ReverseClientToml` use hand-written `Debug` impls + that print `Some(****)` for `auth_password` (and `server_uri`), while + serialization keeps the real values. + +No compatibility tier or manifest claim changed, and no pproxy default, cache +scope, or cache expiry was touched. Closure is conditional on one item only: +the coordinator's workspace-wide `fmt`/`clippy`/`test` gate, which runs after +every corrective wave has landed. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Docs describe credentials as URI-borne (fragment / userinfo), not `--auth`-gated | `docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md`, `docs/PPROXY_MIGRATION.md`, `docs/cli/PPROXY_CLI_INVENTORY.md` diffs | pass | No remaining "`--auth` enables authentication" or "no `[listeners.auth]` unless `--auth`" claim | +| Docs state `--auth` default `2592000` (30 days), including when omitted | same diffs; `PproxyArgs::effective_auth_timeout()` unchanged at `86_400 * 30` (`crates/eggress-pproxy-compat/src/args.rs`) | pass | Default existed; only documentation was wrong | +| Docs state cache is process-local, bounded, monotonic, IP-only, shared across credentialed listeners | same diffs; `AuthReuseCache` (`crates/eggress-server/src/accept/mod.rs:41-49`) untouched | pass | 4096-entry bound and lazy eviction documented | +| Docs offer `--auth 0` / native `[listeners.auth]` escape hatches | same diffs | pass | | +| One startup warning names the 30-day default, IP-only key, and cross-listener cache | `PproxyArgs::auth_reuse_advisory()` (`args.rs`), `auth_reuse_advisory_for()` + `execute()` (`crates/eggress-cli/src/pproxy_exec.rs:197-207,248-251`) | pass | Verbatim text in §3 below | +| Warning fires once at startup, never per connection | single call site in `execute`, after the `--test` early return, before daemonize/serve | pass | Manual run showed exactly one occurrence | +| Warning only with credentialed listeners | unit test `pproxy_exec::tests::auth_reuse_advisory_fires_for_credentialed_listener_only` (gated on compiled `[listeners.auth]`); manual unauthenticated run produced zero advisories | pass | Also gated off translation-only subcommands | +| Warning never echoes credentials or listener URIs | static text; unit tests assert no `user`/`pass`/host/port; manual `grep -c secret` = 0 on stderr and stdout | pass | | +| Invalid UDP remote errors redact raw URI | `crates/eggress-pproxy-compat/src/translate/intermediates.rs:855-865`; tests `translate::tests::udp_remote_errors_redact_credentials`, `translate::tests::udp_remote_error_redacts_percent_and_bracket_passwords` | pass | Both "invalid URI" and "no proxy hop" paths | +| Passwords with `@`, `:`, brackets, percent escapes never leak | `uri::tests::test_redact_uri_for_error_hides_credentials` (last-`@`, `p[a]ss`, unmatched `[` fallback, `%40`/`%3A`, username-only, chain, fragment, 256-bound) | pass | | +| `--annotate` redacts argv but preserves flags, chains, queries | `uri::redact_argv_for_annotation` + `uri::tests::test_redact_argv_for_annotation_preserves_flags_and_chains`, `..._username_only_and_fragments` | pass | `-l`/`-r`/`--auth` preserved | +| `--annotate` integration with credentialed `-l`/`-r` pair | `crates/eggress-cli/tests/pproxy_cli.rs::translate_annotate_redacts_credentials_but_keeps_toml_runnable` | pass | Asserts `****:****@` and absence of both secrets in the annotation line | +| `pproxy check --json` recognized displays redacted | `crates/eggress-cli/tests/pproxy_cli.rs::check_json_redacts_parsed_uris_and_diagnostics` | pass | `parsed_uris.listeners`/`remotes` and diagnostics redacted; `raw_args`/`chain_info[].raw` intentionally raw (§10) | +| Generated TOML unchanged and runnable (real credentials kept) | same CLI test asserts `password = "supersecret"` and the credentialed upstream URI remain in the TOML; translation code untouched | pass | | +| Compat IR `Debug` never prints `auth_password` | custom `Debug` in `crates/eggress-pproxy-compat/src/translate/model.rs`; test `translate::tests::compat_ir_debug_redacts_reverse_auth_password` | pass | Prints `Some(****)`; JSON serialization still contains the real value | +| No new flag, no cache scope/expiry change | diff review: `AuthReuseCache`, `from_facade`, supervisor wiring untouched; only advisory text added | pass | | +| Manifest claim unchanged | `python3 scripts/validate_pproxy_parity_manifest.py --strict docs/parity/pproxy_capability_manifest.toml` → PASS 162 capabilities; generated-report roundtrip consistent; `docs/parity/` unmodified | pass | See §4 | +| Focused Rust verification green | commands in §4 | pass | | +| Coordinator workspace-wide gate | not run in this wave by instruction | partial | Sole closure condition | + +## 3. Production implementation evidence + +Verbatim warning emitted by both compatibility entry points (prefix +`warning: ` for `eggress pproxy run`, `pproxy: warning: ` for the standalone +`pproxy` binary): + +```text +pproxy-compatible authentication reuse is active for listener credentials: the reuse cache is process-global, keyed only by source IP, and shared across credentialed compatibility listeners (bounded, monotonic expiry). Reuse interval: 2592000s (30 days) when --auth is omitted; effective for this process: 2592000s. Set --auth 0 to disable practical reuse, or use native [listeners.auth] for per-connection checks with no reuse cache. +``` + +Placement: `eggress_cli::pproxy_exec::execute`, after the `--test` diagnostic +early return and before `maybe_daemonize`/supervisor start, gated on +`rt_config.listeners.iter().any(|l| l.auth.is_some())`. The standalone `pproxy` +binary and `eggress pproxy run` both delegate to `execute`, so the warning is +emitted once per process, never per connection. + +Ownership changes landed: + +- `crates/eggress-pproxy-compat/src/uri.rs` — `redact_uri_for_error` is now + `pub(crate)`, hop-aware (redacts every `scheme://` hop in a `__` chain), and + authority-bounded (an `@` in a query/path is no longer treated as userinfo); + new `redact_uri_token` and public `redact_argv_for_annotation`; last-`@` + fallback for unmatched brackets keeps the redactor total. +- `crates/eggress-pproxy-compat/src/args.rs` — new + `PproxyArgs::auth_reuse_advisory()`; `effective_auth_timeout()` unchanged. +- `crates/eggress-pproxy-compat/src/translate/intermediates.rs` — UDP remote + errors redact the raw `-ur` value; the `auth-timeout` translation warning + now says `--auth` sets the reuse interval and credentials come from the URI. +- `crates/eggress-pproxy-compat/src/translate/model.rs` — hand-written `Debug` + for `ReverseServerToml`/`ReverseClientToml`; serialization unchanged. +- `crates/eggress-cli/src/commands/pproxy.rs` — `--annotate` uses + `redact_argv_for_annotation`. `check --json` was reviewed but its documented + "raw" fields were left unchanged (§10). +- `crates/eggress-cli/src/pproxy_exec.rs` — startup advisory helper and call. +- Tests: compat unit tests (uri/args/translate), `pproxy_exec` unit test, + annotated-translate CLI test. + +Not implemented (out of scope by plan §5): no new auth flag, no native +auth-cache configuration, no change to the pproxy reuse default or cache +scope, no SOCKS4 credential enforcement (Protocols Edge M003). + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggress-pproxy-compat +cargo test -p eggress-cli --test cli_exit_codes +cargo test -p eggress-cli --test pproxy_cli +cargo test -p eggress-cli --test pproxy_binary +cargo test -p eggress-cli --test pproxy_translation_golden +cargo test -p eggress-cli --lib auth_reuse_advisory +cargo test -p eggress-runtime --test security_invariants +cargo test -p eggress-embed --test error_redaction +cargo clippy -p eggress-pproxy-compat -p eggress-cli --all-targets -- -D warnings +cargo fmt -p eggress-pproxy-compat -p eggress-cli -p eggress-runtime +cargo fmt -p eggress-pproxy-compat -p eggress-cli -p eggress-runtime -- --check +python3 scripts/validate_pproxy_parity_manifest.py --strict docs/parity/pproxy_capability_manifest.toml +python3 scripts/validate_pproxy_parity_manifest.py --write-report /report.md docs/parity/pproxy_capability_manifest.toml +python3 scripts/validate_pproxy_parity_manifest.py --check-report /report.md docs/parity/pproxy_capability_manifest.toml +``` + +Manual process checks (real binaries, listener killed after ~2 s): + +```bash +target/debug/eggress pproxy run -- -l 'socks5://user:secret@127.0.0.1:19899' +target/debug/pproxy -l 'socks5://u:p@127.0.0.1:19897' +target/debug/eggress pproxy run -- -l 'socks5://127.0.0.1:19898' +``` + +### Results + +- `cargo test -p eggress-pproxy-compat` — pass: 373 lib tests, 6 + `native_equivalence`, 11 `uri_syntax_equivalence`, 0 doc tests; 0 failed. +- `cargo test -p eggress-cli --test cli_exit_codes` — pass: 5/5. +- `cargo test -p eggress-cli --test pproxy_cli` — pass: 14/14, including the + new annotated-translate and `check --json` redaction tests. +- `cargo test -p eggress-cli --test pproxy_binary` — pass: 34/34 (extra + confidence for the changed `--auth` warning text and startup banner). +- `cargo test -p eggress-cli --test pproxy_translation_golden` — pass: 9/9; + no fixture change was needed (the goldens do not pin the `--auth` warning). +- `cargo test -p eggress-cli --lib auth_reuse_advisory` — pass: 1/1. +- `cargo test -p eggress-runtime --test security_invariants` — pass: 8/8. +- `cargo test -p eggress-embed --test error_redaction` — pass: 12/12. +- `cargo clippy -p eggress-pproxy-compat -p eggress-cli --all-targets -- -D warnings` + — pass, no diagnostics. +- `cargo fmt -p eggress-pproxy-compat -p eggress-cli -p eggress-runtime` and + its `-- --check` re-run — clean (no reformat of unrelated packages; + `cargo fmt --all` was not used). +- Manifest `--strict` — PASS, 162 capabilities (`drop_in` 90, + `compatible_with_warning` 54, `native_equivalent` 16, + `intentional_non_parity` 2, `unsupported` 0). +- Report roundtrip — "Report is consistent with manifest", exit 0. +- Manual `eggress pproxy run` with credentials — exactly one advisory on + stderr; `grep -c secret` on stdout and stderr = 0. +- Manual standalone `pproxy` with credentials — exactly one advisory with the + `pproxy: ` prefix; no credential. +- Manual `eggress pproxy run` without credentials — zero advisories (only the + pre-existing `[direct-mode]` warning). + +Environment note: the assigned command +`python3 scripts/validate_pproxy_parity_manifest.py --check-report` is +incomplete — the script requires a report path argument. The equivalent +supported checks above (`--strict`, then `--write-report` followed by +`--check-report` on a temporary generated report) were run instead; the +committed tree has no report file to check against. + +**Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — +`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace --locked`, the documented CLI/embed feature slices, the +embed OpenSSH regression (6/6), and `cargo deny --workspace check` +(advisories/bans/licenses/sources). `cargo audit --ignore RUSTSEC-2023-0071` +reports only the four tracked `zip 6.0.0` advisories. The condition recorded in +§11 is therefore satisfied. + +## 5. Invariant review + +| Source-plan invariant (§4) | Evidence | Status | +|---|---|---| +| pproxy 2.7.9 behavior remains the default; no tier change without manifest + oracle evidence | `AuthReuseCache`/`from_facade`/supervisor untouched; manifest `--strict` PASS; no `docs/parity/` change | holds | +| `PproxyUri::redacted_display`, `RedactedUri`, `CredentialSpec` redaction remain canonical | untouched; `uri_syntax_equivalence::redaction_hides_credentials_both_grammars` passes | holds | +| Compatibility diagnostics remain structured and machine-readable | no diagnostic enum/schema change; one plain startup warning line | holds | +| `translate` still emits usable TOML with real credentials | `translate_annotate_redacts_credentials_but_keeps_toml_runnable`; existing translate goldens pass | holds | +| `--annotate` remains useful for reproduction | flags/chain separators/query preserved; only userinfo/fragment replaced with placeholders | holds (fragment-suffix nuance in §10) | +| No new auth flag or credential store | diff review | holds | + +## 6. Failure and recovery review + +- Duplicate delivery / idempotency: the advisory is emitted from one call site + per process start; repeated invocations each warn once. No idempotency state + was added. +- Cancellation races: none introduced; the advisory is a synchronous + `eprintln!` before bind/serve. +- Process or supervisor restart: the warning re-emits once on each new + compatibility process, which is the intended operator-visible behavior. +- Partial persistence failure: not applicable (no persistence added). +- Stale generation or lease: not applicable. +- Contention and resource release: redaction allocates one bounded `String` per + call (`<= 256` bytes for error output) and holds no locks. +- Malformed or unauthorized input: `redact_uri_for_error` is total — it + tolerates non-URI tokens, unmatched brackets/braces, empty authorities, and + multi-hop input, never panics, and never echoes the raw input; covered by + unit tests. +- Bounded relay and association behavior: unchanged. + +## 7. Migration and compatibility review + +- Config migration: none required. Documentation now describes the existing + behavior; operators who believed `--auth` was the authentication switch must + put credentials in the listener URI and use `--auth` only for the reuse + interval. +- Backward compatibility: no CLI, URI, translation, or runtime behavior change + beyond one additional startup warning line and redacted diagnostics. +- Protocol negotiation / translator tiers: unchanged. No manifest or matrix + edit; no oracle/differential/interop run was required (the claim did not + change). +- Rollback: revert the three documentation files and the Rust source/test files + listed in §3; no persistent state, schema, or cache change exists to roll + back. + +## 8. Security review + +- Authorization enforcement: unchanged (`[listeners.auth]` from URI + credentials, `AuthReuseCache` semantics identical). +- Secret handling: warning text is static with no identifiers; `--annotate` + redacts userinfo and fragment auth; UDP remote errors use the canonical + redactor; compat IR `Debug` hides `auth_password`/`server_uri` while + serialization preserves them. +- Path validation / privilege boundaries: untouched. +- Denial-of-service bounds: redaction output is bounded to 256 bytes for error + messages; the auth cache remains the pre-existing 4096-entry bounded cache + with monotonic expiry. +- Redaction: unit tests cover `@`-in-password, `:`-in-password, balanced and + unmatched brackets, percent escapes, username-only userinfo, IPv6 hosts, + chains, query strings, and fragments. +- Residual exposures (see §10): `pproxy check --json` `raw_args` and + `chain_info[].raw`; other compat IR `Debug` derives + (`ListenerToml`/`AuthToml`/`UpstreamToml`); Python embedding entry point has + no advisory. + +## 9. Documentation and operations + +- `docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md` — replaced the false + "No Authentication by Default" section with the URI-credential contract, a + dedicated source-IP reuse section, corrected translate-time wording, and + corrected comparison tables. +- `docs/PPROXY_MIGRATION.md` — new "Listener credentials and `--auth`" + subsection; compatibility-boundary bullet corrected. +- `docs/cli/PPROXY_CLI_INVENTORY.md` — `--auth` row and a paragraph separating + URI credentials from the reuse interval. +- Operator diagnostics: one startup warning (text in §3); the `--auth` + translation warning now says it sets the reuse interval. +- Recovery instructions: none needed (documentation/warning/redaction only). +- `docs/SECURITY_REVIEW.md` was not edited because it is outside this + milestone's owned file list; the coordinator should fold the redaction + evidence into it if that document tracks it. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| medium | `eggress pproxy check --json` emits credentialed URIs in its documented "raw" fields: `raw_args` (original argv) and `parsed_uris.chain_info[].raw` (raw chain string). The `cli.check_json_chain_info` manifest entry explicitly describes `raw`, Python contract tests assert `raw_args` equality, and `docs/PPROXY_MIGRATION.md` documents `raw_args` as the original arguments. Redacting either field changes a documented, manifest-described output contract, so it was **not** done unilaterally in this milestone. | Machine-readable check output can contain credentials when piped to logs or committed as evidence. | Open a follow-up that updates the manifest `eggress_behavior` text, the migration doc, the Python contract/tests, and the CLI together; then redact (or add `redacted_args`/`redacted_chain` alongside). Tracked as the primary residual of M003. | +| low | Other compat IR structs still derive `Debug` (`ListenerToml.auth`, `AuthToml.password`, `ShadowsocksToml.password`, `TrojanToml.password`, `UpstreamToml.uri`, and `TranslationIntermediates`). No production log path prints them today. | Latent leak if a future diagnostic prints the IR. | Extend the hand-written `Debug` pattern in a follow-up; `ReverseServerToml`/`ReverseClientToml` are closed. | +| low | Annotated argv truncates at the first `#` when a token carries fragment auth (`#****`), so a fragment-bearing hop followed by `__` chain hops loses those trailing hops in the annotation line only. | Reproduction value for a rare `-l a#u:p__b` shape; no credential exposure. | Accept, or make fragment redaction hop-aware if the shape becomes common. | +| low | The Python embedding path (`EggressService.start_with_compatibility_options`) constructs the same reuse cache but does not print the advisory; Python sources are outside this milestone's owned files. | Python-embedded deployments do not see the startup warning. | Add the advisory in the Python bindings surface if parity of operator visibility is required. | +| low | No process-level regression test asserts the advisory in `pproxy_run_process.rs` (test ownership for this milestone was limited to the `--annotate` CLI test). | The call site is covered by unit tests plus manual process verification, not a process test. | Add a process assertion in a test-ownership-expanded follow-up. | +| low | Workspace-wide `fmt`/`clippy`/`test` gate not run in this wave (coordinator owns it). | Integration risk with concurrent waves. | Coordinator runs the broad gate once after all corrective waves. | + +## 11. Roadmap disposition + +Milestone closed. Production implementation, focused tests, documentation, and +manifest validation for M003 are complete, the coordinator's workspace-wide +`fmt`/`clippy`/`test` gate passed on 2026-11-16, and the manifest claim is +unchanged. + +The `check --json` raw-field exposure in §10 is a pre-existing, +manifest-described output contract outside M003's stated redaction scope +(UDP errors, `--annotate`, compat IR `Debug`). It is tracked for a follow-up and +is **not** a closure condition for this milestone. No release, tag, or publish +action is part of this milestone. + +## 12. Registry updates + +Required in `plans/registry.md` (owned by the coordinator, not edited here): + +- mark Parity Compat M003 as closed, pointing at + `plans/closure/parity-compat/003-status.md`; +- mark Security Hardening S6 (same plan/evidence) as closed in + `plans/subsystems/security-hardening-roadmap.md` §12; +- record that the coordinator workspace-wide gate passed on 2026-11-16. + +Applied in the source subsystem roadmap by this milestone: +`plans/subsystems/parity-compat-roadmap.md` §7/§12 now report M003 as +closed with the closure record path. The manifest, matrix, and +generated reports are unchanged. diff --git a/plans/closure/protocols-edge/003-status.md b/plans/closure/protocols-edge/003-status.md new file mode 100644 index 00000000..95c1a3e8 --- /dev/null +++ b/plans/closure/protocols-edge/003-status.md @@ -0,0 +1,308 @@ +# Protocols Edge Milestone 003 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` + +Source subsystem roadmaps: + +- `plans/subsystems/protocols-edge-roadmap.md` §7 Milestone 3, §12 milestone status +- `plans/subsystems/security-hardening-roadmap.md` §7 Milestone S3 + +Repository baseline reviewed: `ba64e16` (branch `feat/auto-20261116-652bb64d`, +workspace `1.0.12`) plus this pass's uncommitted working-tree changes + +Implementation commits or pull requests: + +- None. This pass is uncommitted working-tree work in the shared corrective + wave; no commit, tag, or publication was created by this milestone. + +## 1. Executive finding + +The two inbound-enforcement bypasses named by the milestone are closed, and the +address-classification and auth-transport gaps they depended on are covered by +tests. + +- SOCKS4 listeners with `[listeners.auth]` now enforce the full pproxy + `user:pass` credential in the SOCKS4 user-ID field, compare it with + `subtle::ConstantTimeEq`, report a generic authentication failure without + echoing either component, derive the session identity from the authenticated + username, and seed the shared IP auth-reuse cache only on that + full-credential success. Username-only, wrong-password, and empty user IDs + fail before any tunnel or cache entry exists. +- `allow_private_egress = false` is now enforced after DNS on all three locally + resolving UDP paths (standalone SOCKS5 UDP, SOCKS5 UDP ASSOCIATE, standalone + Shadowsocks UDP). The existing single `lookup_host` call is collected in full + and every answer is filtered through the shared classifier; the first + permitted address is connected and an all-private resolution returns + `UdpError::PrivateEgressBlocked` without creating a flow. +- The shared classifier in `eggress-core::connector` now treats CGNAT + `100.64.0.0/10`, NAT64 `64:ff9b::/96`, 6to4 `2002::/16`, Teredo `2001::/32`, + IPv6 benchmarking `2001:2::/48`, and ORCHID `2001:10::/28` / `2001:20::/28` + as reserved/private, including IPv4-mapped forms. `eggress-udp` reuses it and + its duplicate private-IP helpers are gone; the UDP-local shape checks (port + zero, multicast, broadcast, unspecified, loopback) remain. +- Config validation emits a non-fatal warning when a listener is non-loopback, + configures `[listeners.auth]`, has no `[listeners.tls]`, and offers HTTP, + SOCKS4, or SOCKS5. Shadowsocks, Trojan, and TLS listeners do not warn, and + the configuration is never rejected. + +The pproxy SOCKS4 `matched` claim was restored, not changed: no manifest or +compatibility-tier edit was required, and no oracle/differential gate was +triggered by this pass. Closure is conditional on one item only — the +coordinator's workspace-wide `fmt`/`clippy`/`test` gate, which runs after every +corrective wave has landed. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| SOCKS4 `[listeners.auth]` enforces the full `user:pass` credential in the user-ID field | `crates/eggress-server/src/accept/handlers.rs` (`accept_socks4`); `test_socks4_auth_full_credential_accepted` | pass | `ct_eq` over `username:password`; expected bytes zeroized after compare | +| Username-only SOCKS4 user ID rejected | `test_socks4_auth_username_only_rejected` | pass | Generic `AuthenticationFailed` | +| Wrong-password SOCKS4 user ID rejected | `test_socks4_auth_wrong_password_rejected` | pass | — | +| Empty SOCKS4 user ID rejected when auth is configured | `test_socks4_auth_empty_user_id_rejected` | pass | — | +| Failed SOCKS4 attempt never seeds the auth-reuse cache | `test_socks4_auth_rejected_attempt_does_not_authorize_retry` (three failure shapes, `cache.is_empty()` after each) | pass | Cache seeded only in the full-credential branch | +| Successful SOCKS4 auth records the authenticated username identity | `test_socks4_auth_full_credential_accepted` (`ClientIdentity::Username("user")`, `cache.lookup(peer)`) | pass | Raw user ID is no longer the cached identity | +| SOCKS4 auth failure does not echo credentials | `test_socks4_auth_failure_does_not_leak_credentials` | pass | Rendered error is exactly `authentication failed` | +| Reuse cache stays peer-scoped | `test_socks4_auth_reuse_cache_is_peer_scoped` | pass | Same peer reuses; another peer is rejected | +| `allow_private_egress = false` blocks a domain resolving to a private address (flow level) | `crates/eggress-udp/src/direct.rs` `private_domain_is_dropped_when_policy_disallows` | pass | `PrivateEgressBlocked`; counting echo server observes zero datagrams | +| Same target allowed when `allow_private_egress = true` | `private_domain_is_allowed_when_policy_permits` | pass | Echo round-trip | +| Mixed public/private resolution filters rather than truncating | `restrictive_policy_selects_first_permitted_answer` | pass | `[public, private]` and `[cgnat, public]` select the public answer | +| Public destination still resolves under a restrictive policy | `public_domain_still_resolves_when_policy_disallows_private` | pass | Numeric public destination, no external DNS | +| Empty answer set fails with `UnresolvedTarget` | `restrictive_policy_selects_first_permitted_answer` | pass | — | +| Standalone SOCKS5 UDP path drops private-resolving domain and records rejection | `crates/eggress-udp/tests/standalone_udp.rs` `standalone_udp_private_domain_dropped_when_policy_disallows` | pass | `standalone_rejected_datagrams == 1`, no datagram at target | +| Standalone SOCKS5 UDP path still works with the default policy | `standalone_udp_private_domain_allowed_when_policy_permits` | pass | — | +| SOCKS5 UDP ASSOCIATE path drops private-resolving domain and records `dropped_packets` | `crates/eggress-udp/src/relay.rs` `relay_private_domain_dropped_when_policy_disallows` | pass | Previously the error escaped without a drop count | +| SOCKS5 UDP ASSOCIATE permissive path unchanged | `relay_private_domain_allowed_when_policy_permits` | pass | — | +| Standalone Shadowsocks UDP drops private-resolving domain and records rejection | `crates/eggress-udp/src/standalone_shadowsocks.rs` `build_direct_flow` passes `config.allow_private_egress`; `shadowsocks_standalone_private_domain_dropped_when_policy_disallows` | pass | `standalone_rejected_datagrams == 1`, no datagram at target | +| No second DNS lookup | `direct.rs` `resolve_target` collects the one `lookup_host` result; no other call added | pass | Code inspection + diff | +| Literal shape checks retained | `crates/eggress-udp/src/security.rs` `validate_target_shape` (unchanged) | pass | `security.rs` unit tests unchanged and green | +| Shared classifier covers CGNAT | `eggress-core/src/connector.rs` `is_v4_cgnat`; `reserved_special_purpose_ranges_table`; UDP `reject_cgnat_ipv4_egress` | pass | 100.63.255.255 / 100.128.0.0 remain public | +| Shared classifier covers NAT64 / 6to4 / Teredo | `is_v6_nat64` / `is_v6_6to4` / `is_v6_teredo`; table test; UDP `reject_nat64_and_teredo_egress` | pass | — | +| Shared classifier covers `2001:2::/48` and ORCHID | `is_v6_benchmarking` / `is_v6_orchid`; table test | pass | `2001:1::/32`, `2001:3::/32`, `2001:30::/32` stay public | +| IPv4-mapped forms classified | `is_reserved_or_private_ip` recursion; table entries `::ffff:100.64.0.1`, `::ffff:100.127.255.254`, `::ffff:8.8.8.8` | pass | — | +| UDP duplication removed | `security.rs` delegates to `is_reserved_or_private_ip`; local `is_private_ipv4/6` bodies replaced | pass | — | +| Auth-without-TLS warning for non-loopback HTTP/SOCKS with auth | `crates/eggress-config/src/validate/security.rs`; `warn_non_loopback_http_auth_without_tls`, `warn_non_loopback_socks4_and_socks5_auth_without_tls` | pass | Path `listeners[].tls` | +| No warning for TLS / Shadowsocks / Trojan / loopback | `no_warn_authed_http_with_tls`, `no_warn_authed_shadowsocks_without_tls`, `no_warn_authed_trojan_protocol_without_tls`, `no_warn_loopback_http_auth_without_tls` | pass | — | +| Warning text never echoes credentials | `warn_non_loopback_http_auth_without_tls` asserts the username and password are absent | pass | Message names listener and bind only | +| Config never rejected for this condition | Warning path only; `cargo test -p eggress-config` (135 + 1 tests) | pass | — | +| pproxy SOCKS4 claim unchanged (`matched`) | `docs/parity/pproxy_capability_manifest.toml` `protocol.socks4.connect_ipv4` / `protocol.socks4.user_id` untouched; no manifest or matrix edit in this pass | pass | Behavior restored to the pinned oracle's `userid in users` semantics | +| `allow_private_egress = true` default preserved | `CompiledListenerUdpConfig::default()` unchanged; `StandaloneUdpConfig`/`RelayConfig` test fixtures still `true`; existing UDP suites green | pass | — | + +## 3. Production implementation evidence + +- `crates/eggress-server/src/accept/handlers.rs` — `accept_socks4` rewritten around + a three-way decision: cached identity, full-credential verification, or the + unauthenticated path. The credential is assembled as `username:password` into a + zeroized buffer and compared with `subtle::ConstantTimeEq`; success records + `ClientIdentity::Username(username)`. Cache-hit sessions no longer re-record the + entry, matching the SOCKS5 accept path (reuse proves an earlier authentication; + only a fresh full-credential success refreshes the cache). +- `crates/eggress-core/src/connector.rs` — `is_reserved_or_private_ip` extended + with `is_v4_cgnat`, `is_v6_nat64`, `is_v6_6to4`, `is_v6_teredo`, + `is_v6_benchmarking`, and `is_v6_orchid`; documented range list updated. +- `crates/eggress-udp/src/security.rs` — literal-target policy now delegates to + the shared classifier and returns the dedicated + `UdpError::PrivateEgressBlocked`; the duplicated private-IP helpers are gone and + the stale "deferred post-DNS check" comment is replaced by the real contract. +- `crates/eggress-udp/src/direct.rs` — `UdpTargetFlow::new` and + `resolve_target` take `allow_private_egress`; `select_resolved_addr` filters the + full answer set and fails closed when nothing is permitted. +- `crates/eggress-udp/src/relay.rs` — direct-flow creation passes the policy and + records `record_dropped()` on failure instead of propagating a bare error. +- `crates/eggress-udp/src/standalone.rs`, + `crates/eggress-udp/src/standalone_shadowsocks.rs` — pass their configured + policy; the existing `record_standalone_rejected()` call sites now also count + post-DNS rejections. +- `crates/eggress-udp/src/error.rs` — added `UdpError::PrivateEgressBlocked`. +- `crates/eggress-config/src/validate/security.rs` — auth-without-TLS warning. + +Public-surface note: `UdpTargetFlow::new` gained a required `allow_private_egress` +parameter (plan §6B directed one policy parameter on the direct flow path). The +crate is unpublished for this pass; the signature change is deliberate so a caller +cannot silently default into permissive egress. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggress-server accept +cargo test -p eggress-protocol-socks +cargo test -p eggress-udp +cargo test -p eggress-runtime --test udp +cargo test -p eggress-runtime --test security_invariants +cargo test -p eggress-config +cargo test -p eggress-core --lib connector +cargo clippy -p eggress-server -p eggress-udp -p eggress-core -p eggress-config --all-targets -- -D warnings +cargo fmt -p eggress-server -p eggress-udp -p eggress-core -p eggress-config +``` + +### Results + +| Command | Result | +|---|---| +| `cargo test -p eggress-server accept` | pass — 47 tests (1 filtered in `public_api`) | +| `cargo test -p eggress-protocol-socks` | pass — 112 + 14 + 2 tests | +| `cargo test -p eggress-udp` | pass — 221 lib + 12 + 17 + 28 tests | +| `cargo test -p eggress-runtime --test udp` | pass — 26 tests | +| `cargo test -p eggress-runtime --test security_invariants` | pass — 8 tests | +| `cargo test -p eggress-config` | pass — 135 + 1 tests | +| `cargo test -p eggress-core --lib connector` | pass — 31 tests (classifier table included) | +| `cargo clippy -p eggress-server -p eggress-udp -p eggress-core -p eggress-config --all-targets -- -D warnings` | pass — no warnings | +| `cargo fmt -p eggress-server -p eggress-udp -p eggress-core -p eggress-config` | pass — no drift after formatting | + +The clippy and `cargo fmt --check` gates were re-run after the final Shadowsocks +standalone test was added (split per crate, identical clean result), so the +recorded evidence matches the final working-tree state. + +Not run in this session (by instruction): workspace-wide `cargo test`, workspace +`clippy`, `cargo fmt --all`, `--all-features`, the external pproxy oracle / +differential / interop suites, benchmarks, fuzz, soak, and `cargo audit`/`cargo +deny`. The differential suites are not required because the SOCKS4 `matched` +claim did not change (see §7). Dependency advisories are owned by other +milestones. + +**Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — +`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace --locked`, the documented CLI/embed feature slices, the +embed OpenSSH regression (6/6), and `cargo deny --workspace check` +(advisories/bans/licenses/sources). `cargo audit --ignore RUSTSEC-2023-0071` +reports only the four tracked `zip 6.0.0` advisories. The condition recorded in +§11 is therefore satisfied. + +## 5. Invariant review + +- SOCKS5, HTTP CONNECT/forward, H2, WebSocket, and reverse auth paths were not + modified; their constant-time comparisons still use `subtle::ConstantTimeEq` + and `cargo test -p eggress-server accept` covers them. +- SOCKS4 failures remain `AcceptError::AuthenticationFailed` with a static + message; `test_socks4_auth_failure_does_not_leak_credentials` asserts the + rendered text contains neither the username, the password, nor the wrong + password. +- The auth-reuse cache remains bounded, monotonic-expiry, and peer-keyed + (`AuthReuseCache` untouched); the only change is which paths may write to it. + Username-only matches cannot reach `record_authenticated`. +- UDP association/flow limits, client pinning, datagram bounds, and idle + timeouts are untouched; the full `eggress-udp` suite (278 tests) is green. +- `allow_private_egress = true` remains the compiled default and the UDP test + fixtures keep using it; loopback echo tests still pass. +- Domain resolution still uses one `tokio::net::lookup_host` call per flow; no + blocking resolver, timeout layer, or second lookup was added. +- No compatibility tier, manifest row, or generated parity report changed. + +## 6. Failure and recovery review + +- A failed SOCKS4 authentication returns before the stream is joined into a + tunnel and before any cache write; there is no partially constructed flow. +- UDP resolution failure or an all-private answer set returns + `UdpError::PrivateEgressBlocked` / `UnresolvedTarget`/`Io` before + `UdpSocket::connect`, so no flow is registered and the existing flow-reaping + and registry-cleanup paths are unchanged. The per-path metrics + (`dropped_packets` for the associate path, `standalone_rejected_datagrams` for + the standalone paths) count the drop. +- Cancellation while resolving is unchanged: `select_resolved_addr` is a pure + function after the lookup, and the flow registry still owns established-flow + cleanup. +- The config warning path is read-only and runs during validation; no runtime + locking, reload, or startup ordering changed. +- Malformed/unauthorized input handling is unchanged: SOCKS4 request parsing + remains bounded by `MAX_USER_ID_LEN`/`MAX_DOMAIN_LEN`, and UDP datagram + decoding remains size-gated. + +## 7. Migration and compatibility review + +- `allow_private_egress` still defaults to `true`; operators who opted into + `false` now actually get domain enforcement. No config schema change; the key + remains `[listeners.udp].allow_private_egress` (and the `defaults` equivalent). +- SOCKS4 clients on auth-enabled listeners must now send the complete + `user:pass` string as the user ID. This restores the pinned pproxy 2.7.9 + behavior (`userid in users`, `users` holding `user:pass` strings); it is + documented in `docs/security/SECURE_CONFIGURATION.md` and + `docs/security/OPEN_PROXY_PREVENTION.md`. +- The pproxy SOCKS4 `matched` claim was **restored**, not changed. No manifest + row, compatibility matrix, or generated parity report was edited, and the + oracle/differential gate was not triggered. The `protocol.socks4.connect_ipv4` + and `protocol.socks4.user_id` rows still describe the pre-pass `matched` + behavior, which is now truthful for auth-enabled listeners as well. +- Cache-hit sessions no longer refresh the SOCKS4 reuse entry. That aligns + SOCKS4 with the SOCKS5 accept path and does not widen authorization: any + cached identity still originates from a full-credential success. pproxy + `--auth` semantics remain owned by Parity M003. +- The classifier extension changes TCP DNS-rebinding outcomes for domains that + resolve into CGNAT or the IPv4-embedding IPv6 ranges (they are now rejected + like RFC 1918). This is the milestone's stated goal; literal targets are + unaffected, and `allow_private_egress = true` continues to permit UDP + loopback/LAN flows. +- No wire-format, protocol-negotiation, or translator change. + +## 8. Security review + +- Authorization: SOCKS4 now requires both credential components; the comparison + is constant-time, the failure is generic, and the accept path returns before + tunnel creation, so no partially authorized session exists. +- Secret handling: the assembled `username:password` buffer is zeroized after + comparison; `InboundAuthentication`'s existing `Drop` zeroization of the + configured password is untouched; no new `Debug`/`Display` surface exposes + credentials. +- The config warning text contains only the listener name and bind address — + never a username, password, env var value, or URI (asserted by test). +- Path validation: UDP literal shape checks stay in place; post-DNS filtering + uses the same shared classifier as the TCP guard, so the two gates cannot + drift. +- Denial-of-service bounds: unchanged (no new allocations proportional to input + beyond the answer list already collected, which the previous `.next()` also + materialized from the same iterator). +- Audit behavior: dropped/rejected datagrams now produce a metric on the + associate direct path where previously the error was only traced. + +## 9. Documentation and operations + +- `docs/security/THREAT_MODEL.md` — A1 mitigations (auth-without-TLS warning), + and mitigations 17–19 (SOCKS4 full-credential semantics, UDP post-DNS policy, + classifier ranges). +- `docs/security/OPEN_PROXY_PREVENTION.md` — warning-system bullet, expanded + SOCKS4/SOCKS5/HTTP/Shadowsocks protocol controls, and the updated testing list. +- `docs/security/SECURE_CONFIGURATION.md` — auth table note for SOCKS4, an + "Auth without TLS" paragraph, and the private-egress/UDP subsection (CGNAT and + friends, `allow_private_egress` example). CIDR and admin wording intentionally + left to the routing milestone. +- `architecture/protocols-socks.md` — SOCKS4 user-ID credential-carrier contract + and the cross-crate test coverage note. +- `architecture/udp.md` — module-map row for `direct.rs`, post-DNS policy + contract, per-packet step, test coverage, and a reviewer gotcha. +- No operator commands, exit codes, metrics names, or configuration keys were + added or renamed. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | `UdpTargetFlow::new` gained a required `allow_private_egress` parameter (public crate surface). | Downstream callers in this workspace are updated; an external embedder compiling against the next release must pass the flag. | Covered by the next release's changelog/versioning decision; no action inside this milestone. | +| low | A domain resolving to `localhost`-style dual-stack answers under `allow_private_egress = true` still connects to the first answer, which may be an address family the local UDP bind cannot reach. | Pre-existing behavior, unchanged by this pass; tests use numeric or all-private resolution to stay deterministic. | Not in scope; record only if cross-family UDP target selection is prioritized. | +| low | SOCKS4 has no auth-failure session metric (the accept signature carries no session metrics). | Failures are logged/handled generically but not counted. | Plan §6A allowed deferral; candidate for a later metrics milestone. | + +No critical or high finding remains. + +## 11. Roadmap disposition + +Milestone closed: production implementation, the focused verification set, and +the coordinator's workspace-wide `fmt`/`clippy`/`test` gate all passed. No +corrective implementation plan is required for M003 scope. + +## 12. Registry updates + +- `plans/subsystems/protocols-edge-roadmap.md`: top status line, dependency-graph + label, Milestone 3 status, and §12 milestone row moved from `ready` to + `closed` with this closure record. +- `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md`: + status `ready` → `implemented`. +- `plans/subsystems/security-hardening-roadmap.md` S3: no edit required by this + milestone's ownership (its §12 row is coordinated by the security roadmap's own + wave); the evidence above satisfies the S3 exit conditions. +- No change to `plans/registry.md` was made, because the registry row for this + implementation belongs to the shared corrective-wave bookkeeping owned by the + coordinator. +- No release, tag, or commit created. diff --git a/plans/closure/routing-health-observability/003-status.md b/plans/closure/routing-health-observability/003-status.md new file mode 100644 index 00000000..c347f5bc --- /dev/null +++ b/plans/closure/routing-health-observability/003-status.md @@ -0,0 +1,303 @@ +# Routing, Health, Metrics, and Admin Milestone 003 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` + +Source subsystem roadmap: + +- `plans/subsystems/routing-health-observability-roadmap.md` (Milestone 3) +- `plans/subsystems/security-hardening-roadmap.md` (S4; audit findings M4, L12, M8 admin half) + +Repository baseline reviewed: `ba64e16` (workspace 1.0.12) with the +2026-11-16 corrective waves present as uncommitted working-tree changes + +Implementation commits or pull requests: + +- none — this milestone is delivered as an uncommitted working-tree change per + the coordinator's instruction (no commit, tag, or release was created) + +## 1. Executive finding + +The milestone is complete at the implementation level. Both routing matchers +now canonicalize IPv4-mapped IPv6 literals before a CIDR comparison, so +`::ffff:10.0.0.1` matches `10.0.0.0/8` for `destination_cidr` and +`source_cidr` (including inside a negation) without altering the target or +source reported by `route explain`. The literal-IP-only CIDR contract is now +explicit in the config validator (a conservative advisory warning) and in the +operator documentation, and the admin HTTP surface validates `Host` (plus +`Origin` and `Content-Type` for the one POST endpoint) against +`[admin] allowed_hosts` before authentication and before any body is read, with +a plaintext-transport warning for non-loopback binds. + +No DNS resolution was added to routing, no admin state-changing endpoint was +introduced, admin auth/limiter/connection/body limits are unchanged, and no +compatibility claim was touched. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| `::ffff:10.0.0.1` matches `10.0.0.0/8` for `destination_cidr` | `eggress-routing` `ipv4_mapped_destination_matches_ipv4_cidr`; live `route explain` demo | pass | Also `mapped_destination_cannot_bypass_negated_cidr` | +| `::ffff:10.0.0.1` matches an IPv4 CIDR for `source_cidr` | `ipv4_mapped_source_matches_ipv4_source_cidr`; runtime `route_explain_source_field_changes_decision` (mapped source) | pass | Also `mapped_source_cannot_bypass_negated_source_cidr` | +| Native IPv6 still matches native IPv6; unrelated v4/v6 does not match | `ipv6_cidr_match`, `native_ipv6_source_cidr_still_matches`, `ipv4_cidr_does_not_match_unrelated_native_ipv6`, `native_ipv6_cidr_does_not_match_ipv4`, `ipv4_mapped_destination_outside_ipv4_cidr_no_match` | pass | Family-correct in both directions | +| Route semantics and `route explain` reporting unchanged | `mapped_destination_canonicalization_does_not_rewrite_explanation`; live demo reports `[::ffff:10.1.2.3]:443` | pass | Canonicalization is local to the comparison | +| Config warning for private/reserved `destination_cidr` + `reject` + no host condition | `warn_private_destination_cidr_reject_rule_without_host_condition`, `warn_private_destination_cidr_inside_negation`, `warn_private_ipv4_mapped_destination_cidr` | pass | Non-fatal; message names the literal-only contract and upstream remote resolution | +| No warning when a host condition exists, for public ranges, or for non-reject actions | `no_warn_private_cidr_when_host_condition_present`, `no_warn_private_cidr_when_shortcut_host_condition_present`, `no_warn_public_destination_cidr_reject_rule`, `no_warn_private_cidr_for_non_reject_action` | pass | Conservative by design | +| Warning never echoes credentials or upstream URIs | `cidr_warning_does_not_echo_credentials_or_upstream_uri`, `warn_plaintext_non_loopback_admin_even_with_auth` | pass | Asserts on the secret and endpoint strings | +| `[admin] allowed_hosts` TOML + compiled field, additive to bind defaults | `compile_admin_allowed_hosts_default_to_loopback_names`, `compile_admin_allowed_hosts_are_additive_and_normalized`, `compile::admin_hosts::tests::*` | pass | Case-insensitive, port-insensitive, bracketed IPv6 | +| Invalid/wildcard entry rejected at validation | `invalid_admin_allowed_host_entry_is_rejected` | pass | `admin.allowed_hosts[0]` diagnostic | +| Host validation before auth and before body read | `host_rejection_precedes_authentication` | pass | Bad Host → 400 even with a bearer token configured | +| Missing/unparseable/unknown Host → generic 400, no echo, no redirect | `dns_rebinding_host_is_rejected`, `missing_or_unparseable_host_is_rejected`, runtime `admin_host_origin_and_content_type_policy_from_config` | pass | Body is exactly `bad request` | +| `X-Forwarded-Host` ignored | `forwarded_host_header_does_not_widen_the_allowlist` | pass | Only the actual `Host` header counts | +| Default `http://127.0.0.1:9090` works with no config | `default_loopback_hosts_are_accepted`, `empty_allowed_hosts_falls_back_to_the_bound_address`, live curl `200` | pass | `localhost` and `[::1]:port` too | +| `POST /-/route-explain` requires `application/json` | `route_explain_requires_json_content_type`, `route_explain_accepts_json_content_type` | pass | `415` otherwise; parameters and case tolerated | +| `Origin` host must be allowlisted; `Origin: null` rejected unless listed | `route_explain_rejects_cross_origin_post`, `route_explain_accepts_same_origin_post`, `route_explain_rejects_null_origin_unless_allowed` | pass | `403` with a generic body, no echo | +| Non-loopback plaintext admin warning | `warn_plaintext_non_loopback_admin_even_with_auth`; live supervisor log capture | pass | Existing no-auth warning retained | +| Reload policy for `allowed_hosts` | `reload_rejects_admin_allowed_hosts_change`, `eggress-runtime --test reload` | pass | `classify_reload_config` now compares the allowlist, so a change requires a restart (same policy as `admin.bind`) | +| Existing admin auth/limiter/status tests remain green | `cargo test -p eggress-admin`, `cargo test -p eggress-runtime --test admin` | pass | 50 + 23 tests | +| No pproxy compatibility claim change | no manifest or tier change in scope | pass | Manifest untouched | +| Docs updated | `docs/security/SECURE_CONFIGURATION.md`, `docs/CONFIG_REFERENCE.md`, `docs/security/THREAT_MODEL.md`, `architecture/routing.md`, `architecture/admin.md` | pass | Admin/CIDR sections only in the shared security doc | + +## 3. Production implementation evidence + +Routing (`crates/eggress-routing/src/matcher.rs`): + +- `canonical_ip(IpAddr) -> IpAddr` uses `Ipv6Addr::to_ipv4_mapped()` and is + applied in `MatchExpr::DestinationCidr` and `MatchExpr::SourceCidr` + immediately before `IpNet::contains`. `TargetHost::Domain` still returns + `false`; nothing is resolved. The `RouteRequest` target/source is untouched, + so `Router::explain` keeps reporting the client-supplied literal. +- No async work, lock, or allocation was added beyond the copy of an `IpAddr`. + +Config (`crates/eggress-config/`): + +- `validate/security.rs`: `warn_literal_only_cidr_reject_rules` walks each + `reject` rule's match expression (bounded by `MAX_MATCH_EXPR_DEPTH`), + records whether a `host_exact`/`host_suffix`/`host_regex` condition scopes + the rule (including the rule-level shortcut fields) and the first + `destination_cidr` whose network or last address is private/reserved per + `eggress_core::connector::is_reserved_or_private_ip`. One advisory warning per + such rule, at the leaf path, naming the CIDR and the literal-only contract. + The non-loopback admin block now emits a plaintext-HTTP warning in addition to + the retained no-auth warning. +- `model.rs`: `AdminConfig.allowed_hosts: Option>` with + `#[serde(default)]`. +- `compile/admin_hosts.rs` (new): `normalize_host_entry`, + `derive_allowed_hosts`, `effective_allowed_hosts`. +- `compile/model.rs`: compiled `AdminConfig.allowed_hosts: Vec`. +- `compile/process.rs`: `compile_admin` derives the effective allowlist from the + resolved bind (default `127.0.0.1:9090`) plus configured entries. +- `validate/core.rs`: `validate_admin` rejects an unparseable entry or a + wildcard (`admin.allowed_hosts[i]`). + +Admin (`crates/eggress-admin/`): + +- `server.rs`: `AdminState.allowed_hosts`; `run()` replaces an empty list with + bind-derived defaults for the address that actually bound; `host_allowed()` + runs first in the per-request service (before auth, before any body read) and + returns a generic `400 "bad request"`. `request_origin_allowed()` and + `request_content_type_is_json()` live here; `normalize_host_entry` is reused + from `eggress-config` so configured entries and header values normalize + identically. The non-loopback bind warning now states plaintext HTTP and + points at `allowed_hosts`. +- `routes.rs`: `/-/route-explain` rejects a non-JSON `Content-Type` (`415`) and + a disallowed `Origin`/`Origin: null` (`403`) before `collect_limited`. +- `client.rs`: no behavior change; the client already sent + `Content-Type: application/json` and `Host: :`. + +Runtime (`crates/eggress-runtime/`): the compiled `allowed_hosts` is cloned +into `AdminState` at admin task spawn (`supervisor/services.rs`). Because the +allowlist is fixed when the admin task starts, `supervisor/reload.rs`'s +`classify_reload_config` now compares it alongside `enabled`/`bind`, so editing +`allowed_hosts` fails the reload with "admin endpoint bind/allowed_hosts +configuration changed; restart required" instead of silently keeping the old +policy. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggress-routing +cargo test -p eggress-config +cargo test -p eggress-admin +cargo test -p eggress-runtime --test admin +cargo test -p eggress-runtime --test security_invariants +cargo clippy -p eggress-routing -p eggress-admin -p eggress-config -p eggress-runtime --all-targets -- -D warnings +cargo fmt -p eggress-routing -p eggress-admin -p eggress-config -p eggress-runtime -- --check +cargo build -p eggress-cli --bin eggress +cargo check -p eggress-pproxy-compat --all-targets +cargo test -p eggress-runtime --lib +cargo test -p eggress-runtime --test reload +``` + +### Results + +- `eggress-routing`: 153 lib tests passed (183 total across lib, `properties`, + `scheduler_parity`), 0 failed. +- `eggress-config`: 153 lib tests + 1 `tests/fuzz_smoke.rs` passed, 0 failed. +- `eggress-admin`: 50 lib tests passed, 0 failed. +- `eggress-runtime --test admin`: 23 passed, 0 failed. +- `eggress-runtime --test security_invariants`: 8 passed, 0 failed. +- clippy (four crates, all targets, `-D warnings`): clean, no warnings. +- `cargo fmt --check` (four crates): clean. `--all` was deliberately not used; + the workspace-wide gate is the coordinator's step. +- `cargo build -p eggress-cli --bin eggress`: succeeded (used for the live + evidence below). +- `cargo check -p eggress-pproxy-compat --all-targets`: clean after the + one-field compile fix described in §10. +- `eggress-runtime --lib`: 70 passed, 0 failed (includes the new + `reload_rejects_admin_allowed_hosts_change`). +- `eggress-runtime --test reload`: 18 passed, 0 failed. + +Not run, by instruction from the coordinator: `cargo test --workspace`, +`cargo clippy --workspace`, `cargo fmt --all`, `--all-features`, benches, +oracle/differential/interop suites, `cargo deny`/`cargo audit`. + +**Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — +`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace --locked`, the documented CLI/embed feature slices, the +embed OpenSSH regression (6/6), and `cargo deny --workspace check` +(advisories/bans/licenses/sources). `cargo audit --ignore RUSTSEC-2023-0071` +reports only the four tracked `zip 6.0.0` advisories. The condition recorded in +§11 is therefore satisfied. + +## 5. Invariant review + +- **First-match-wins / explanation semantics**: unchanged. Only the value + handed to `IpNet::contains` is canonicalized; rule ordering, action mapping, + and `RouteExplanation` fields are untouched (proved by + `mapped_destination_canonicalization_does_not_rewrite_explanation` and the + live demo). +- **CIDR matching stays synchronous and literal-only**: no DNS, no blocking + work, no new locks, no new allocations per rule beyond an `IpAddr` copy; a + `Domain` target still never matches. The warning makes the contract explicit + instead of silently implying a private-network ACL. +- **`SourceCidr` remains the exact peer address**: no proxy-header trust was + added; `X-Forwarded-For` is still not read. +- **Admin auth/limiter/caps unchanged**: `authorized()`, the per-IP failure + limiter, the 64-connection semaphore, 16 KiB body cap, 30 s connection + timeout, endpoint set, default bind, and enabled default are untouched. + Host validation was inserted ahead of auth, so it cannot weaken it; + `host_rejection_precedes_authentication` asserts both orderings (400 then + 401). +- **Loopback clients keep working with no configuration**: bind-derived + defaults cover `127.0.0.1`, `localhost`, and `::1` (and stay in place for a + wildcard bind), asserted by `default_loopback_hosts_are_accepted`, + `empty_allowed_hosts_falls_back_to_the_bound_address`, and live curl. +- **No compatibility claim change**: manifest, tier vocabulary, and generated + parity reports untouched. + +## 6. Failure and recovery review + +- **Rejected Host/Origin/content-type**: fails before auth and before the body + is consumed, so no state changes and no unbounded read. Responses are generic + (`bad request`, `{"error":"origin not allowed"}`, + `{"error":"expected content-type: application/json"}`) and never echo the + rejected value, credentials, or topology. +- **Missing/unparseable Host**: fails closed with 400. A request without + `Content-Length`/body is never inspected first. +- **Empty allowlist in a hand-built `AdminState`**: `run()` derives defaults + from the bound address instead of denying everything; the production path + always supplies the compiled list, so this is a fallback, not a policy. +- **Startup bind failure**: unchanged — still a startup error before readiness. +- **Reload**: the allowlist is bound to the listener, not to the snapshot, and + `classify_reload_config` now rejects a change to it with the same + restart-required verdict as `admin.bind`; routing/health/upstream swaps are + unaffected. No partial state swap was added. +- **Cancellation/shutdown**: unchanged; the admin task still stops last through + the ordered shutdown path. No new task or timer was introduced. +- **Malformed input**: identity length/emptiness, invalid `source`/`target`, + and oversized body handling are unchanged and covered by the existing runtime + admin tests. + +## 7. Migration and compatibility review + +- `[admin] allowed_hosts` is additive with a serde default. Existing configs + compile; loopback admin keeps working with no new key because the defaults + are derived from `bind`. +- Operators reaching admin through a reverse proxy or a DNS name must add that + host; otherwise requests fail closed with `400`. Documented migration note in + `docs/security/SECURE_CONFIGURATION.md` and the new key in + `docs/CONFIG_REFERENCE.md`. +- Wildcard allowlist entries are rejected at validation rather than silently + ignored, so a mistaken "allow everything" cannot look like a security control. +- CIDR canonicalization only changes previously broken mapped-IPv6 matches; + literal IPv4 and native IPv6 behavior is unchanged. The warning is advisory — + no configuration is rejected. +- One internal compile-only consequence: the TOML `AdminConfig` gained a field, + so `eggress-pproxy-compat`'s in-process translator literal needed + `allowed_hosts: None` (see §10). No translator output, URI grammar, or tier + behavior changed. + +## 8. Security review + +- The DNS-rebinding read path is closed for the admin surface: `/-/status`, + `/-/config`, `/-/routes`, `/-/upstreams`, `/-/reverse`, and `/metrics` all + require an allowlisted `Host`; `/-/route-explain` additionally requires JSON + content type and an allowlisted `Origin`. +- The check is a pure header comparison: no DNS lookup, no additional + connection, and the allowlist is fixed for the listener lifetime. +- `X-Forwarded-Host` is deliberately ignored, so a header the client controls + cannot widen the allowlist. +- A rejected request never reflects attacker input, so the endpoint cannot be + used as an HTML/JSON injection vector, and the generic body leaks no topology. +- Plaintext admin transport is now warned twice (config load and runtime) with + concrete alternatives; admin TLS remains explicitly out of scope. +- No credentials appear in any new warning or response: asserted by + `cidr_warning_does_not_echo_credentials_or_upstream_uri`, + `warn_plaintext_non_loopback_admin_even_with_auth`, and the response-body + assertions on the admin tests. +- Redaction rules, auth constant-time comparison, limiter behavior, and the + bounded body/connection caps are unchanged. + +## 9. Documentation and operations + +- `docs/security/SECURE_CONFIGURATION.md`: admin section rewritten (plaintext + transport, `allowed_hosts`, Origin/Content-Type policy, migration note) and + the CIDR section now states the literal-only contract, the mapped-IPv6 + canonicalization, and the advisory warning. Default-vs-hardened table and + checklist gained admin transport/allowlist rows. +- `docs/CONFIG_REFERENCE.md`: `[admin] allowed_hosts` row plus a policy + paragraph; CIDR leaf-matcher descriptions now say "literal target/source IP" + with a paragraph on no-DNS, mapped-IPv6 canonicalization, and the warning. +- `docs/security/THREAT_MODEL.md`: new attacker A10 (DNS-rebinding web page), + admin entry-point note, and mitigations 20–21. +- `architecture/routing.md`: new "CIDR matching rules" section (canonicalization, + literal-only, explanation unchanged) plus security-note and test-map updates. +- `architecture/admin.md`: `AdminState.allowed_hosts`, the Host/Origin gate in + the request pipeline, invariants, security notes, test map, and a reviewer + gotcha about bind-derived defaults. +- Operator diagnostics: warnings carry a stable path (`admin.bind`, + `rules[i]…destination_cidr`) so they can be filtered. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | `crates/eggress-pproxy-compat/src/translate/native.rs` needed a one-field compile fix (`allowed_hosts: None`) because the TOML `AdminConfig` gained a field | none — behavior identical; the file is outside this milestone's file list | Coordinator should include the one-line diff in the parity-compat wave review so it is not mistaken for a compat change | +| low | `crates/eggress-runtime/src/supervisor/reload.rs` gained the `allowed_hosts` comparison and `crates/eggress-runtime/src/supervisor.rs` gained one unit test (`reload_rejects_admin_allowed_hosts_change`) to satisfy plan §10's reload requirement | none — admin config changes already require a restart for `bind`; this closes a silent divergence for the new security field | Coordinator should include these two files in the runtime review scope; only `supervisor/services.rs` was listed in the assignment | +| low | Admin TLS is still not implemented: non-loopback admin remains plaintext and is only warned about | expected — explicitly out of scope for M003 | separate architecture decision if native admin TLS is ever required | +| low | `destination_cidr`/`source_cidr` remain literal-IP-only; the guard for names is the resolved-target egress policy | by contract, not a defect | document/consume the egress guard rather than adding DNS to routing | + +## 11. Roadmap disposition + +Milestone closed. The coordinator's workspace-wide `cargo fmt --all -- --check`, +`cargo clippy --workspace --all-targets -- -D warnings`, and +`cargo test --workspace --locked` gate passed on 2026-11-16 after all six +corrective waves landed. No corrective implementation plan is required for M003 +scope itself. + +## 12. Registry updates + +- `plans/subsystems/routing-health-observability-roadmap.md`: status line, + Milestone 3 status, and the milestone table row now record + `closed` with this closure record as the link. +- `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md`: + `Status: implemented`. +- `plans/registry.md`: no change made by this session — the milestone row is + owned by the coordinator's registry reconciliation across the corrective + waves. diff --git a/plans/closure/transports/004-status.md b/plans/closure/transports/004-status.md new file mode 100644 index 00000000..daa74fe0 --- /dev/null +++ b/plans/closure/transports/004-status.md @@ -0,0 +1,329 @@ +# Transports Milestone 004 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` + +Source subsystem roadmap: + +- `plans/subsystems/transports-roadmap.md` §7 Milestone 4, §12 milestone status +- `plans/subsystems/security-hardening-roadmap.md` H1 and L11 + +Repository baseline reviewed: `ba64e16` (branch `feat/auto-20261116-652bb64d`, workspace `1.0.12`) + +Implementation commits or pull requests: + +- None. This pass is uncommitted working-tree work in the shared corrective + wave; no commit, tag, or publication was created by this milestone. + +## 1. Executive finding + +The release-blocking default-graph defect is closed. Default outbound TLS now +resolves `rustls 0.23.46`, `rustls-webpki 0.103.17`, `webpki-roots 1.0.12` +(reached through the `webpki-roots 0.26.11` compatibility re-export), +`rustls-platform-verifier 0.7.1`, `webpki-root-certs 1.0.12`, +`quinn 0.11.12`, `quinn-proto 0.11.19`, `quinn-udp 0.5.16`, and +`tokio 1.54.1`. `cargo audit` no longer reports RUSTSEC-2026-0381/-0382 (the +distrusted emSign root and the compromised-intermediate acceptance path) or any +rustls/quinn/tokio advisory. No source adaptation was required: the only +compile-affecting change outside the lockfile is documentation and the two +new behavioural guards. + +The two truth/doc defects and the latent secret exposure found by the same +audit are also closed: the bundled-Mozilla root set is now described as such +instead of as a "system root store", `?insecure` is documented as reachable +from configuration builds rather than API-only, config compilation emits one +redacted warning per upstream that selects it, and +`CompiledListenerTlsConfig` no longer prints PEM or key bytes. + +Closure is conditional on one item only: the coordinator's workspace-wide +`fmt`/`clippy`/`test` gate, which runs after every corrective wave has landed. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Default graph resolves `rustls >= 0.23.46` | `cargo tree -i rustls@0.23.46` → `rustls v0.23.46` | pass | 0.23.46 exactly | +| Default graph resolves `rustls-webpki >= 0.103.16` | `cargo tree -i rustls-webpki` → `rustls-webpki v0.103.17` | pass | 0.103.17 accepted by plan §16 | +| Default graph resolves `webpki-roots 1.x >= 1.0.10` | `cargo tree -i webpki-roots@1.0.12` → parent is `webpki-roots v0.26.11` → `eggress-transport-tls` | pass | 1.x parent verified, not just the 0.26 string | +| `rustls-platform-verifier` / `webpki-root-certs` fixed | lock: `0.7.1` / `1.0.12` (`cargo update` output) | pass | | +| Fixed quinn graph | `cargo tree -p eggress-transport-quic -i quinn` → `0.11.12`; `-i quinn-proto` → `0.11.19`; `-i quinn-udp` → `0.5.16` | pass | quinn is not in the root package graph, so the inverse tree is taken from its owner crate | +| `tokio` fixed | `cargo tree -i tokio` → `tokio v1.54.1` | pass | | +| `cargo audit` no longer reports RUSTSEC-2026-0381/-0382 | `cargo audit --ignore RUSTSEC-2023-0071` | pass | Neither ID appears in the report | +| `cargo audit` no longer reports the rustls/quinn/tokio IDs | same run; grep for `-0346/-0347/-0348/-0349`, `quinn`, `tokio` returns nothing | pass | | +| Default outbound TLS verifies; no insecure fallback | `eggress-transport-tls` test `default_verified_config_rejects_self_signed_server` | pass | Self-signed peer rejected by the process-shared default config | +| Default configuration is built from the current root set | `eggress-transport-tls` test `builder_system_roots` asserts the root count equals `webpki_roots::TLS_SERVER_ROOTS.len()` and is non-empty | pass | | +| Custom CA replacement unchanged | pre-existing `builder_with_custom_ca_pem`, `client_config_with_alpn_preserves_trust_policy` | pass | Retained, unmodified | +| mTLS identity unchanged | pre-existing `client_config_with_alpn_preserves_mtls_identity` | pass | Retained, unmodified | +| ALPN preservation unchanged | pre-existing `client_config_with_alpn_*` (3 tests) | pass | Retained, unmodified | +| `tls_override` + per-hop `insecure=true` fails closed | pre-existing `eggress-outbound` tests `tls_override_plus_insecure_fails_closed{,_with_insecure_tls_feature}` | not run in this wave | No code on that path changed; deferred to the coordinator workspace gate (see §10) | +| H2 pool scoping unchanged | pre-existing `eggress-outbound` pool tests | not run in this wave | Unchanged code path; deferred to the coordinator workspace gate | +| Trust-store wording corrected | `architecture/transports-tls.md`, `docs/security/SECURE_CONFIGURATION.md`, `docs/SECURITY_REVIEW.md`, `docs/security/THREAT_MODEL.md` | pass | "bundled Mozilla roots via webpki-roots", not "system root store" | +| `?insecure` documented as config-reachable | `docs/URI_GRAMMAR.md`, `docs/security/SECURE_CONFIGURATION.md`, `docs/SECURITY_REVIEW.md` | pass | "API-only" claim removed | +| Insecure selection warns once, before first handshake, redacted | `eggress-config` tests `compile_warns_once_for_the_insecure_upstream_only`, `compile_does_not_warn_when_every_hop_verifies` | pass | One event per upstream at compile time; no endpoint/credential/URI echo | +| Warning shape names the policy decision | `insecure_hop_summary_*` tests + emitted fields `upstream`, `insecure_hops`, `policy=insecure-tls` | pass | | +| TLS private key never appears in `Debug` | `eggress-config` tests `compiled_listener_tls_debug_redacts_pem_material`, `compiled_listener_tls_debug_reports_absent_material`, `listener_config_debug_redacts_nested_tls_key` | pass | Reports `has_cert`/`has_key`/`key_len` only | +| Reverse-TLS types already redact | `crates/eggress-config/src/compile/model.rs` `CompiledReverseServerTls`/`CompiledReverseClientTls` custom `Debug`; `eggress-protocol-reverse` `ReverseServerTlsConfig`/`ReverseClientTlsConfig` | pass | Inspected; no change required | +| No OpenSSL/native-tls/aws-lc/C crypto introduced | lock scan: `aws-lc-sys` 0, `aws-lc-rs` 0, `openssl-sys` 0, `native-tls` 0; `cargo tree -e features -i rustls@0.23.46` shows `ring` only | pass | | +| MSRV 1.89 and edition 2021 remain valid | `rustc 1.89.0` / `cargo 1.89.0` compiled every checked crate | pass | | +| Insecure QUIC stays behind `insecure-quic` | existing compile-time rejection in `compile_upstreams` retained; `insecure-quic` feature untouched | pass | | +| No pproxy compatibility claim changed | no manifest, tier, or oracle/differential evidence touched | pass | | + +## 3. Production implementation evidence + +Implemented: + +- **Lockfile.** `Cargo.lock` moved exactly ten package versions and gained one + dependency edge (`eggress-config` → `tracing`). No manifest version + requirement was changed; no gated version location was touched. + - `rustls 0.23.45 → 0.23.46` + - `rustls-webpki 0.103.15 → 0.103.17` + - `webpki-roots 1.0.8 → 1.0.12` (the `0.26.11` re-export is unchanged) + - `rustls-platform-verifier 0.7.0 → 0.7.1` and + `rustls-platform-verifier-android 0.1.1 → 0.2.0` + - `webpki-root-certs 1.0.9 → 1.0.12` + - `quinn 0.11.11 → 0.11.12`, `quinn-proto 0.11.17 → 0.11.19`, + `quinn-udp 0.5.15 → 0.5.16` + - `tokio 1.52.3 → 1.54.1` +- **Trust-store truth.** `TlsClientConfigBuilder::with_system_roots` rustdoc and + `default_client_config` rustdoc now state that the roots are the bundled + Mozilla set from `webpki-roots`, compiled into the binary, not the OS store, + and that `with_custom_ca_pem` replaces rather than extends them. Method name + and signature are unchanged for source compatibility. +- **Insecure selection is announced.** `eggress-config` compiles one + `tracing::warn!` per upstream whose chain contains any `?insecure` hop, from + `compile_upstreams` — the same funnel used by TOML startup/reload + (`load_and_compile`) and by the pproxy translator (`compile_config`). The + event carries `upstream` (config id), `insecure_hops` (`hop ()`), + and `policy = "insecure-tls"`. Endpoints, ports, credentials, and the source + URI are never included. It fires once per load, before any chain executes. +- **Secret-bearing `Debug` removed.** `CompiledListenerTlsConfig` in + `eggress-config` no longer derives `Debug`; a manual implementation prints + `has_cert`, `has_key`, `key_len`, and `alpn`. The reverse-TLS compiled types + already had redacting `Debug` (plus zeroizing `Drop`) and were verified, not + modified. +- **`eggress-config` dependency.** Added `tracing.workspace = true` so the + config crate can emit the security notice. No new external crate entered the + graph; `tracing` was already a workspace dependency. + +Planned but deliberately absent (out of scope, unchanged): + +- An OS certificate-store backend. The trust source remains the bundled set. +- Removal of `insecure-tls` from default CLI/runtime builds. That would need a + separate pproxy `--ssl`/QUIC compatibility assessment. + +## 4. Verification executed + +### Commands run + +```bash +cargo update -p rustls@0.23.45 -p rustls-webpki@0.103.15 -p webpki-roots@1.0.8 \ + -p rustls-platform-verifier@0.7.0 -p webpki-root-certs@1.0.9 \ + -p quinn@0.11.11 -p quinn-proto@0.11.17 -p quinn-udp@0.5.15 -p tokio@1.52.3 +cargo tree -i rustls@0.23.46 +cargo tree -i rustls-webpki +cargo tree -i webpki-roots@1.0.12 +cargo tree -i webpki-roots@0.26.11 +cargo tree -i tokio +cargo tree -p eggress-transport-quic -i quinn +cargo tree -p eggress-transport-quic -i quinn-proto +cargo tree -p eggress-transport-quic -i quinn-udp +cargo tree -p eggress-transport-tls -e features -i rustls@0.23.46 +cargo test -p eggress-transport-tls +cargo test -p eggress-config +cargo test -p eggress-runtime --test tls +cargo test -p eggress-embed --test error_redaction +cargo clippy -p eggress-transport-tls -p eggress-config --all-targets -- -D warnings +cargo fmt -p eggress-transport-tls -p eggress-config -- --check +cargo audit --ignore RUSTSEC-2023-0071 +cargo check -p eggress-cli --locked --no-default-features \ + --features full,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins +``` + +`cargo fmt --all`, `cargo clippy --workspace`, `cargo test --workspace`, and +`--all-features` were intentionally not run: the coordinator runs the broad gate +once, after every corrective wave has landed. + +### Results + +| Command | Result | +|---|---| +| `cargo update …` | pass — "Locking 10 packages to latest compatible versions" | +| `cargo tree -i rustls@0.23.46` | pass — `rustls v0.23.46` under `eggress-core`, `eggress-outbound`, `eggress-transport-tls`, `eggress-bench`, `tokio-rustls 0.26.4` | +| `cargo tree -i rustls-webpki` | pass — `rustls-webpki v0.103.17` under `rustls v0.23.46` | +| `cargo tree -i webpki-roots@1.0.12` | pass — parent `webpki-roots v0.26.11` → `eggress-transport-tls` | +| `cargo tree -i webpki-roots@0.26.11` | pass — under `eggress-transport-tls`, `eggress-bench`, `eggress-outbound` | +| `cargo tree -i tokio` | pass — `tokio v1.54.1` across the workspace | +| `cargo tree -p eggress-transport-quic -i quinn{-proto,-udp}` | pass — `quinn 0.11.12`, `quinn-proto 0.11.19`, `quinn-udp 0.5.16` | +| `cargo tree -e features -i rustls@0.23.46` | pass — `ring`/`std`/`tls12` only, no aws-lc | +| `cargo test -p eggress-transport-tls` | pass — 24 passed, 0 failed; 0 doc-tests | +| `cargo test -p eggress-config` | pass — 129 lib tests passed, 0 failed; `tests/fuzz_smoke.rs` 1 passed; 0 doc-tests | +| `cargo test -p eggress-runtime --test tls` | pass — 4 passed, 0 failed | +| `cargo test -p eggress-embed --test error_redaction` | **blocked, not run to completion** — the test binary could not link because `crates/eggress-pproxy-compat/src/translate/model.rs:159` derives `Debug` for `ReverseServerToml` while line 187 also defines `impl std::fmt::Debug for ReverseServerToml` (E0119). That file belongs to the concurrent parity-compat corrective wave and was not modified here. | +| `cargo clippy -p eggress-transport-tls -p eggress-config --all-targets -- -D warnings` | pass — finished with no warnings | +| `cargo fmt -p eggress-transport-tls -p eggress-config -- --check` | pass — no diffs after applying `cargo fmt` to the same two packages | +| `cargo audit --ignore RUSTSEC-2023-0071` | partial by design — 8 vulnerabilities remain, all outside this milestone; 3 yanked-crate warnings; 1 `unsound` warning. TLS/QUIC/tokio advisories are gone. | +| `cargo check -p eggress-cli … --features full,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins` | **blocked, not run to completion** — same E0119 error in `eggress-pproxy-compat`. The `pproxy-legacy`/`pproxy-daemon` feature slice pulls that crate in, so this command cannot resolve until the parity-compat wave compiles. | + +Remaining `cargo audit` findings, with ownership: + +| Crate | Advisory | Owner | +|---|---|---| +| `russh` | RUSTSEC-2026-0492 | Transports M005 (optional `ssh`) | +| `russh` | RUSTSEC-2026-0495 | Transports M005 | +| `crypto-bigint` | RUSTSEC-2026-0387 (also yanked) | Transports M005 (`russh` path) | +| `ctutils` | RUSTSEC-2026-0385 | Transports M005 (`russh` path) | +| `zip` | RUSTSEC-2026-0429 | Delivery M004 | +| `zip` | RUSTSEC-2026-0367 | Delivery M004 | +| `zip` | RUSTSEC-2026-0368 | Delivery M004 | +| `zip` | RUSTSEC-2026-0369 | Delivery M004 | +| `rustix 1.1.4` | RUSTSEC-2026-0486 (`unsound`, xattr) | Pre-existing via `tempfile 3.27.0`; unchanged by this pass and outside the TLS/QUIC/tokio scope | +| `der 0.8.0`, `wnaf 0.14.0` | yanked (warning only, not advisories) | Pre-existing; `russh`/crypto path | + +Absent from the report (previously present): RUSTSEC-2026-0381, RUSTSEC-2026-0382, +RUSTSEC-2026-0346, RUSTSEC-2026-0347, RUSTSEC-2026-0348, RUSTSEC-2026-0349. + +**Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — +`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace --locked`, the documented CLI/embed feature slices, the +embed OpenSSH regression (6/6), and `cargo deny --workspace check` +(advisories/bans/licenses/sources). `cargo audit --ignore RUSTSEC-2023-0071` +reports only the four tracked `zip 6.0.0` advisories. The condition recorded in +§11 is therefore satisfied. + +## 5. Invariant review + +- **Default outbound TLS verifies; no insecure fallback.** `build()` still + selects `with_root_certificates(...)` unless `self.insecure` was explicitly + requested. The new + `default_verified_config_rejects_self_signed_server` test proves the shared + default rejects an unverifiable peer, so an accidental downgrade in the + verifier path would fail a test rather than silently succeed. +- **Custom CA replaces the root store.** `with_custom_ca_pem` still assigns + `builder.root_store = roots`; `builder_with_custom_ca_pem` and + `client_config_with_alpn_preserves_trust_policy` remain green. +- **ALPN adaptation preserves policy.** `client_config_with_alpn` is unchanged; + the three ALPN tests and the mTLS-preservation test remain green. +- **`tls_override` + per-hop `insecure=true` fails closed.** No code on the + outbound executor path changed; the pre-existing fail-closed tests were not + executed in this wave and are deferred to the workspace gate. +- **Insecure QUIC stays behind `insecure-quic`.** The compile-time rejection in + `compile_upstreams` is untouched and the feature was not enabled. +- **No C crypto backend.** `aws-lc-sys`, `aws-lc-rs`, `openssl-sys`, and + `native-tls` are absent from the lock; rustls resolves `ring` only. +- **MSRV/edition.** Every check ran on `rustc 1.89.0`, edition 2021, with + `unsafe_code = "deny"` unchanged. +- **No pproxy claim change.** No manifest, tier, or oracle evidence was edited. + +## 6. Failure and recovery review + +- **Root-load/parse failure does not downgrade.** A failing root set still + yields a build/handshake error; nothing in this pass added a fallback path. + The `OnceLock` caches still store only successful builds. +- **Warning idempotency and no spam.** The notice is emitted from configuration + compilation, i.e. once per load or hot reload, not per connection, packet, or + hop. Hot reload re-emits it once per reload, which matches "once before the + first handshake" for the new generation. +- **Cancellation/restart.** No lifecycle, listener-topology, or shutdown-order + code changed; the warning adds no state. +- **Malformed input.** The redaction helpers consume already-parsed + `ProxyChainSpec` values, so a malformed URI still fails in + `parse_proxy_chain` before any notice is produced. +- **Contention.** No new locks or shared mutable state were introduced; + `CompiledListenerTlsConfig` remains `Clone` with the same fields. + +## 7. Migration and compatibility review + +- No API removal or signature change. `with_system_roots` keeps its name and + behavior; only its documentation is corrected. +- No configuration schema change: `?insecure` parsing is untouched, and no TOML + key was added or removed. +- Existing `?insecure` configs continue to work but now produce one warning per + upstream at compile time. +- `eggress-config` gained a `tracing` dependency edge; this is not a published + API change and `tracing` was already a workspace dependency. +- No version bump: the workspace stays at `1.0.12`, and the four gated version + locations plus `python/pyproject.toml` are untouched. +- Rollback is a normal `Cargo.lock` revert; no schema, on-disk, or on-wire + migration exists. + +## 8. Security review + +- **Advisory exposure removed from the default graph.** The distrusted emSign + root (RUSTSEC-2026-0381) and the compromised-intermediate acceptance path + (RUSTSEC-2026-0382) are gone, together with the rustls and quinn/tokio + advisories listed for this milestone. +- **Redaction.** The compile-time notice carries only the upstream id, hop + indexes, and protocol names; a test asserts that credentials, host, and port + never appear. `CompiledListenerTlsConfig` prints presence flags and a key + length only, asserted directly and through the enclosing `ListenerConfig`. +- **No new trust surface.** The root source is unchanged and now described + accurately; there is still no OS-store backend and no automatic trust of + locally installed CAs. +- **Insecure mode remains explicit.** The feature is still required, the QUIC + gate is unchanged, and no error path substitutes an insecure verifier. +- **Denial-of-service bounds.** No parsing, buffering, or relay path changed. + +## 9. Documentation and operations + +- `architecture/transports-tls.md` — root source is "bundled Mozilla roots", + the `with_system_roots` name is described as historical, the insecure + dual-gate is qualified (compiled into shipped CLI builds, not test-only), and + the compile-time warning is documented. +- `docs/security/SECURE_CONFIGURATION.md` — upstream trust-root paragraph and + a corrected insecure-mode paragraph covering `?insecure` reachability, the + warning, and the `insecure-quic` gate. +- `docs/SECURITY_REVIEW.md` — TLS insecure-mode section rewritten; the + "Mitigations Already Implemented" entry no longer claims an OS root store or + an API-only insecure mode. +- `docs/security/THREAT_MODEL.md` — A2 mitigation states the bundled-root + behavior and CA-pinning consequence. +- `docs/URI_GRAMMAR.md` — new "Query parameters" section documenting `?rule` + and `?insecure`, plus a `?insecure` example. +- `plans/implementation/transports/004-…md` — status `ready` → `implemented`. +- `plans/subsystems/transports-roadmap.md` — M004 status recorded as + implemented / closed. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | Workspace-wide `fmt`/`clippy`/`test` gate not run in this wave | Cross-crate regressions outside the touched crates would be invisible here | Coordinator runs `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace --locked` after all waves land | +| low | `cargo test -p eggress-embed --test error_redaction` and the `eggress-cli` locked feature check could not complete | Two acceptance commands have no result for this wave | Re-run both after the parity-compat wave compiles; the failure is E0119 in `eggress-pproxy-compat`, not in this milestone's code | +| low | `eggress-outbound` `tls_override`/H2-pool suites not executed here | Plan §10 integration evidence is inherited, not re-measured | Covered by the coordinator workspace gate; no code on those paths changed | +| low | `rustix 1.1.4` RUSTSEC-2026-0486 remains (via `tempfile 3.27.0`) | `unsound` xattr advisory in a dev/test-only dependency | Track separately; outside the TLS/QUIC/tokio graph and unchanged by this pass | +| low | `russh`, `crypto-bigint`, `ctutils`, `zip` advisories remain | Optional `ssh` graph and archive path | Transports M005 and Delivery M004 respectively | + +Post-wave note (2026-11-16): the `russh`/`crypto-bigint`/`ctutils` and `zip` +findings listed above are owned by Transports M005 and Delivery M004. M005 +cleared the SSH graph, and M004 added the advisory gate with a tracked `zip` +exception and cleared the `rustix` advisory via `rustix 1.1.6`. No finding in +this table remains open for M004 scope. + +## 11. Roadmap disposition + +**Closed.** Production implementation for Transports M004 is complete and the +default TLS graph no longer carries the advisories that blocked release. The +coordinator broad gate passed on 2026-11-16, including the two commands the +in-flight parity-compat edit had blocked (`eggress-embed` `error_redaction` and +the CLI `--features full,ssh,quic,...` check). No commit, tag, or release was +created by this milestone; publication remains a separate maintainer-authorized +action. Transports M005 and Delivery M004 are unaffected. + +## 12. Registry updates + +Required, not performed here because `plans/registry.md` is owned by the wave +coordinator: + +- `plans/registry.md`: add Transports M004 to the implementation/closure index + with status `closed` and link + `plans/closure/transports/004-status.md`. +- `plans/registry.md`: record that the default-graph advisory set dropped from + 21 findings to 8 vulnerabilities (plus 3 yanked warnings and 1 `unsound` + warning), and list the remaining IDs with their owning milestones. +- `plans/subsystems/transports-roadmap.md`: apply the M004 status update + (applied in this pass for the M004 status fields only). +- `docs/ROADMAP.md`: reflect the M004 state alongside the other corrective + waves once the coordinator reconciles all of them. diff --git a/plans/closure/transports/005-status.md b/plans/closure/transports/005-status.md new file mode 100644 index 00000000..58ddbeea --- /dev/null +++ b/plans/closure/transports/005-status.md @@ -0,0 +1,334 @@ +# Transports Milestone 005 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/transports/005-russh-065-advisory-migration.md` + +Source subsystem roadmap: + +- `plans/subsystems/transports-roadmap.md` §7 Milestone 5, §12 milestone status +- `plans/subsystems/security-hardening-roadmap.md` Milestone S2 + +Repository baseline reviewed: `ba64e16` (branch `feat/auto-20261116-652bb64d`, workspace `1.0.12`) + +Implementation commits or pull requests: + +- None. This pass is uncommitted working-tree work in the shared corrective + wave; no commit, tag, or publication was created by this milestone. + +## 1. Executive finding + +The optional SSH transport now resolves `russh 0.65.2`, `crypto-bigint 0.7.11`, +and `ctutils 0.4.8`. `cargo audit` no longer reports RUSTSEC-2026-0492, +RUSTSEC-2026-0495, RUSTSEC-2026-0387 (crypto-bigint), or RUSTSEC-2026-0385 +(ctutils) for the SSH graph. + +The breaking surface was smaller than the plan anticipated. The only +compiler-required adaptation was `russh::client::Handler::check_server_key`: +the parameter became `&russh::keys::PublicKeyOrCertificate` inside the existing +async RPITIT method. Session connect, authentication, channel open, remote +forward, cancellation, and cache logic compiled unchanged, so the session/cache +model was not touched. + +The pre-0.65 crate could not even parse a certificate host key (the KEX host-key +blob was decoded with `parse_public_key`), so such a handshake failed before a +policy decision. `check_server_key` now rejects +`PublicKeyOrCertificate::Certificate(_)` with `Ok(false)` and a warning under +every policy, which preserves that fail-closed outcome rather than projecting a +certificate onto the certified plain key. + +The policy branch moved verbatim into a private `verify_host_key()` helper so it +can be unit-tested without a live session; the decision logic, logging, and +`InsecureCompatibility` scoping are otherwise unchanged. Eight policy/redaction +unit tests were added (nine with `pproxy-compat`). + +Real-server evidence is green: the crate OpenSSH suite (7 tests) and the required +embed regression with `ssh,pproxy-compat` (6 tests) both ran against a local +`sshd`, not a skip. No pproxy claim, manifest entry, public Eggress type, or +default feature set changed. + +Closure is conditional on one item only: the coordinator's workspace-wide +`fmt`/`clippy`/`test` gate after all corrective waves land. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Workspace resolves `russh >= 0.65.0` | `cargo tree -i russh -p eggress-transport-ssh` → `russh v0.65.2` | pass | 0.65.2 exactly | +| Exactly one `russh` line in the graph | `grep -c 'name = "russh"' Cargo.lock` → `1`; embed `ssh` inverse tree shows only `0.65.2` | pass | No duplicate/leftover 0.62 line | +| `crypto-bigint >= 0.7.6` | lock `crypto-bigint 0.7.11`; inverse tree: `crypto-primes`/`elliptic-curve` → `rsa`/`ecdsa` → `russh 0.65.2` | pass | Was 0.7.5 (advisory + yanked) | +| `ctutils >= 0.4.4` | lock `ctutils 0.4.8`; inverse tree under `crypto-bigint 0.7.11` | pass | Was 0.4.2 | +| Ring-only crypto; no `aws-lc-rs` | `russh` pin keeps `default-features = false, features = ["ring", "flate2", "rsa"]`; `cargo check`/`clippy` resolved no `aws-lc-*` crate | pass | `deny.toml` still bans `aws-lc-sys` | +| `check_server_key` adapted to 0.65 | `crates/eggress-transport-ssh/src/lib.rs` `check_server_key` takes `&russh::keys::PublicKeyOrCertificate` | pass | Only compiler-required change | +| Certificate host keys fail closed | `lib.rs` `Certificate(_)` arm logs and returns `Ok(false)` before any policy branch | pass | Matches pre-0.65 handshake failure | +| `KnownHosts` default still fails closed | unit test `default_known_hosts_policy_rejects_unrecorded_host`; embed test `native_toml_connector_rejects_untrusted_ssh_host_key` | pass | Unknown/unrecorded host is rejected | +| Missing/unreadable known_hosts rejects | unit test `missing_known_hosts_file_rejects_host_key`; lookup-error branch logs `known_hosts lookup failed; rejecting host key` | pass | Same `false`/`Err` path as the default-policy branch; old comment retained | +| `KnownHostsFile` accepts match, rejects mismatch | unit test `known_hosts_file_accepts_matching_key_and_rejects_mismatch` | pass | Changed key returns `Err(KeyChanged)` → `false` | +| `InsecureCompatibility` only reachable via compat cache | `SshSessionCache::new_compatibility()` stays `#[cfg(feature = "pproxy-compat")]`; unit test `compatibility_cache_constructs_the_insecure_policy` runs only with the feature | pass | `cargo test` without the feature compiles 8 tests, with it 9 | +| Session cache key scoped by policy | unit test `session_key_is_scoped_by_host_key_policy` (`HashSet` length 2) | pass | `SshSessionKey.policy` unchanged | +| Redaction preserved | unit tests `ssh_auth_debug_never_shows_secrets`, `session_key_debug_never_shows_secrets`; OpenSSH test `openssh_password_failure_is_redacted_and_reconnect_is_explicit` | pass | Debug emits `****`; errors omit password | +| Forwarded-channel accept path | OpenSSH test `openssh_remote_tcp_forward_accepts_incoming_channel` | pass | Reject path unchanged; not separately unit-tested (see §10) | +| Crate OpenSSH interop | `cargo test -p eggress-transport-ssh --features pproxy-compat --test openssh` → 7 passed | pass | Real `sshd`, not skipped | +| Required embed regression | `EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat --test ssh` → 6 passed | pass | No test adaptation needed | +| `ssh` and `ssh,pproxy-compat` compile | both `cargo check -p eggress-embed --locked --no-default-features --features …` runs | pass | | +| CLI optional-transport slice compiles | `cargo check -p eggress-cli --locked --no-default-features --features full,ssh,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins` | pass | | +| SSH graph advisories absent | `cargo audit --ignore RUSTSEC-2023-0071` | pass | -0492/-0495/-0385/-0387 gone | +| MSRV 1.89 sufficient | `rustc 1.89.0` / `cargo 1.89.0` built every checked slice | pass | No MSRV change | +| No public Eggress API change | `SshHostKeyPolicy`, `SshAuth`, `SshSessionKey`, `SshSessionCache`, `SshRemoteForward` signatures untouched; `verify_host_key` is private | pass | `docs/RUST_API.md` unchanged | +| Default feature graph unchanged | `ssh` remains opt-in on CLI/embed; no feature list edited | pass | | +| No pproxy claim change | no manifest, tier, oracle, or differential evidence touched | pass | | + +## 3. Production implementation evidence + +- **Workspace pin.** `Cargo.toml:93` moved from + `russh = { version = "0.62.6", default-features = false, features = ["ring", "flate2", "rsa"] }` + to `0.65.2` with the identical feature set. No other manifest line changed. +- **Lockfile.** `cargo update -p russh` ("Locking 11 packages to latest + compatible versions") moved: `argon2 0.6.0-rc.8 → 0.6.0`, + `blake2 0.11.0-rc.6 → 0.11.0`, `crypto-bigint 0.7.5 → 0.7.11`, + `ctutils 0.4.2 → 0.4.8`, `der 0.8.0 → 0.8.3`, `num-bigint 0.4.8 → 0.5.1`, + `pkcs1 0.8.0-rc.4 → 0.8.0`, `rsa 0.10.0-rc.18 → 0.10.0`, + `russh 0.62.6 → 0.65.2`, `spki 0.8.0 → 0.8.1`, + `ssh-key 0.7.0-rc.11 → 0.7.0-rc.12`, and removed + `internal-russh-num-bigint 0.5.0`. No version requirement was edited elsewhere; + the workspace stays at `1.0.12`. +- **Adapter.** `crates/eggress-transport-ssh/src/lib.rs`: + - `check_server_key` signature/parameter migrated; `PublicKeyOrCertificate::Certificate` + is rejected with a warning before the policy decision. + - the three-way policy branch moved unchanged into private + `verify_host_key(host, port, policy, &PublicKey) -> bool`, with the same + `tracing::warn!` calls for a failed lookup and the same + `InsecureCompatibility => true` arm. + - `server_channel_open_forwarded_tcpip`, `connect_stream`, + `authenticate_password`, `authenticate_publickey`, + `channel_open_direct_tcpip`, `channel_open_direct_streamlocal`, + `tcpip_forward`, `cancel_tcpip_forward`, `keepalive_*`, and the whole cache + required no change. +- **Tests.** A `#[cfg(test)] mod tests` was added to the same file with eight + tests (nine with `pproxy-compat`): `SshAuth`/`SshSessionKey` redaction, + policy-scoped cache key, known_hosts match/mismatch/absent, + default-policy rejection, insecure acceptance, cache policy accessors, and the + feature-gated compatibility constructor. Test host keys are public-key vectors + only. +- **Not implemented (deliberately).** No certificate host-key support, no new + auth method, no agent forwarding, no SFTP/remote command, no listener role, + no change to cache bounds, hop-zero reuse rules, or `local_bind` handling. +- **Embed test.** `crates/eggress-embed/tests/ssh.rs` needed no adaptation and + is unmodified. + +## 4. Verification executed + +### Commands run + +| Command | Result | +|---|---| +| `cargo update -p russh` | pass — "Locking 11 packages to latest compatible versions"; the 12 moves/removal in §3 | +| `cargo update -p crypto-bigint -p ctutils` | pass — "Locking 0 packages to latest compatible versions" (already at `0.7.11` / `0.4.8` from the `russh` update) | +| `cargo tree -i russh -p eggress-transport-ssh` | pass — `russh v0.65.2` → `eggress-transport-ssh` | +| `cargo tree -i russh -p eggress-embed --no-default-features --features ssh` | pass — single `russh v0.65.2` under the embed/outbound/runtime/server chain | +| `cargo tree -i crypto-bigint -p eggress-transport-ssh` | pass — `crypto-bigint v0.7.11` | +| `cargo tree -i ctutils -p eggress-transport-ssh` | pass — `ctutils v0.4.8` | +| `cargo test -p eggress-transport-ssh` | pass — 8 lib tests passed, 0 failed; `tests/openssh.rs` 0 tests (feature-gated file), 0 doc-tests | +| `cargo test -p eggress-transport-ssh --features pproxy-compat --lib` | pass — 9 passed, 0 failed | +| `cargo test -p eggress-transport-ssh --features pproxy-compat --test openssh -- --nocapture` | pass — 7 passed, 0 failed | +| `EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat --test ssh -- --nocapture` | pass — 6 passed, 0 failed | +| `cargo check -p eggress-embed --locked --no-default-features --features ssh` | pass | +| `cargo check -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat` | pass | +| `cargo check -p eggress-cli --locked --no-default-features --features full,ssh,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins` | pass | +| `cargo clippy -p eggress-transport-ssh -p eggress-embed --all-targets -- -D warnings` | pass — finished with no warnings | +| `cargo fmt -p eggress-transport-ssh -p eggress-embed -- --check` | pass — clean | +| `cargo audit --ignore RUSTSEC-2023-0071` | partial by design — 4 vulnerabilities remain, all `zip`; 2 warnings (`rustix` unsound, `wnaf` yanked) | +| `cargo deny check advisories` | `advisories ok` — but its debug trace filters `russh 0.65.2` and the `eggup`/`zip` subtree out of the graph (200 crates filtered), so it is not evidence for this milestone | + +OpenSSH availability: `command -v sshd` → `/usr/sbin/sshd`, +`command -v ssh-keygen` → `/usr/bin/ssh-keygen`; both suites ran against a +fixture `sshd` and did not skip for missing tools. Two environment gates are +pre-existing and unchanged: the transport password-success test prints +`skipping SSH password-auth success test: EGRESS_SSH_TEST_PASSWORD is unset` +(public-key and password-failure coverage still ran), and nothing in this +milestone added a skip. + +The brief's literal command `cargo test -p eggress-transport-ssh --test openssh` +was also run without the feature and reports `running 0 tests`, because +`tests/openssh.rs` is `#![cfg(feature = "pproxy-compat")]`. The feature-enabled +run above is the one that executes the suite. + +`cargo audit` headings absent compared with the pre-migration baseline: +RUSTSEC-2026-0385 (`ctutils`), RUSTSEC-2026-0387 (`crypto-bigint`), +RUSTSEC-2026-0492 and RUSTSEC-2026-0495 (`russh`). The `crypto-bigint` and +`der` yanked warnings also disappeared. + +Remaining `cargo audit` findings: + +| Crate | Advisory | Owner | +|---|---|---| +| `zip 6.0.0` | RUSTSEC-2026-0429 | Delivery M004 | +| `zip 6.0.0` | RUSTSEC-2026-0367 | Delivery M004 | +| `zip 6.0.0` | RUSTSEC-2026-0368 | Delivery M004 | +| `zip 6.0.0` | RUSTSEC-2026-0369 | Delivery M004 | +| `rustix 1.1.4` | RUSTSEC-2026-0486 (`unsound` warning, not a vulnerability) | Pre-existing via `tempfile`; unchanged here | +| `wnaf 0.14.0` | yanked (warning only) | Pre-existing; not on the SSH path | + +**Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — +`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace --locked`, the documented CLI/embed feature slices, the +embed OpenSSH regression (6/6), and `cargo deny --workspace check` +(advisories/bans/licenses/sources). `cargo audit --ignore RUSTSEC-2023-0071` +reports only the four tracked `zip 6.0.0` advisories. The condition recorded in +§11 is therefore satisfied. + +## 5. Invariant review + +- **Verified host keys by default.** `SshSessionCache::new()` still selects + `KnownHosts`; `verify_host_key` still calls + `russh::keys::check_known_hosts`. The embed test + `native_toml_connector_rejects_untrusted_ssh_host_key` proves a TOML chain + fails against a fixture host key absent from known_hosts. +- **Missing/unreadable file rejects.** The `Err` branch logs + `known_hosts lookup failed; rejecting host key` and returns `false`; nothing + maps an error to acceptance. `missing_known_hosts_file_rejects_host_key` + asserts the absent-file case, which reaches the same branch through + `check_known_hosts_path`. +- **Insecure compatibility stays scoped.** `InsecureCompatibility` is still + constructed only by `SshSessionCache::new_compatibility()` under + `pproxy-compat`, still emits the per-connection warning in + `get_or_connect`/`connect_fresh`, and `SshSessionKey.policy` still separates + the two caches (unit-tested). +- **No credential leak.** `SshAuth::Debug` and `SshSessionKey::Debug` are + untouched and unit-tested (`****`, no secret substring). Errors still use + static strings: `AuthenticationFailed`, + `PrivateKey("could not load configured private key")`, and + `Connection(error.to_string())` from `russh`, which does not echo the + password or key path. +- **Restricted forwarding surface.** No new channel type, listener role, auth + method, remote command, SFTP, or agent forwarding was added. The crate still + exposes only direct TCP, remote Unix-socket, and explicitly requested remote + TCP forwarding. +- **Cache bounds and lifecycle.** `Arc>>` with the same + hop-zero rules, `shutdown()` clear, and `invalidate()` eviction are unchanged. +- **No new SSH listener or auth mechanism.** +- **No pproxy claim change.** No manifest tier, oracle, or differential + evidence was touched. + +## 6. Failure and recovery review + +- **Host-key rejection fails the connection.** `Ok(false)` from + `check_server_key` makes `russh` return `Error::UnknownKey`; there is no + fallback to `InsecureCompatibility` and no retry with relaxed policy. +- **Certificate host keys fail closed.** Rejected in the handler before the + policy branch under every policy, matching the pre-0.65 parse failure. +- **Cache isolation.** Lookups are keyed by host/port/username/auth/hop/policy; + a live session created under one policy cannot satisfy a request under + another. A closed handle is removed before reconnect. +- **Cancellation.** Authentication and channel-open paths are unchanged; a + dropped future still drops the handle before cache insertion, so no partial + entry remains. +- **Concurrency.** Cache access remains mutex-protected; the remote-forward + receiver keeps depth 128 and no lock is held across an await. +- **Shutdown.** `shutdown()` still clears every cached handle; the OpenSSH + reconnect-after-shutdown assertions remain green. +- **Malformed input.** Empty Unix socket path and target port `0` guards are + unchanged, as is the non-loopback remote-forward warning. + +## 7. Migration and compatibility review + +- **Breaking dependency change is contained.** The only public-facing effect is + the dependency version; `russh` types still do not appear in Eggress's public + API, so no `docs/RUST_API.md` edit was required. +- **No config/schema change.** TOML and pproxy URI translation are untouched. +- **Feature graph unchanged.** `ssh` remains an opt-in feature on + `eggress-cli`/`eggress-embed`/`eggress-runtime`; the default CLI, embed, and + Python graphs do not include `russh`. +- **Observable behavior delta.** A server that presents an SSH host certificate + previously failed the handshake in KEX; it now fails host-key verification + with a clearer warning. The result (connection refused) is identical. +- **Rollback.** Reverting the pin and `Cargo.lock` restores 0.62.6; the adapter + would need the old `&PublicKey` parameter. There is no on-disk or on-wire + migration. +- **Test contract.** The OpenSSH suites still gate on the `pproxy-compat` + feature and on OpenSSH tool availability, unchanged. + +## 8. Security review + +- **Advisories closed.** RUSTSEC-2026-0492 (client handler callbacks for + unopened channels, CVSS 7.5), RUSTSEC-2026-0495 (agent signing without + `confirm`), RUSTSEC-2026-0387 (`crypto-bigint` timing variability), and + RUSTSEC-2026-0385 (`ctutils` non-constant-time masks) are no longer reported. + The two `russh` advisories are reachable in principle even though this + crate exposes no agent surface; the migration removes them rather than + relying on reachability reasoning. +- **Host-key trust boundary.** `KnownHosts`/`KnownHostsFile` remain + fail-closed; only the explicitly constructed compatibility cache accepts any + key. Certificate host keys are refused instead of being downgraded to their + certified plain key, which prevents a certificate from satisfying a + known_hosts entry that was never recorded for it. +- **Redaction.** Password and private-key path never appear in `Debug`; the new + certificate warning logs only host and port. +- **Supply chain.** The `ring` feature set is retained and `aws-lc-rs` remains + disabled and banned by `deny.toml`; no C toolchain dependency was added. +- **Denial-of-service bounds.** No parsing, buffering, channel-depth, or relay + path changed. + +## 9. Documentation and operations + +- `architecture/transports-ssh-quic-h3.md` — module-map line count, public API + line references, host-key flow (`verify_host_key` + certificate rejection), + the pinned `russh` line, and the review entry-point commands updated. +- `docs/SECURITY_REVIEW.md` — mitigation 13 now records the pinned `russh` + 0.65.x line, the fixed advisories, fail-closed known_hosts lookup, and + certificate host-key rejection. +- `plans/implementation/transports/005-russh-065-advisory-migration.md` — + status `ready` → `implemented`. +- `plans/subsystems/transports-roadmap.md` — M005 status fields and status-table + row updated; M004 rows untouched. +- No operator command, CLI flag, config key, exit code, or diagnostic format + changed; no recovery instruction changed. +- No release, tag, publication, or version bump was performed. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | Workspace-wide `fmt`/`clippy`/`test` gate not run in this wave | Cross-crate regressions outside the owned crates would be invisible here | Coordinator runs `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace --locked` after all waves land | +| low | `zip 6.0.0` advisories (RUSTSEC-2026-0429/-0367/-0368/-0369) remain | Optional updater path only; not an SSH dependency | Delivery M004 / upstream `eggup-archive` with `zip >= 9.0.0` | +| low | Forwarded-channel reject branch (no registered forward, or full queue) has no dedicated test | A regression there would only be caught by inspection, not by a test | The accept path is covered by `openssh_remote_tcp_forward_accepts_incoming_channel`; a reject test would need a live session that requests a forward the client never registered | +| low | `cargo deny check advisories` reports ok while filtering the optional `ssh` graph (and `eggup`/`zip`) out of its feature resolution | A CI gate built only on this command would miss optional-feature advisories | Delivery M004 owns the advisory gate; the gate should account for optional features or run against `--all-features`-equivalent scope | +| low | `rustix 1.1.4` RUSTSEC-2026-0486 (`unsound`) and `wnaf 0.14.0` yanked warnings remain | Warning-only, outside the SSH path | Track separately; unchanged by this pass | +| low | Transport password-success test stays skipped without `EGRESS_SSH_TEST_PASSWORD` | One auth mode is not exercised by default | Pre-existing environment gate; public-key auth and password-failure coverage ran | + +Post-wave note (2026-11-16): the `rustix` advisory was cleared by the `rustix +1.1.6` update in Delivery M004, and the `cargo deny` graph-scope finding was +fixed by the `cargo deny --workspace check` gate in M004. The four `zip` +advisories remain tracked there. + +## 11. Roadmap disposition + +**Closed.** Production implementation for Transports M005 is complete: the +optional SSH transport is on the fixed `russh` line, its policy and cache +invariants are intact, and real-`sshd` regressions are green. The coordinator +broad gate, including the embed OpenSSH regression, passed on 2026-11-16. No +commit, tag, or release was created; publication remains a separate +maintainer-authorized action. + +## 12. Registry updates + +Required, not performed here because `plans/registry.md` and `docs/ROADMAP.md` +are owned by the wave coordinator: + +- `plans/registry.md`: move Transports M005 from `ready` to + `closed`, link + `plans/closure/transports/005-status.md`, and drop the "`russh 0.65.x` API + migration" blocker note. +- `plans/registry.md`: narrow the security-corrective gate note — S2 is + implemented; S5 still owns the `zip` exception, and the note should record + that `cargo deny check advisories` resolves a feature-filtered graph that + omits the optional `ssh` line. +- `plans/registry.md`: the residual-advisory entry can be reduced to the four + `zip` IDs plus the `rustix`/`wnaf` warnings; the four SSH-graph IDs are gone. +- `plans/subsystems/transports-roadmap.md`: M005 status fields applied in this + pass; the roadmap header still reads "M004/M005 security correctives ready" + and should be reconciled with the coordinator's final state. +- `docs/ROADMAP.md`: reflect the M005 state alongside the other corrective + waves once the coordinator reconciles all of them. diff --git a/plans/implementation/README.md b/plans/implementation/README.md index 7b81862d..e808b54a 100644 --- a/plans/implementation/README.md +++ b/plans/implementation/README.md @@ -4,7 +4,16 @@ This directory contains bounded plans handed directly to implementation agents. Implementation plans are operational documents tied to the current repository state. They may be corrected, superseded, or archived without modifying the canonical long-term documents. -There is currently no active implementation plan. New plans are registered in `plans/registry.md` and `docs/ROADMAP.md` before handoff. +Active plans are registered in `plans/registry.md` and `docs/ROADMAP.md` before handoff. The 2026-11-16 security-corrective set was implemented and closed on 2026-11-16: + +- `transports/004-tls-trust-and-dependency-advisory-remediation.md` (`plans/closure/transports/004-status.md`) +- `transports/005-russh-065-advisory-migration.md` (`plans/closure/transports/005-status.md`) +- `protocols-edge/003-socks4-auth-and-udp-private-egress.md` (`plans/closure/protocols-edge/003-status.md`) +- `routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` (`plans/closure/routing-health-observability/003-status.md`) +- `delivery/004-updater-trust-and-advisory-gate.md` (`plans/closure/delivery/004-status.md`) +- `parity-compat/003-auth-reuse-and-compat-redaction.md` (`plans/closure/parity-compat/003-status.md`) + +The previously registered `transports/003-downstream-safe-bounded-websocket-composition-api.md` remains ready; Delivery M003 is closed. ## Layout and naming diff --git a/plans/implementation/delivery/004-updater-trust-and-advisory-gate.md b/plans/implementation/delivery/004-updater-trust-and-advisory-gate.md new file mode 100644 index 00000000..53c47ac8 --- /dev/null +++ b/plans/implementation/delivery/004-updater-trust-and-advisory-gate.md @@ -0,0 +1,357 @@ +# Delivery M004 — Updater Trust, Advisory Gate, and Credential-Output Hardening + +Status: implemented (2026-11-16; the four `zip 6.0.0` advisories remain tracked as a narrow, commented `deny.toml` exception pending an upstream `eggup-archive` release with `zip >= 9.0.0`) + +Repository baseline: `feat/auto-20261116-652bb64d` at `ba64e16` (workspace 1.0.12) + +Source roadmaps: + +- `plans/subsystems/delivery-roadmap.md` (new milestone M004) +- `plans/subsystems/security-hardening-roadmap.md` (S5) + +Long-term requirements: + +- `plans/000-long-term-specification.md` §2 (goal 7), §4 (invariants 3, 10) +- `plans/001-terminology-and-domain-model.md` §2 (deployment forms) +- `plans/002-long-term-roadmap.md` (release/distribution maintenance) + +Applicable ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +Primary class: invariant / infrastructure + +## 1. Objective + +Harden the standalone updater and delivery/verification surfaces: + +1. Remove production access to the updater’s `file://`/`EGRESS_UPDATE_BASE_URL` + test hook. +2. Stop trusting `PATH` for integrity-critical tools (`curl`, `sha256sum`, + `shasum`) and use a private, non-predictable staging directory. +3. Redact `egress system-proxy inspect --json` raw settings. +4. Add an advisory gate to CI and release preflight, with a narrow tracked + exception for the upstream-blocked `zip 6.0.0` dependency. + +This milestone does not change release discovery, target naming, checksum +policy, staged-version verification, or the no-sudo/no-elevation policy. + +## 2. Why this milestone is ready + +- `tempfile 3.27` is already in the workspace dependency graph; promoting it to + a regular `eggress-cli` dependency is small and MSRV-compatible. +- `sha2 0.10` is already used by protocol crates; adding it to `eggress-cli` + removes the `sha256sum`/`shasum` PATH dependency. +- `cargo update --dry-run` resolves the default TLS/QUIC/tokio advisories + (Transports M004); `russh` is handled by Transports M005. +- `eggup-archive 0.1.2` and `0.2.0` both pin `zip = "6.0.0"`; RUSTSEC-2026-0367, + -0368, -0369, and -0429 cannot be removed by a lockfile update alone. Eggup’s + bounded extractor rejects symlinks, non-files, `enclosed_name() == None`, and + `..`/absolute paths, and does not call `ZipArchive::extract`, so the interim + risk is lower — but it must be tracked, not hidden. +- The existing updater already verifies the whole archive and staged versions; + this milestone hardens the trust path without changing that contract. + +## 3. Current implementation evidence + +### Updater trust + +- `EGRESS_UPDATE_BASE_URL` is read unconditionally in release code + (`crates/eggress-cli/src/update/mod.rs:101-103`). +- `file://` URLs are accepted by `curl_fetch_text`/`curl_download` + (`crates/eggress-cli/src/update/download.rs:63-84`); only non-HTTPS, + non-file URLs are rejected. +- `find_curl` scans `PATH` (`download.rs:41-53`). +- `compute_sha256` runs `sha256sum` or `shasum` from `PATH` + (`crates/eggress-cli/src/update/verify.rs:31-55`). +- `staging_dir` is `/tmp/eggress-update-` with + `remove_dir_all` + `create_dir_all` (`update/mod.rs:268-273`); `curl -o` + writes into it and follows symlinks. +- The archive is verified at `update/mod.rs:175-176` and extracted afterward at + `:178-190`; a writable staging directory creates a swap window. + +### Credential-output + +- `InspectionResult` serializes both `settings` (raw) and `redacted_settings` + (`crates/eggress-system-proxy/src/inspection.rs:51-60`). +- `egress system-proxy inspect --json` serializes the whole result + (`crates/eggress-cli/src/commands/system_proxy.rs:10-13`). +- `settings` values can contain `http://user:pass@...` from OS/env settings. + +### Advisory gate + +- `cargo audit --ignore RUSTSEC-2023-0071` reports 21 vulnerabilities and 5 + warnings. +- `cargo deny check` reports `advisories FAILED`, while `bans`, `licenses`, and + `sources` pass; `deny.toml` has no ignores. +- `.github/workflows/ci.yml` and `scripts/release-preflight.sh` do not run + either tool. + +## 4. Invariants that must not regress + +- Release discovery remains latest-stable-only; no prerelease/floating branch. +- The SHA-256 sidecar remains the integrity gate; a mismatch leaves the current + installation untouched. +- Both staged executables are executed and must match the release tag exactly + and agree with one another before replacement. +- The updater never invokes `sudo`, never mutates shell/PATH state, and never + falls back to Cargo/source builds. +- A failed update leaves the installed pair untouched. +- The `egress`/`pproxy` pair is replaced as one unit; no split update. +- No new runtime HTTP client dependency; no shell evaluation of downloaded data. +- No release/tag is created by this milestone. + +## 5. Scope + +### In scope + +- `eggress-cli` updater feature gate, tool discovery, hash implementation, + staging, and tests. +- `eggress-system-proxy`/`eggress-cli` JSON redaction. +- `deny.toml`, CI workflow, release preflight, and advisory documentation. +- Moving the direct `zip` dependency to `[dev-dependencies]` if it is used only + by tests (verify before changing). +- Tracking the upstream `eggup-archive`/`zip` blocker in the registry. + +### Explicitly out of scope + +- Implementing the upstream Eggup `zip >= 9` release. +- Changing release discovery, asset naming, version validation, or exit codes. +- Adding a signature/provenance system beyond the existing checksum. +- Admin TLS or protocol/runtime changes. +- Publishing a release. + +## 6. Required production changes + +### A. Gate the updater test hook + +Add a non-default `update-fixtures` feature to `eggress-cli` (or an equivalent +`#[cfg(any(test, feature = "update-fixtures"))]` gate) and compile +`EGRESS_UPDATE_BASE_URL` plus `file://` acceptance only under it. + +Release default behavior: + +- ignore `EGRESS_UPDATE_BASE_URL`; +- reject `file://` (and every non-HTTPS scheme); +- keep the existing HTTPS `--proto =https --tlsv1.2` constraints. + +Update in-module updater tests to use the feature/cfg; add a negative test that +the default release behavior rejects a `file://` base URL and ignores the env +override. + +### B. Remove PATH trust from integrity-critical operations + +1. **Hashing:** add `sha2 = "0.10"` and compute SHA-256 in-process. Delete the + `sha256sum`/`shasum` discovery and parsing path; if an OS tool is retained for + diagnostics, it must not be the verification authority. +2. **curl:** prefer fixed absolute locations: + - Unix: `/usr/bin/curl`, then `/bin/curl`; + - Windows: `%SystemRoot%\System32\curl.exe`; + - do not scan arbitrary `PATH` entries. If no trusted location exists, fail + with an actionable error. A test-only override may be compiled under the + `update-fixtures` feature, never in release builds. +3. Verify the selected executable is a regular file and not writable by + group/other where the platform exposes that metadata. Do not follow a + symlinked tool path. + +### C. Replace predictable staging + +Use `tempfile::Builder` (or equivalent): + +- a private directory with `0700` permissions, created atomically; +- archive/checksum files created with `create_new`, not overwrite; +- no symlink following for output paths; +- ensure the directory is on the same filesystem/installation path where the + transaction requires atomic replacement; +- hold the archive open or re-hash it immediately before extraction to close the + verify/extract swap window; +- keep cleanup best-effort and never remove an unrelated path. + +Add tests for: pre-existing symlink at the archive path, private directory mode, +concurrent staging attempts, and hash mismatch after a post-verification +replace (should fail closed). + +### D. Redact `system-proxy inspect --json` + +Make `InspectionResult` serialize redacted settings only: + +- mark raw `settings` `#[serde(skip_serializing)]` (or implement a custom + `Serialize`); +- ensure `redacted_settings` is always populated when `settings` is present; +- keep `settings` available for in-process callers that need raw values; +- add CLI tests asserting credentials never appear in `--json`. + +This is a public JSON behavior change; document it in the command help and +release notes. + +### E. Add the advisory gate + +1. Add a CI job (or step) that installs a pinned `cargo-deny` and runs + `cargo deny check` (advisories/bans/licenses/sources). Prefer a pinned action + SHA or `cargo install --locked` consistent with the repository’s supply-chain + posture. +2. Add the same check to `scripts/release-preflight.sh` or the release workflow + preflight job so a tag cannot ship with an unreviewed advisory. +3. Add a narrow `deny.toml` ignore list only for the currently upstream-blocked + `zip` IDs, with comments naming the Eggup dependency, the reason the + vulnerable `extract()` APIs are not used, and the removal condition. Do not + ignore TLS/SSH/QUIC advisories that this program fixes. +4. Record the `zip` blocker in `plans/registry.md` blocked work. + +If the gate lands before Transports M004/M005 close, use temporary ignores for +those IDs only with a dated removal condition; prefer landing after S1/S2. + +### F. `zip` direct dependency hygiene + +Verify `crates/eggress-cli/Cargo.toml:92` is used only by +`#[cfg(test)]` code (`update/eggup.rs` test helpers). If so, move `zip` to +`[dev-dependencies]` and test with `zip 9.x` where the test API permits. This +does not remove the transitive `zip 6.0.0` from `eggup-archive`; it only keeps +the production CLI graph honest. + +## 7. Ordered work packages + +### Work package A — Updater source and tool trust + +Intent: release builds cannot be redirected or tricked by PATH. + +Acceptance evidence: env/file rejection tests; absolute tool resolution; no +`sha256sum` authority; docs. + +### Work package B — Private staging and TOCTOU + +Intent: no local user can swap the archive or symlink the output. + +Acceptance evidence: private mode, create-new, symlink, and re-hash tests. + +### Work package C — JSON redaction + +Intent: `system-proxy inspect --json` never prints credentials. + +Acceptance evidence: CLI/unit tests for env/system settings with userinfo. + +### Work package D — Advisory gate and zip exception + +Intent: advisories are visible in CI/release, with a tracked exception. + +Acceptance evidence: gate run output; `deny.toml` comments; registry blocker; +no unreviewed ignores. + +## 8. Failure, cancellation, restart, and contention semantics + +- A missing trusted curl/hash tool fails before download/mutation. +- A checksum mismatch, extraction failure, or candidate-version failure leaves + the installed pair untouched. +- Concurrent updater invocations must not share a staging path; create-new and + private directory semantics make the loser fail cleanly. +- A cancellation/kill during download leaves only a private temp directory; it + must not remove or mutate the installed pair. +- The advisory gate is read-only and does not modify the lockfile. + +## 9. Compatibility and migration + +- Release builds no longer honor `EGRESS_UPDATE_BASE_URL`/`file://`; fixture + tests and local workflows must enable `update-fixtures` explicitly. +- The updater’s user-visible flow (discover, download, verify, stage, execute, + replace) is unchanged. +- `system-proxy inspect --json` output changes: raw `settings` is omitted/redacted; + `redacted_settings` remains. This is a security fix and must be documented. +- No pproxy compatibility claim change. +- No version bump/tag. + +## 10. Required tests + +### Focused unit tests + +- `update_fixtures_are_required_for_file_urls` / release rejection. +- `find_curl` prefers absolute paths; rejects a PATH-only fake. +- in-process SHA-256 matches known vectors and the sidecar. +- staging directory is private, create-new, and refuses a pre-existing symlink. +- post-verification archive replacement fails closed. +- `InspectionResult` JSON omits raw credentials. + +### Integration tests + +- Existing updater fixture flow with `update-fixtures`. +- Existing `eggress`/`pproxy` updater tests. +- CLI `system-proxy inspect --json` with credential-bearing env/system proxy. + +### Security and negative tests + +- `EGRESS_UPDATE_BASE_URL=file:///tmp/evil` is ignored in release/default. +- A symlinked archive/checksum path is rejected or safely replaced. +- A fake `sha256sum` on PATH cannot influence verification. +- JSON contains no `user:pass@`. + +## 11. Required verification commands + +```bash +cargo test -p eggress-cli update +cargo test -p eggress-cli --features update-fixtures update +cargo test -p eggress-system-proxy +cargo test -p eggress-cli --test cli_exit_codes +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +cargo audit --ignore RUSTSEC-2023-0071 +cargo deny check +``` + +`cargo deny check` may fail on `russh` until Transports M005 and on `zip` until +the tracked exception/upstream release; record the exact IDs and do not claim a +clean gate prematurely. + +## 12. Documentation updates + +- `docs/INSTALLATION.md` — updater test hook, trusted tool requirements, staging, + no-sudo behavior. +- `docs/cli/EXIT_CODES.md` — only if verification failure wording changes. +- `docs/security/SECURE_CONFIGURATION.md` / `docs/SECURITY_REVIEW.md` — + updater trust boundary and advisory gate. +- `deny.toml` comments and registry blocked-work entry for `zip`. +- CI/release process docs (`docs/CI_STATUS.md`, `docs/release/RELEASE_PROCESS.md`) + after the gate lands. + +## 13. Acceptance criteria + +- Default/release builds ignore `EGRESS_UPDATE_BASE_URL` and reject `file://`. +- No integrity decision depends on a PATH-resolved `sha256sum`/`shasum`. +- `curl` resolves from a fixed trusted location or fails closed. +- Staging is private, create-new, and symlink-safe; post-verification replacement + fails closed. +- `system-proxy inspect --json` contains no credentials. +- CI/release preflight runs an advisory gate; any `zip` exception is explicit, + commented, and tracked in the registry. +- Existing updater contract and release policy are unchanged. + +## 14. Stop conditions + +Stop and report if: + +- absolute curl locations are unavailable on a supported target; +- moving `zip` to dev-dependencies changes a public crate feature/dependency; +- the JSON redaction breaks a documented consumer contract that requires raw + settings (add an explicit unsafe accessor instead of silently leaking); +- the advisory gate cannot run without network/action-install permission; +- the `zip` exception is not approved by the maintainer; +- the change would require a release/tag. + +## 15. Closure evidence required + +- Updater negative tests for env/file/PATH/symlink/TOCTOU. +- In-process SHA-256 vector test and updater fixture transcript. +- `system-proxy --json` redaction test. +- CI/release gate run output and `deny.toml` diff. +- Registry blocked-work entry for `zip` with the upstream dependency and + removal condition. +- Explicit statement that no release/tag was created. + +## 16. Handoff notes + +- Do not add a new HTTP client dependency; use trusted curl or an existing + workspace mechanism. +- Keep the update transaction’s existing Eggup staging/rollback authority; this + plan hardens inputs, not the install transaction. +- The test hook is used by in-module tests; prefer `cfg(test)` plus a + non-default feature so external fixture tests remain possible. +- Use `OpenOptions::create_new` rather than truncate; do not follow symlinks. diff --git a/plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md b/plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md new file mode 100644 index 00000000..f9148d74 --- /dev/null +++ b/plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md @@ -0,0 +1,343 @@ +# Parity Compat M003 — Auth Reuse Semantics and Compatibility Redaction + +Status: implemented + +Repository baseline: `feat/auto-20261116-652bb64d` at `ba64e16` (workspace 1.0.12) + +Source roadmaps: + +- `plans/subsystems/parity-compat-roadmap.md` (new milestone M003) +- `plans/subsystems/security-hardening-roadmap.md` (S6) + +Long-term requirements: + +- `plans/000-long-term-specification.md` §4 (invariant 3, 9), §5 (compat contract) +- `plans/001-terminology-and-domain-model.md` §3–§4 (tier vs status, manifest authority) +- `plans/002-long-term-roadmap.md` (Phases 7–8, 36–42) + +Applicable ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +Primary class: invariant / polish + +## 1. Objective + +Make the pproxy-compatible source-IP authentication reuse contract truthful and +visible, and close compatibility-surface credential leaks: + +1. Correct the security/migration documentation: credentials come from the URI + fragment; `--auth` is the re-authentication interval, not the credential flag. +2. Make the 30-day default and the process-global, IP-keyed cache explicit at + startup and in the docs. +3. Redact raw UDP remote URIs in compatibility errors and raw argv in + `pproxy translate --annotate`. +4. Redact compatibility IR `auth_password` in `Debug`. + +No compatibility tier changes are intended. If a change alters a manifest claim, +the manifest plus oracle/differential/interop gate applies. + +## 2. Why this milestone is ready + +- The pinned pproxy 2.7.9 oracle uses a class-level `AuthTable._auth`/`_user` + keyed only by source IP and an `authtime` default of `86400*30` + (`pproxy/server.py`). Eggress reproduces that with one + `CompatibilityRuntimeHooks::auth_reuse` cache threaded into every listener + and a 30-day `effective_auth_timeout()`. +- `docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md:9,23,67` currently says + authentication is absent unless `--auth` is used and that translation does + not add `[listeners.auth]` without `--auth`. That is false: credentials come + from the URI fragment, and `translate/intermediates.rs:264-265` adds listener + auth from that fragment. `--auth` only changes the reuse interval. +- `translate/intermediates.rs:854-862` interpolates the raw `remote_str` into + `CompatError::InvalidArgs`; the canonical redactor exists at + `crates/eggress-pproxy-compat/src/uri.rs:227-231`. +- `crates/eggress-cli/src/commands/pproxy.rs:53-55` prints raw `args.args` for + `--annotate`. +- `crates/eggress-pproxy-compat/src/translate/model.rs:159-181` derives `Debug` + for `ReverseServerToml`/`ReverseClientToml` with `auth_password` plaintext. + +## 3. Current implementation evidence + +### Auth reuse + +- `PproxyArgs::effective_auth_timeout()` returns `Duration::from_secs(86_400 * 30)` + when `--auth` is omitted (`crates/eggress-pproxy-compat/src/args.rs:550-553`). +- `pproxy_exec` passes that value unconditionally to `from_facade` + (`crates/eggress-cli/src/pproxy_exec.rs:254-257`). +- `from_facade` creates one cache (`crates/eggress-runtime/src/supervisor.rs:138-150`); + `prepare_listener_set` passes the same `Arc` to every listener + (`supervisor.rs:482-487`), and `cached_identity` looks up only by IP + (`crates/eggress-server/src/accept/mod.rs:212-218`). +- The pproxy oracle has the same global IP cache and 30-day default, so this is + compatibility behavior, not a divergence. The security problem is that the + docs understate it, and an operator can believe `--auth` is what enables + authentication. + +### Redaction + +- `redact_uri_for_error` strips userinfo and bounds input + (`uri.rs:227-231`) but the UDP remote error path does not use it. +- `PproxyUri` has a redacting `Debug` and `redacted_display` + (`uri.rs:59-130,703-707`); the raw `remote_str` path bypasses both. +- `--annotate` uses `args.args.join(" ")`; a `-l socks5://user:pass@...` command + line is reproduced verbatim. +- `ReverseServerToml`/`ReverseClientToml` are internal serialization structs; + no current production log path prints them, but `Debug` is a latent leak. + +## 4. Invariants that must not regress + +- pproxy 2.7.9 behavior remains the default; no tier change without manifest + + oracle/differential/interop evidence. +- `PproxyUri::redacted_display`, `RedactedUri`, and `CredentialSpec` redaction + remain the canonical output paths. +- Compatibility diagnostics remain structured and machine-readable. +- `translate` still emits usable TOML (it contains the real credentials needed + to run); only annotations/errors are redacted. +- `--annotate` remains useful for reproduction, with credentials replaced by a + clear placeholder. +- No new auth flag or credential store is introduced. + +## 5. Scope + +### In scope + +- `docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md`, + `docs/PPROXY_MIGRATION.md`, `docs/cli/PPROXY_CLI_INVENTORY.md`, and related + security wording. +- A startup warning in the pproxy compatibility path describing the 30-day + global IP reuse and `--auth 0`/native-auth alternatives. +- `intermediates.rs` error redaction. +- `pproxy translate --annotate` argv redaction. +- Compat IR `Debug` redaction. +- Focused Rust/Python redaction tests and manifest validation. + +### Explicitly out of scope + +- Changing the pproxy auth-reuse default or cache scope; that would be a + compatibility change. +- Adding a new `--no-auth-reuse` flag or native auth-cache config. +- Manifest tier changes unless the evidence shows one is required. +- SOCKS4 credential enforcement (Protocols Edge M003; coordinate the shared-cache + test). +- Updater/CI changes (Delivery M004). + +## 6. Required production changes + +### A. Correct the `--auth` contract in docs + +Rewrite the security-differences section to state: + +- credentials are carried by the listener URI fragment (`#user:pass`), not by + `--auth`; +- `--auth N` sets the source-IP re-authentication interval; the pproxy default + is `2592000` seconds (30 days), including when the flag is omitted; +- the cache is process-local, bounded, monotonic-expiry, and keyed only by + source IP, so it is shared across compatibility listeners with credentials; +- `--auth 0` disables practical reuse; use native `[listeners.auth]` (no reuse + cache) or a trusted single-user environment for stricter behavior. + +Correct `PPROXY_MIGRATION.md` and `CLI_INVENTORY` to match. Do not claim that +translation omits `[listeners.auth]` without `--auth`. + +### B. Add a startup warning + +When the compatibility facade has listener credentials and an auth-reuse cache +(which is the normal pproxy-compatible path), emit one warning that names the +30-day default, the source-IP-only scope, and the cross-listener cache. Redact +credentials and listener URIs. + +Do not warn when there are no credentialed listeners, and do not emit it once +per connection. + +### C. Redact compatibility errors + +In `translate/intermediates.rs`, replace raw `remote_str` interpolation with +the canonical `redact_uri_for_error(remote_str)` (or +`egress_uri::redact_proxy_uri`) for both “invalid UDP remote URI” paths. Ensure +the error still preserves the reason and enough endpoint context to debug. + +Add tests with: + +- `socks5://user:pass@127.0.0.1:1080` malformed / no-hop cases; +- passwords containing `@` and brackets; +- a `file://` or non-URI input that still gets bounded/redacted. + +### D. Redact `translate --annotate` + +Add a small argv redaction helper: + +- iterate arguments, preserving flags and non-URI values; +- for URI-shaped tokens, call `redact_proxy_uri`/`PproxyUri::redacted_display`; +- replace `userinfo` with `****:****@` (or `****@` when only a username is + present); +- preserve the chain separator and query string. + +Use it for the `# pproxy arguments:` annotation. Keep the generated TOML +unchanged (it must still be runnable). Add a CLI test with `--annotate` and a +credentialed `-l`/`-r` pair. + +### E. Redact compat IR Debug + +Replace the derived `Debug` for `ReverseServerToml`/`ReverseClientToml` with +custom implementations that print `auth_password: ****` (or `Some(****)`) and +keep other fields. Add a unit test asserting the password string does not appear +in `format!("{:?}", ...)`. + +### F. Manifest/tier check + +Check whether `cli.auth` or any SOCKS4/auth claim changes. Documentation and +redaction-only changes should not. If a warning/behavior change is judged to +alter the claim: + +- update the manifest and matrix; +- run the oracle/differential suite; +- record the new tier and evidence in closure. + +Do not edit generated reports as the source of truth. + +## 7. Ordered work packages + +### Work package A — Documentation correction + +Intent: stop misdescribing authentication vs reuse. + +Acceptance evidence: docs diff; no `--auth`-as-authentication claim remains. + +### Work package B — Startup warning + +Intent: make the compatibility cache visible without changing behavior. + +Acceptance evidence: warning test; redaction; no per-connection spam. + +### Work package C — Error/annotate redaction + +Intent: remove raw URI/argv credential leaks. + +Acceptance evidence: Rust/Python redaction tests; `redact_uri_for_error` reuse. + +### Work package D — Debug redaction and manifest check + +Intent: close the latent IR leak and confirm no tier drift. + +Acceptance evidence: Debug test; manifest validator; differential only if claim +changed. + +## 8. Failure, cancellation, restart, and contention semantics + +- The startup warning is emitted once at compatibility startup, before serving. +- The auth-reuse cache remains bounded and monotonic; no change to expiry or + eviction. +- Redaction helpers must be total and allocation-bounded; a malformed URI must + not panic or echo raw input. +- `translate --annotate` remains deterministic. +- No runtime locking or reload changes. + +## 9. Compatibility and migration + +- Default pproxy-compatible behavior is unchanged; only warnings/docs/redaction. +- Operators who relied on the incorrect docs must migrate to: + - credentials in the listener fragment (existing behavior), and + - `--auth N` for the reuse interval, or `--auth 0`/native auth for no reuse. +- `translate` TOML remains valid and contains real credentials; do not paste + annotated output with credentials into public logs. +- If a manifest claim changes, follow the tier/evidence gate. + +## 10. Required tests + +### Focused unit tests + +- `redact_uri_for_error` / `redact_proxy_uri` for credentialed UDP remotes. +- `--annotate` output contains `****` and not the password/username. +- `ReverseServerToml`/`ReverseClientToml` Debug contains `****`. +- Startup warning includes 30 days/global scope and no credentials. + +### Integration tests + +- `egress pproxy translate` with `--annotate` and credentialed remotes. +- `egress pproxy check --json` remains redacted. +- Python `translate_pproxy_*` / `redacted_toml` tests remain green. +- `scripts/validate_pproxy_parity_manifest.py --check-report` remains green. + +### Security and negative tests + +- Malformed UDP remote with `user:pass@` does not leak. +- Passwords with `@`, `:`, brackets, and percent escapes do not leak. +- No raw `args.args` path in `--annotate`. + +### Migration and compatibility tests + +- Existing `cli.auth` manifest claim unchanged unless evidence is updated. +- Oracle/differential only if the claim changed. + +## 11. Required verification commands + +```bash +cargo test -p eggress-pproxy-compat +cargo test -p eggress-cli --test cli_exit_codes +cargo test -p eggress-runtime --test security_invariants +cargo test -p eggress-embed --test error_redaction +python3 scripts/validate_pproxy_parity_manifest.py --check-report +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +``` + +If a claim changed: + +```bash +EGRESS_REQUIRE_EXTERNAL_INTEROP=1 cargo test -p eggress-cli \ + --test differential_pproxy -- --ignored --test-threads=1 +``` + +## 12. Documentation updates + +- `docs/security/PPROXY_COMPAT_SECURITY_DIFFERENCES.md` — full `--auth` + correction and cache scope. +- `docs/PPROXY_MIGRATION.md` — auth/reuse migration guidance. +- `docs/cli/PPROXY_CLI_INVENTORY.md` — `--auth` default and meaning. +- `docs/SECURITY_REVIEW.md` — redaction evidence if relevant. +- `docs/parity/` only if a claim/evidence entry changes. + +## 13. Acceptance criteria + +- Security/migration docs correctly separate URI-fragment credentials from + `--auth` reuse. +- Compatibility startup warns about the 30-day, IP-only, cross-listener cache. +- Malformed UDP remote errors and `--annotate` output never contain raw + credentials. +- Compat IR Debug never prints `auth_password`. +- Manifest claim is unchanged or has a recorded evidence-backed update. +- Existing pproxy behavior and differential tests remain green. + +## 14. Stop conditions + +Stop and report if: + +- the warning/redaction requires a compatibility tier change without oracle + evidence; +- pproxy oracle behavior contradicts the documented 30-day/global cache; +- `--annotate` cannot be redacted without breaking its reproduction purpose + (define a placeholder contract first); +- a public `Debug`/serialization contract requires raw values (add an explicit + accessor rather than leaking by default); +- the change would alter credentials in generated TOML (it must not). + +## 15. Closure evidence required + +- Docs diff showing the corrected `--auth` contract. +- Warning test output with no credentials. +- Redaction test output for errors/annotate/Debug. +- Manifest validator output and either “claim unchanged” or differential + evidence for the updated claim. +- Explicit no-release statement. + +## 16. Handoff notes + +- The pproxy oracle’s `AuthTable` is class-level (`_auth`/`_user`); do not + “fix” it into a per-listener cache in compatibility mode without a tier + decision. Document it and warn. +- `--auth` is not an authentication switch. Credentials are in the URI fragment. +- Keep generated TOML usable; redact only diagnostics/annotations. +- Coordinate the shared-cache test with Protocols Edge M003’s SOCKS4 cache + seeding fix. diff --git a/plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md b/plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md new file mode 100644 index 00000000..1cce09d5 --- /dev/null +++ b/plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md @@ -0,0 +1,391 @@ +# Protocols Edge M003 — SOCKS4 Credential Enforcement and UDP Private-Egress Policy + +Status: implemented + +Repository baseline: `feat/auto-20261116-652bb64d` at `ba64e16` (workspace 1.0.12) + +Source roadmaps: + +- `plans/subsystems/protocols-edge-roadmap.md` (new milestone M003) +- `plans/subsystems/security-hardening-roadmap.md` (S3) + +Long-term requirements: + +- `plans/000-long-term-specification.md` §4 (invariants 2, 3, 10), §5 (compat contract) +- `plans/001-terminology-and-domain-model.md` §2–§3 (listener roles, route identity) + +Applicable ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +Primary class: invariant + +## 1. Objective + +Close two inbound-enforcement bypasses and the related address-classification +gaps: + +1. SOCKS4 listeners that configure `[listeners.auth]` must enforce the full + pproxy credential, not only the username. +2. `allow_private_egress = false` must be enforced after DNS for every locally + resolving UDP path, not only for literal IP targets. +3. Private/reserved-IP classification must include CGNAT and IPv4-embedding IPv6 + forms. +4. Non-loopback password-authenticated listeners without TLS must warn, because + HTTP/SOCKS credentials would otherwise travel in clear. + +This is a corrective pass; it adds no protocol or capability. + +## 2. Why this milestone is ready + +- The pinned pproxy 2.7.9 oracle defines SOCKS4 auth as + `userid in users`, where `users` contains full `user:pass` credential strings + (`pproxy/proto.py`, SOCKS4 `accept`). Eggress currently compares the SOCKS4 + user ID only to the username (`crates/eggress-server/src/accept/handlers.rs:151-160`), + so the password is unenforced. +- The UDP validation comment explicitly claims a post-DNS check that does not + exist on the UDP direct path (`crates/eggress-udp/src/security.rs:101-104` + versus `crates/eggress-udp/src/direct.rs:64-70`). +- `eggress-udp` already depends on `eggress-core`, which owns the shared + `is_reserved_or_private_ip` classifier + (`crates/eggress-core/src/connector.rs:20-75`); no new crate dependency is + required. +- `eggress-config` already emits non-fatal security warnings + (`crates/eggress-config/src/validate/security.rs:16-53`); the TLS/auth warning + fits that mechanism. +- No compatibility tier change is required if SOCKS4 is brought into line with + the existing `matched` behavior. If evidence shows a claim change, the + manifest/oracle gate applies. + +## 3. Current implementation evidence + +### SOCKS4 auth + +`accept_socks4`: + +- calls `cached_identity(auth, peer_ip)`; +- on cache miss destructures `auth_credentials(auth)` as `(username, _, _)` and + compares `request.user_id` only to `username` (`handlers.rs:151-160`); +- records the identity in the shared auth-reuse cache after success + (`handlers.rs:168-173`). + +`read_socks4_request` bounds the user ID and reads it as UTF-8 +(`crates/eggress-protocol-socks/src/socks4/server.rs`). SOCKS4 has no separate +password field; the pproxy-compatible carrier is the user ID. + +### UDP private egress + +`validate_standalone_target` rejects literal private IPs when +`allow_private_egress = false`, but the domain branch is `_ => {}` and the +comment defers the check to a post-DNS function (`security.rs:83-105`). +`UdpTargetFlow::new` calls `direct::resolve_target`, which does +`lookup_host(...).next()` and connects with no filtering +(`direct.rs:12-28,64-70`). Call sites include standalone SOCKS5 UDP +(`standalone.rs:114,622`), SOCKS5 UDP ASSOCIATE (`relay.rs:100,544`), and +standalone Shadowsocks UDP (`standalone_shadowsocks.rs:138,637`). + +### Address classification + +`is_reserved_or_private_ip` covers loopback, RFC1918, link-local, ULA, +multicast, documentation, benchmarking, 240/4, and some special-use IPv6, but +does not cover: + +- CGNAT `100.64.0.0/10`; +- NAT64 `64:ff9b::/96`; +- 6to4 `2002::/16`; +- Teredo `2001::/32`; +- smaller IETF special-purpose blocks such as `2001:2::/48`. + +The UDP-local `is_private_ipv4/6` helpers +(`crates/eggress-udp/src/security.rs:55-75`) cover only RFC1918/loopback/ +link-local/ULA/mapped forms, so literal CGNAT also passes +`allow_private_egress = false`. + +### Auth transport warning + +`validate_config_security` warns only when a non-loopback listener has no auth, +Shadowsocks, SSR, or Trojan (`security.rs:16-35`). It does not warn when HTTP/ +SOCKS password auth is configured without `[listeners.tls]`. + +## 4. Invariants that must not regress + +- SOCKS5, HTTP CONNECT/forward, H2, WebSocket, and reverse auth remain + constant-time and unchanged. +- SOCKS4 auth failures remain generic (`AuthenticationFailed`), with no + credential echo. +- The auth-reuse cache remains bounded, monotonic-expiry, and policy-scoped as + it is today; a SOCKS4 username-only identity must never seed it. +- UDP association/flow limits, client pinning, datagram bounds, and idle + timeouts are unchanged. +- `allow_private_egress = true` remains the pproxy-compatible default; local + UDP echo tests that use loopback continue to work when explicitly permitted. +- Domain resolution uses the existing `lookup_host`; do not add a second lookup + or a blocking resolver. +- No pproxy compatibility tier change without manifest/evidence. + +## 5. Scope + +### In scope + +- `eggress-server::accept` SOCKS4 credential comparison and cache seeding. +- `eggress-udp` post-DNS destination filtering for standalone SOCKS5 UDP, + SOCKS5 UDP ASSOCIATE, and standalone Shadowsocks UDP. +- Shared private/reserved-IP classification for CGNAT/NAT64/6to4/Teredo and + other selected special-purpose ranges. +- `eggress-config` warning for non-loopback password auth without TLS. +- Focused unit/integration tests, docs, and metrics where available. + +### Explicitly out of scope + +- CIDR route matching and admin Host validation (Routing M003). +- pproxy `--auth` reuse documentation/guardrails (Parity M003). +- Admin TLS or native admin transport changes. +- TCP `allow_private_egress` unification; the documented literal-private TCP + default is unchanged. +- SSH/TLS dependency upgrades. + +## 6. Required production changes + +### A. Enforce the full SOCKS4 credential + +In `accept_socks4`: + +1. Build the expected user-ID credential as `username + ":" + password`. +2. Compare `request.user_id.as_bytes()` against that byte string with + `subtle::ConstantTimeEq`. +3. On mismatch, return `AuthenticationFailed` without revealing which component + failed. +4. On success, record an identity derived from the authenticated username (for + example `ClientIdentity::Username(username)`), not the raw username-only + user ID. Never call `record_authenticated` from a path that accepted a + username-only match. +5. If `auth_credentials` is `None`, keep the current unauthenticated path. + +Consider adding SOCKS4 auth-failure accounting through the existing session +metrics path if the accept signature can carry it without broad churn; if not, +record it as a follow-up rather than widening this milestone. + +Add tests for: + +- `user:pass` accepted; +- `user` alone rejected; +- `user:wrong` rejected; +- empty user ID rejected when auth is configured; +- cache is not seeded by a rejected SOCKS4 attempt; +- a successful SOCKS4 full-credential auth does not authorize a different + listener/credential set through the shared cache (coordinate with Parity M003 + for the cross-listener case). + +### B. Apply policy after UDP DNS resolution + +Introduce one destination-policy parameter on the direct UDP flow path: + +- Add `allow_private_egress: bool` (or a small `TargetPolicy` value) to + `UdpTargetFlow::new` and `direct::resolve_target`. +- Resolve the domain, collect all returned addresses, and filter each through + `eggress_core::connector::is_reserved_or_private_ip` when the policy is + restrictive. +- Connect to the first allowed address; if none remain, return a structured + `UdpError` and record the existing dropped metric. Do not truncate to the + first address before filtering. +- Pass `config.allow_private_egress` from `StandaloneUdpConfig` and + `RelayConfig`; the standalone Shadowsocks path passes its own flag. +- Keep the literal-target shape checks (port zero, multicast, broadcast, + unspecified) in `validate_standalone_target`. + +Add tests: + +- `allow_private_egress = false` plus a domain resolving to `127.0.0.1` is + dropped and no datagram reaches a local echo server; +- the same target is allowed when `allow_private_egress = true`; +- a domain resolving to a public address still works (use a test resolver or a + hosts-file-free approach; do not depend on external DNS); +- mixed public/private resolution filters private addresses rather than + connecting to the first answer. + +### C. Extend the shared address classifier + +Add the missing ranges to `eggress-core::connector::is_reserved_or_private_ip`: + +- IPv4 CGNAT `100.64.0.0/10`; +- IPv6 NAT64 `64:ff9b::/96`; +- IPv6 6to4 `2002::/16`; +- IPv6 Teredo `2001::/32`; +- selected IETF special-purpose ranges (`2001:2::/48` benchmarking, + `2001:10::/28`/`2001:20::/28` ORCHID where appropriate). + +Reuse the core classifier from `eggress-udp` instead of maintaining a second +set of `is_private_ipv4/6` rules; keep the UDP-local shape checks separate. +Add table-driven tests for every new range and for IPv4-mapped forms. + +### D. Warn on auth without TLS + +In `validate_config_security`, add a warning when: + +- the listener bind is non-loopback; +- `listener.auth` is configured; +- `listener.tls` is `None`; +- the protocol set contains HTTP, SOCKS4, or SOCKS5 (Shadowsocks and Trojan + provide their own encryption/auth; do not warn for those). + +The warning must say credentials may be transmitted in clear and recommend +`[listeners.tls]`, loopback, or a trusted tunnel. Do not reject the config in +this milestone; it is a compatibility-preserving warning. + +## 7. Ordered work packages + +### Work package A — SOCKS4 full-credential enforcement + +Intent: remove the password bypass and cache seeding. + +Acceptance evidence: focused accept tests; pproxy oracle/differential evidence +for SOCKS4 auth if the manifest claim is touched; no credential in errors. + +### Work package B — UDP post-DNS policy + +Intent: make `allow_private_egress = false` true for domain targets. + +Acceptance evidence: unit + integration tests for private domain drop and +public/private mixed resolution; no double lookup; existing UDP tests green. + +### Work package C — Address classification + +Intent: close CGNAT/NAT64/6to4/Teredo gaps and deduplicate UDP classification. + +Acceptance evidence: table-driven tests; `is_reserved_or_private_ip` used by +UDP; no behavior change when policy allows private egress. + +### Work package D — Auth-transport warning and docs + +Intent: make plaintext credential exposure visible. + +Acceptance evidence: config warning test; docs updated; no false warning for +Shadowsocks/Trojan/TLS listeners. + +## 8. Failure, cancellation, restart, and contention semantics + +- A failed SOCKS4 auth returns before any tunnel/flow is created; no cache + entry is written. +- UDP resolution failure or all-private resolution returns a dropped datagram; + it does not create a flow or retry another address after a connect error. +- Cancellation while resolving/validating a UDP target does not leak a flow; + existing flow registry cleanup remains responsible for established flows. +- The warning path is read-only and runs at config validation; no runtime + locking changes. + +## 9. Compatibility and migration + +- `allow_private_egress` remains default `true` for pproxy compatibility; + opting into `false` becomes actually enforced for domains. +- SOCKS4 changes from username-only to full `user:pass` user-ID matching. This + restores the pproxy 2.7.9 behavior; verify the manifest claim and run the + oracle/differential suite if the claim text changes. +- Existing configs with SOCKS4 + auth must send the full credential in the + SOCKS4 user ID. Document this in the migration/security docs. +- No protocol wire change. + +## 10. Required tests + +### Focused unit tests + +- SOCKS4: full credential accepted; username-only rejected; wrong password + rejected; empty rejected; cache not seeded on failure. +- UDP: private domain dropped with policy false; allowed with true; mixed + addresses filtered; public domain still resolved. +- Classifier: CGNAT, NAT64, 6to4, Teredo, mapped IPv6, documentation ranges. +- Config: auth-without-TLS warning for HTTP/SOCKS; no warning for TLS, + Shadowsocks, or Trojan. + +### Integration tests + +- `eggress-udp` standalone/relay private-domain drop. +- `eggress-runtime` UDP suite with an echo server. +- SOCKS4 accept tests in `eggress-server`. + +### Security and negative tests + +- No raw username/password in errors/logs. +- No datagram sent to the private target on rejection. +- No cache reuse after a failed SOCKS4 attempt. + +### Migration and compatibility tests + +- Existing `allow_private_egress = true` tests continue to pass. +- Oracle/differential SOCKS4 auth scenarios, if the claim changed. + +## 11. Required verification commands + +```bash +cargo test -p eggress-server accept +cargo test -p eggress-protocol-socks +cargo test -p eggress-udp +cargo test -p eggress-runtime --test udp +cargo test -p eggress-runtime --test security_invariants +cargo test -p eggress-config +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +``` + +If the SOCKS4 manifest claim changes: + +```bash +EGRESS_REQUIRE_EXTERNAL_INTEROP=1 cargo test -p eggress-cli \ + --test differential_pproxy -- --ignored --test-threads=1 +``` + +## 12. Documentation updates + +- `docs/security/THREAT_MODEL.md` — UDP post-DNS policy and SOCKS4 credential + semantics. +- `docs/security/SECURE_CONFIGURATION.md` — private egress and auth-with-TLS + guidance; correct the “CIDR is a complete private-IP ACL” implication. +- `docs/security/OPEN_PROXY_PREVENTION.md` — non-loopback auth-without-TLS + warning. +- `architecture/protocols-socks.md` / `architecture/udp.md` — target policy. +- `docs/parity/PPROXY_PRACTICAL_COMPATIBILITY_MATRIX.md` only if the SOCKS4 + claim changes. + +## 13. Acceptance criteria + +- A SOCKS4 listener with auth accepts `user:pass` and rejects username-only and + wrong-password attempts. +- A failed SOCKS4 attempt cannot seed the auth-reuse cache. +- `allow_private_egress = false` drops domain targets resolving to private/ + reserved addresses on all three UDP paths. +- CGNAT/NAT64/6to4/Teredo are classified as non-public. +- Non-loopback HTTP/SOCKS auth without TLS produces a warning. +- Existing UDP/SOCKS behavior remains green when private egress is allowed. + +## 14. Stop conditions + +Stop and report if: + +- the pproxy oracle shows a different SOCKS4 credential carrier than + `user:pass`; +- UDP resolution needs a new resolver abstraction or timeout policy beyond the + existing flow; +- the classifier change would reject a legitimate pproxy-compatible target that + the oracle accepts; +- the auth warning requires a compatibility tier change; +- the SOCKS4 change requires a public API change outside the accept path. + +## 15. Closure evidence required + +- Focused test output for SOCKS4/UDP/classifier/config. +- pproxy differential output if the claim changed; otherwise a statement that + the existing `matched` claim was restored. +- `cargo audit`/`cargo deny` status (dependency advisories are owned by other + milestones; record remaining IDs). +- Documentation diff. +- Explicit no-release statement. + +## 16. Handoff notes + +- pproxy SOCKS4 uses the raw user ID as the credential carrier; do not add a + nonstandard password field. +- Do not resolve domains twice; validate the addresses returned by the existing + lookup. +- `allow_private_egress = true` is intentional compatibility; do not change the + default. +- Coordinate the cross-listener auth-reuse documentation with Parity M003. diff --git a/plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md b/plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md new file mode 100644 index 00000000..91805417 --- /dev/null +++ b/plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md @@ -0,0 +1,321 @@ +# Routing, Health, Metrics, and Admin M003 — CIDR Canonicalization and Admin Exposure + +Status: implemented + +Repository baseline: `feat/auto-20261116-652bb64d` at `ba64e16` (workspace 1.0.12) + +Source roadmaps: + +- `plans/subsystems/routing-health-observability-roadmap.md` (new milestone M003) +- `plans/subsystems/security-hardening-roadmap.md` (S4) + +Long-term requirements: + +- `plans/000-long-term-specification.md` §4 (invariants 4–5, 10) +- `plans/001-terminology-and-domain-model.md` §2–§3 (Route, admin surface) + +Applicable ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +Primary class: invariant + +## 1. Objective + +Make CIDR destination/source matching family-correct for IPv4-mapped IPv6 and +make the “literal IPs only, no DNS” contract explicit, so an operator cannot +believe a CIDR rule is a complete private-network ACL. Add Host/Origin +validation to the admin HTTP surface to block DNS-rebinding reads, and warn when +non-loopback admin is plaintext HTTP. + +## 2. Why this milestone is ready + +- `ipnet::IpNet::contains(&IpAddr)` intentionally returns `false` across + address families (`ipnet` `Contains<&IpAddr>` implementation); an IPv4 CIDR + therefore does not match `::ffff:10.0.0.1`. The matcher passes the raw + `IpAddr` (`crates/eggress-routing/src/matcher.rs:190-208`). +- `MatchExpr::DestinationCidr` already returns `false` for every domain + (`matcher.rs:190-196`); this is existing behavior, not a new decision. + The security documentation currently presents CIDR rules as private-network + blocking (`docs/security/SECURE_CONFIGURATION.md:127-155`). +- `eggress-admin` currently has no `Host`/`Origin` check in the request path + (`crates/eggress-admin/src/server.rs`, `routes.rs`); the admin surface is + read-only except `POST /-/route-explain`, but DNS rebinding can read + `/-/status`, `/-/routes`, `/-/upstreams`, `/-/reverse`, and `/metrics`. +- `AdminConfig` has no TLS field (`crates/eggress-config/src/model.rs:346-355`), + and the admin CLI client rejects `https://` URLs + (`crates/eggress-admin/src/client.rs:297-301`). Non-loopback admin is + therefore plaintext HTTP. + +## 3. Current implementation evidence + +- `DestinationCidr`: only `TargetHost::Ip` matches; domains are `false` + (`matcher.rs:190-196`). +- `SourceCidr`: uses `request.source` and `cidr.contains(&addr.ip())` + (`matcher.rs:202-208`); no canonicalization. +- `RouteRequest` carries `TargetAddr`/`Source` from the listener; SOCKS5, + HTTP CONNECT, and H2 can all carry IPv4-mapped IPv6 literals. +- `validate_config_security` handles listener/admin/reverse warnings but does + not warn about CIDR/domain limitations or admin plaintext HTTP + (`crates/eggress-config/src/validate/security.rs:16-53`). +- `AdminServer::new` warns when bound non-loopback, but only about exposure; + it does not validate Host/Origin (`crates/eggress-admin/src/server.rs:155-170`). +- `AdminState` has `auth`, snapshot, metrics, readiness; no allowed-host field. + +## 4. Invariants that must not regress + +- First-match-wins routing and `route explain` output semantics are unchanged. +- CIDR matching remains synchronous: no DNS resolution or blocking work inside + route evaluation. +- `SourceCidr` remains an exact match on the actual peer address; no proxy + header trust is introduced. +- Admin auth (bearer/basic), auth-failure limiter, connection cap, body cap, and + read-only behavior remain unchanged. +- Admin endpoints continue to serve loopback clients (`curl 127.0.0.1:9090`, + `localhost`, `[::1]`) without new configuration. +- No pproxy compatibility claim changes. + +## 5. Scope + +### In scope + +- Canonical IPv4/IPv6 handling in `DestinationCidr` and `SourceCidr`. +- A config warning + docs for CIDR’s literal-only/domain limitation. +- `[admin] allowed_hosts` (or equivalent) and Host/Origin validation. +- Non-loopback admin plaintext warning. +- Admin tests for allowed/blocked Host, Origin, and JSON content type. +- Docs updates for CIDR and admin transport. + +### Explicitly out of scope + +- DNS-aware routing matchers or resolving domains inside route evaluation. +- Native admin TLS implementation. +- Unified TCP `allow_private_egress` policy. +- Admin authentication changes or new admin endpoints. +- Changing the default bind or admin enabled state. + +## 6. Required production changes + +### A. Canonicalize CIDR inputs + +Add a small canonicalization helper, for example: + +```rust +fn canonical_ip(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)), + v4 => v4, + } +} +``` + +Use it in both `DestinationCidr` and `SourceCidr` before `cidr.contains(...)`. +Do not mutate the original `TargetAddr`; route explanation should still show the +client-supplied literal. + +Add tests: + +- `::ffff:10.0.0.1` matches `10.0.0.0/8`; +- `::ffff:10.0.0.1` in `SourceCidr` matches an IPv4 source CIDR; +- native IPv6 CIDRs still match native IPv6; +- IPv4 CIDRs do not match unrelated IPv6; +- mapped addresses do not bypass a `not { destination_cidr = ... }` rule. + +### B. Make the CIDR contract explicit + +1. Add a config warning when a rule’s action is `reject` (or equivalent) and it + contains a `destination_cidr` in a private/reserved range without any + host/host-suffix/host-regex/domain condition. The warning should say CIDR + matches literal IP targets only; a domain resolving into that range is not + matched by this rule, and upstream chains resolve names remotely. +2. Update `docs/security/SECURE_CONFIGURATION.md` and + `docs/CONFIG_REFERENCE.md` to state the literal-only contract and to point + operators to `allow_private_egress`/egress policy or trusted upstreams for + names. +3. Do not add DNS resolution to the router. A DNS-aware policy, if ever needed, + is a separate architecture decision. + +Be conservative with the warning: it must not fire for rules that intentionally +match only literal IPs and also have a host condition that covers names, and it +must not echo credentials. + +### C. Add admin Host/Origin validation + +Add an optional `[admin] allowed_hosts = ["admin.example", "127.0.0.1"]` field +(compiled into `AdminConfig`). Defaults: + +- loopback bind: allow the bind host, `localhost`, `127.0.0.1`, and `[::1]`/ + `::1`; +- non-loopback bind: allow the bind host and `localhost`; operators behind a + reverse proxy or DNS name must add the host explicitly. + +Implement a `host_allowed(req, allowed_hosts)` check before auth/handle: + +- parse the `Host` header (strip the port; handle bracketed IPv6); +- reject a missing/unparseable/unknown Host with `400 Bad Request`; +- never redirect or echo the rejected value into HTML; +- keep the response body generic. + +For `POST /-/route-explain`: + +- require `Content-Type: application/json` (case-insensitive media type); +- if an `Origin` header is present, require its host to be in `allowed_hosts`; +- reject `Origin: null` for browser-style requests unless the operator + explicitly allows it. + +Do not apply Host validation to the CLI admin client in a way that breaks +`http://127.0.0.1:9090`; the default allowlist must cover it. + +### D. Warn on plaintext non-loopback admin + +In `validate_config_security`, for a non-loopback `admin.bind`, emit a warning +that the admin protocol is plaintext HTTP and that Basic/Bearer credentials and +topology are exposed; recommend loopback, a VPN/SSH tunnel, or a TLS-terminating +reverse proxy with `allowed_hosts`. Keep the existing “no auth” warning. + +### E. Tests + +- CIDR canonicalization tests above. +- Config warning tests for private CIDR + reject + no host condition; no warning + for literal-only intentional rules or CIDR + host condition. +- Admin Host acceptance/rejection (including IPv6 and port forms). +- Admin Origin acceptance/rejection for POST. +- `Content-Type` rejection for `route-explain`. +- Non-loopback admin warning. +- Existing admin auth/limiter/status tests remain green. + +## 7. Ordered work packages + +### Work package A — CIDR canonicalization + +Intent: remove the mapped-IPv6 bypass without changing route semantics. + +Acceptance evidence: destination/source matcher tests; no async work added. + +### Work package B — Literal-only warning and docs + +Intent: prevent operators from treating CIDR rules as a complete private ACL. + +Acceptance evidence: warning tests; docs updated; no credential echo. + +### Work package C — Admin Host/Origin validation + +Intent: block DNS-rebinding reads and simple cross-origin POSTs. + +Acceptance evidence: admin tests for allowed/blocked Host, Origin, and content +type; default loopback clients still work. + +### Work package D — Admin plaintext warning + +Intent: make non-loopback admin transport risk visible. + +Acceptance evidence: warning test; docs updated. + +## 8. Failure, cancellation, restart, and contention semantics + +- A rejected Host/Origin fails before auth and before reading a body; no state + change. +- Host validation is a pure header check; no DNS lookup, blocking work, or + additional connection. +- Admin connection timeout/cap and auth-failure limiter remain in force. +- Route matching remains synchronous and snapshot-based; no new locks. +- Config warnings remain non-fatal and are emitted once at load/reload. + +## 9. Compatibility and migration + +- Adding `allowed_hosts` is additive; existing configs keep working because the + default allowlist is derived from the bind and loopback names. +- Operators using a DNS name or reverse proxy for admin must add that host; + document the migration. +- CIDR canonicalization changes only previously broken mapped-IPv6 matches; + literal IPv4/IPv6 behavior is unchanged. +- The CIDR warning is advisory; configurations are not rejected. +- No pproxy claim change. + +## 10. Required tests + +### Focused unit tests + +- `eggress-routing` destination/source CIDR mapped IPv6, native IPv6, and + negation cases. +- `eggress-config` private-CIDR warning and admin `allowed_hosts` validation. +- `eggress-admin` Host parsing (IPv4, IPv6 brackets, port), allowed/blocked + Host, allowed/blocked Origin, content-type rejection. + +### Integration tests + +- Admin status/routes/upstreams/metrics with default loopback Host. +- Admin route-explain POST with JSON content type. +- Admin with a configured allowed host and a mismatched Host. +- Reload: admin bind/auth unchanged; `allowed_hosts` changes follow the + existing restart-required policy or are applied consistently. + +### Security and negative tests + +- DNS-rebinding-style `Host: attacker.example` is rejected. +- `Origin: https://attacker.example` POST is rejected. +- Rejected requests do not include credentials or internal topology in the + response. +- CIDR warning does not echo a password or upstream URI. + +## 11. Required verification commands + +```bash +cargo test -p eggress-routing +cargo test -p eggress-config +cargo test -p eggress-admin +cargo test -p eggress-runtime --test security_invariants +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +``` + +No oracle/differential run is required unless a compatibility claim changes. + +## 12. Documentation updates + +- `docs/security/SECURE_CONFIGURATION.md` — CIDR literal-only limitation, + upstream-chain trust, admin loopback/VPN/TLS terminator, `allowed_hosts`. +- `docs/CONFIG_REFERENCE.md` — `admin.allowed_hosts`, CIDR semantics. +- `architecture/routing.md` — canonical IP matching and no DNS in routing. +- `architecture/admin.md` — Host/Origin policy and plaintext warning. +- `docs/security/THREAT_MODEL.md` — admin DNS-rebinding surface. + +## 13. Acceptance criteria + +- `::ffff:10.0.0.1` matches `10.0.0.0/8` for destination and source CIDRs. +- CIDR rules remain literal-only; docs and a config warning say so. +- Admin rejects unexpected Host and cross-origin POSTs while default loopback + clients continue to work. +- Non-loopback admin produces a plaintext/warning message. +- No admin auth/limiter behavior regresses. +- No pproxy claim change. + +## 14. Stop conditions + +Stop and report if: + +- `IpAddr::to_canonical`/mapped helper is unavailable at MSRV 1.89; +- admin Host validation breaks legitimate loopback or reverse-proxy access in a + way that cannot be solved with `allowed_hosts`; +- the CIDR warning requires resolving domains or changing route async semantics; +- the change would alter an existing compatibility claim without evidence; +- admin TLS becomes necessary to satisfy the finding (separate decision). + +## 15. Closure evidence required + +- Matcher/config/admin test output. +- Warning output for a sample private-CIDR rule and a non-loopback admin. +- Documentation diff. +- Statement that no DNS was added to routing and no admin state-changing + endpoint was introduced. +- Explicit no-release statement. + +## 16. Handoff notes + +- Keep `route explain` output useful: canonicalize for matching, not for the + reported target. +- Do not trust `X-Forwarded-Host`; only the actual `Host` header is in scope. +- `allowed_hosts` should compare host names case-insensitively and ignore the + port. +- Coordinate the admin warning wording with Parity M003’s security-doc changes. diff --git a/plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md b/plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md new file mode 100644 index 00000000..69115415 --- /dev/null +++ b/plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md @@ -0,0 +1,321 @@ +# Transports M004 — TLS Trust Store and Dependency Advisory Remediation + +Status: implemented + +Repository baseline: `feat/auto-20261116-652bb64d` at `ba64e16` (workspace 1.0.12) + +Source roadmaps: + +- `plans/subsystems/transports-roadmap.md` (new milestone M004) +- `plans/subsystems/security-hardening-roadmap.md` (S1) + +Long-term requirements: + +- `plans/000-long-term-specification.md` §4 (invariants 7, 8, 10), §5 (compat contract) +- `plans/001-terminology-and-domain-model.md` §3 (transport policy scoping) + +Applicable ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +Primary class: invariant + +## 1. Objective + +Restore verified outbound TLS in the default build by moving the rustls, +webpki-roots, rustls-webpki, rustls-platform-verifier, quinn, and tokio +dependency graph to versions without the known advisories, and make the +insecure-TLS surface match its documentation. + +This is a corrective pass. It does not add a transport, change chain semantics, +or change a pproxy compatibility claim. + +## 2. Why this milestone is ready + +The affected versions are available on crates.io and `cargo update --dry-run` +resolves them within the current semver constraints: + +```text +rustls 0.23.45 -> 0.23.46 +rustls-webpki 0.103.15 -> 0.103.17 +webpki-roots 1.0.8 -> 1.0.12 (via webpki-roots 0.26.11) +rustls-platform-verifier 0.7.0 -> 0.7.1 +webpki-root-certs 1.0.9 -> 1.0.12 +quinn 0.11.11 -> 0.11.12 +quinn-proto 0.11.17 -> 0.11.19 +quinn-udp 0.5.15 -> 0.5.16 +tokio 1.52.3 -> 1.54.1 +``` + +The workspace pins are broad enough for these updates: +`rustls = "0.23"`, `webpki-roots = "0.26"`, `quinn = "0.11.11"`, +`tokio = "1"`, `rustls-platform-verifier = "0.7.0"` (`Cargo.toml:48-97`). + +`russh` is handled by Transports M005; `zip` is tracked by Delivery M004. + +## 3. Current implementation evidence + +- `TlsClientConfigBuilder::with_system_roots()` loads + `webpki_roots::TLS_SERVER_ROOTS` — `crates/eggress-transport-tls/src/client.rs:169-173`. + The name is misleading: this is a bundled Mozilla root set, not the OS store. +- `build()` installs that root set with + `ClientConfig::builder().with_root_certificates(...)` — + `crates/eggress-transport-tls/src/client.rs:279-287`. This is the + `rustls-webpki` verifier path affected by RUSTSEC-2026-0382. +- The resolved `webpki-roots 1.0.8` parent is affected by + RUSTSEC-2026-0381 (bundled `emSign ECC Root CA - G3`); the 0.26.11 + compatibility package itself is marked unaffected, but its 1.x parent is not. +- `rustls 0.23.45` carries RUSTSEC-2026-0346/-0347/-0348/-0349. The default + build does not enable certificate compression or ECH, and no custom + `ClientSessionStore` was found, but the network-triggered downgrade advisory + is a reason to upgrade regardless. +- `insecure-tls` is enabled unconditionally by `eggress-cli` and + `eggress-runtime` (`crates/eggress-cli/Cargo.toml:78`, + `crates/eggress-runtime/Cargo.toml:72`), and per-hop `?insecure` is parsed at + `crates/eggress-uri/src/lib.rs:532-536`. The runtime warning exists at + `crates/eggress-transport-tls/src/client.rs:205-213`, but + `docs/security/SECURE_CONFIGURATION.md:53` says insecure mode is API-only. +- `CompiledListenerTlsConfig` derives `Debug` with `key_pem: Vec` + (`crates/eggress-config/src/compile/model.rs:297-303`); no production log + path currently prints it, but it is an unredacted secret-bearing `Debug`. + +## 4. Invariants that must not regress + +- Default outbound TLS verifies certificates; there is no fallback to insecure + verification on a build, root-load, or handshake error. +- `TlsClientConfigBuilder::with_custom_ca_pem` replaces the root store exactly + as before; custom CA behavior is unchanged. +- `client_config_with_alpn` preserves trust roots, custom verifiers, mTLS + identity, and every other `ClientConfig` field; it only mutates ALPN. +- `tls_override` + per-hop `insecure=true` continues to fail closed. +- Insecure QUIC remains behind `insecure-quic`; insecure TLS remains explicit. +- No OpenSSL, native-tls, aws-lc-sys, or C dependency is introduced. +- MSRV 1.89 and edition 2021 remain valid. +- No pproxy compatibility claim changes. + +## 5. Scope + +### In scope + +- `Cargo.lock` and workspace dependency resolution for the TLS/QUIC/tokio graph. +- `eggress-transport-tls` default roots/verifier and insecure-mode documentation. +- `eggress-transport-quic` only if the quinn/platform-verifier update requires a + source adjustment. +- `eggress-config` TLS listener config `Debug` redaction. +- Focused TLS/QUIC/runtime tests and the relevant feature-slice checks. +- Security documentation corrections for root-store and insecure-mode claims. + +### Explicitly out of scope + +- `russh` migration (Transports M005). +- `zip`/`eggup-archive` upgrade (Delivery M004; currently blocked upstream). +- Admin TLS implementation. +- New trust-store providers or a move to the OS certificate store. +- Changing pproxy compatibility tiers. + +## 6. Required production changes + +### A. Upgrade the default TLS/QUIC/tokio graph + +Update the lockfile with the narrowest commands that resolve the advisories: + +```bash +cargo update -p rustls@0.23.45 +cargo update -p rustls-webpki@0.103.15 +cargo update -p webpki-roots@1.0.8 +cargo update -p rustls-platform-verifier@0.7.0 +cargo update -p quinn@0.11.11 +cargo update -p quinn-proto@0.11.17 +cargo update -p quinn-udp@0.5.15 +cargo update -p tokio@1.52.3 +``` + +Verify with `cargo tree -i` that the default graph resolves the fixed versions. +Do not use `--all-features` for validation; use the documented feature slices. + +If `rustls 0.23.46` or `quinn 0.11.12` requires a source adaptation, keep it +mechanical and preserve the invariants above. Do not bump to a new major/minor +line (for example `rustls 0.24-dev`) in this milestone. + +### B. Make the trust-store description truthful + +Update the `with_system_roots` documentation and the security docs to say +“bundled Mozilla roots via webpki-roots”, not “system root store”. If a future +OS-store backend is desired, it is a separate decision. + +### C. Make insecure TLS explicit and documented + +Choose the smallest safe correction: + +1. Keep the compiled feature but add a config-load warning when any hop has + `insecure=true`, naming the redacted chain and the policy decision; and +2. Correct `docs/security/SECURE_CONFIGURATION.md`, `docs/SECURITY_REVIEW.md`, + and `docs/URI_GRAMMAR.md` so `?insecure` is documented as reachable from + CLI/config builds. + +Do not remove `insecure-tls` from default builds in this milestone if that would +break pproxy-compatible `--ssl`/QUIC translation. A feature-gate change requires +a separate compatibility assessment. + +### D. Redact TLS private-key `Debug` + +Replace the derived `Debug` for `CompiledListenerTlsConfig` with a custom impl +that reports `has_cert`, `has_key`, and key length only. Add a unit/compile-time +guard asserting the PEM/key bytes do not appear in `format!("{:?}", config)`. +Check the reverse-TLS types as well; `eggress-protocol-reverse` already has a +redacting `Debug`, so preserve that pattern. + +### E. Tests + +Add focused tests that: + +- assert the default client config is not insecure and builds from the current + root set; +- assert `?insecure` still requires the expected feature path and does not + silently substitute insecure verification when a `tls_override` is present; +- assert `CompiledListenerTlsConfig` Debug does not contain PEM/key material; +- retain the existing custom-CA, mTLS, ALPN-preservation, and H2 pool tests. + +## 7. Ordered work packages + +### Work package A — Dependency upgrade and tree verification + +Intent: move the default graph to fixed versions without source churn. + +Required changes: lockfile/workspace resolution; any mechanical API adaptation; +`cargo tree` evidence. + +Acceptance evidence: `cargo tree -i` for rustls/rustls-webpki/webpki-roots/ +quinn/tokio; `cargo audit` no longer reports the TLS/QUIC/tokio advisories; the +default `eggress-cli` feature graph is unchanged except for versions. + +### Work package B — Trust-store and insecure-mode truth + +Intent: stop overstating the root store and make insecure selection visible. + +Required changes: rustdoc, security docs, config warning if selected, tests. + +Acceptance evidence: docs review; warning test; no credential echoed. + +### Work package C — Secret-bearing Debug redaction + +Intent: remove the latent TLS private-key exposure. + +Required changes: custom `Debug`; tests. + +Acceptance evidence: Debug output contains no PEM/key bytes; existing reverse +TLS redaction test remains green. + +## 8. Failure, cancellation, restart, and contention semantics + +- A root-load/parse failure remains a startup/handshake error; it must not + downgrade to insecure verification. +- A failed TLS handshake leaves the chain attempt failed; no retry to a + different policy or root set. +- Insecure-mode warning is emitted before the first handshake, not per packet. +- TLS config caching (`OnceLock`) remains process-wide and policy-separated + (`default_client_config` vs `default_insecure_client_config`). +- No listener topology/reload semantics change. + +## 9. Compatibility and migration + +- No API signature removal. `with_system_roots` keeps its name for source + compatibility; only its documentation/behavioral description is corrected. +- Existing configs with `?insecure` continue to work but warn when selected. +- pproxy compatibility claims are unchanged; this is a dependency/trust-store + corrective, not a tier change. +- `Cargo.lock` changes are expected; do not alter the four gated version + locations or publish a release. + +## 10. Required tests + +### Focused unit tests + +- `eggress-transport-tls`: default config not insecure; custom CA still used; + mTLS key parsing; ALPN preservation; `tls_override` + insecure rejection. +- `eggress-config`: TLS listener `Debug` redaction. +- `eggress-uri`: `?insecure` parsing remains stable. + +### Integration tests + +- `eggress-runtime` TLS suite (existing `tests/tls.rs`). +- H2/QUIC feature-gated tests if the lockfile update touches quinn. + +### Security and negative tests + +- Insecure mode is never selected without an explicit request. +- Debug output contains no key bytes. +- Advisory check confirms the fixed versions. + +### Migration and compatibility tests + +- Existing `tls_override`, custom-CA, and pproxy `--ssl` translation tests remain + green. + +## 11. Required verification commands + +```bash +cargo test -p eggress-transport-tls +cargo test -p eggress-config +cargo test -p eggress-runtime --test tls +cargo test -p eggress-embed --test error_redaction +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +cargo audit --ignore RUSTSEC-2023-0071 +cargo deny check +cargo check -p eggress-cli --locked --no-default-features \ + --features full,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins +``` + +`cargo deny check` may still fail on the `russh`/`zip` advisories until +Transports M005/Delivery M004 close; record the remaining IDs explicitly rather +than claiming a clean gate. + +## 12. Documentation updates + +- `docs/SECURITY_REVIEW.md` — root-store wording, insecure-mode + reachability, unsafe/handshake claims if touched. +- `docs/security/SECURE_CONFIGURATION.md` — root store and insecure TLS. +- `docs/URI_GRAMMAR.md` — `?insecure` behavior. +- `architecture/transports-tls.md` — root source and policy boundary. +- `docs/security/THREAT_MODEL.md` — correct the “system root store” implication + if present. + +## 13. Acceptance criteria + +- Default outbound TLS resolves `rustls >= 0.23.46`, `rustls-webpki >= 0.103.16`, + `webpki-roots >= 1.0.10`, and a fixed quinn/tokio graph. +- `cargo audit` no longer reports RUSTSEC-2026-0381/-0382 or the listed + quinn/tokio IDs for the default feature graph. +- No insecure verification is selected without an explicit request. +- TLS private keys never appear in `Debug`. +- Existing TLS/ALPN/custom-CA/H2 tests remain green. +- Documentation states the bundled-root behavior accurately. + +## 14. Stop conditions + +Stop and report rather than improvise if: + +- the fixed versions require a semver-breaking API change in rustls/quinn; +- MSRV 1.89 is insufficient; +- `cargo update` cannot resolve a fixed version without a source change; +- the insecure-mode correction would require a compatibility-tier change; +- `cargo deny` cannot be interpreted because another milestone is mid-flight. + +## 15. Closure evidence required + +- Lockfile diff and `cargo tree -i` output for every affected crate. +- `cargo audit`/`cargo deny` output, with any remaining IDs explained. +- Focused test output and broad gate output. +- Documentation diff. +- Explicit statement that no release/tag was created. + +## 16. Handoff notes + +- Do not run `cargo update` broadly; update only the named packages. +- Do not edit `Cargo.toml` version numbers; this is not a release. +- Preserve user changes; check `git status` before editing. +- If `rustls-webpki` resolves to `0.103.17`, that is acceptable (>=0.103.16). +- `webpki-roots 0.26.11` is a compatibility re-export; verify its 1.x parent, + not only the 0.26 version string. diff --git a/plans/implementation/transports/005-russh-065-advisory-migration.md b/plans/implementation/transports/005-russh-065-advisory-migration.md new file mode 100644 index 00000000..e6569094 --- /dev/null +++ b/plans/implementation/transports/005-russh-065-advisory-migration.md @@ -0,0 +1,286 @@ +# Transports M005 — `russh` 0.65 Advisory Migration + +Status: implemented + +Repository baseline: `feat/auto-20261116-652bb64d` at `ba64e16` (workspace 1.0.12) + +Source roadmaps: + +- `plans/subsystems/transports-roadmap.md` (new milestone M005) +- `plans/subsystems/security-hardening-roadmap.md` (S2) + +Long-term requirements: + +- `plans/000-long-term-specification.md` §4 (invariants 1–3, 7, 10) +- `plans/001-terminology-and-domain-model.md` §3 (policy-scoped transport reuse) + +Applicable ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +Primary class: invariant (optional feature) + +## 1. Objective + +Migrate `eggress-transport-ssh` from `russh 0.62.6` to the fixed `0.65.x` +line and remove RUSTSEC-2026-0492 (client handler callbacks for channels the +client never opened, CVSS 7.5) and RUSTSEC-2026-0495 (agent signing without +confirm), plus the `crypto-bigint`/`ctutils` timing advisories pulled through +`russh`/`rsa`. + +The migration must preserve the established SSH compatibility boundary: +known-hosts verification by default, insecure host-key acceptance only in the +explicit `ssh` + `pproxy-compat` compatibility cache, and only direct TCP, +remote Unix-socket, and explicitly requested remote TCP forwarding. + +## 2. Why this milestone is ready + +- `russh 0.65.2` is published and requires Rust 1.89, matching the workspace + MSRV. +- `russh 0.65.2` still exposes the client APIs this crate uses: + `client::connect_stream`, `client::Handle`, + `channel_open_direct_tcpip`, `channel_open_direct_streamlocal`, + `authenticate_password`, and `authenticate_publickey`. +- The breaking changes are localized to the `client::Handler` trait and key + types; the crate owns that adapter in one file + (`crates/eggress-transport-ssh/src/lib.rs`). +- SSH is optional (`ssh` feature); the default CLI/Python graph is unaffected, + so this can land after the default-graph TLS fix. + +`cargo update` alone only moves `russh 0.62.6 -> 0.62.7`, which does not carry +the fixed versions; the workspace pin at `Cargo.toml:93` must be changed. + +## 3. Current implementation evidence + +- Workspace pin: `russh = { version = "0.62.6", default-features = false, + features = ["ring", "flate2", "rsa"] }` (`Cargo.toml:93`). +- `CompatClient` implements `russh::client::Handler` + (`crates/eggress-transport-ssh/src/lib.rs:129-200`). +- `check_server_key` currently takes `&russh::keys::PublicKey` and returns + `Result`; 0.65 takes `&PublicKeyOrCertificate` and returns + a future. +- `server_channel_open_forwarded_tcpip` uses `russh::client::ChannelOpenHandle` + (`lib.rs:176-200`); 0.65 retains this type but the trait method is async. +- Session auth uses `authenticate_password` / `authenticate_publickey` + (`lib.rs:529-570`); key loading uses `russh::keys::load_secret_key`. +- Host-key checks use `russh::keys::check_known_hosts` and + `check_known_hosts_path` (`lib.rs:136-166`). +- `SshAuth` already has a redacting `Debug` (`lib.rs:49-56`), and errors avoid + echoing password/private-key paths. +- The OpenSSH regression suite is + `cargo test -p eggress-transport-ssh --test openssh -- --nocapture` and the + embed-level required regression is + `EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked + --no-default-features --features ssh,pproxy-compat --test ssh -- --nocapture`. + +## 4. Invariants that must not regress + +- Native/default SSH verifies host keys through `KnownHosts`; missing or + unreadable known-hosts files reject the host key. +- `SshHostKeyPolicy::InsecureCompatibility` remains available only with the + `pproxy-compat` feature and is scoped to its own cache; it never authorizes a + session created under `KnownHosts`. +- Passwords and private-key paths never appear in `Debug`, errors, diagnostics, + or evidence output. +- Only direct TCP, remote Unix-socket, and explicitly requested remote TCP + forwarding are exposed. Remote command, SFTP, agent forwarding, and implicit + listener exposure remain unavailable. +- The SSH session cache remains bounded, policy-keyed, and cleared on service + shutdown. +- No new SSH listener role or auth mechanism is added. +- No pproxy compatibility claim changes. + +## 5. Scope + +### In scope + +- Workspace `russh` pin and lockfile update to `0.65.x`. +- `crates/eggress-transport-ssh/src/lib.rs` adapter migration. +- `crypto-bigint`/`ctutils` resolution through the updated `russh`/`rsa` graph. +- Focused SSH unit tests, OpenSSH regression, and feature-slice checks. +- Documentation updates for any changed API/behavior. + +### Explicitly out of scope + +- SSH listener support. +- New auth methods (certificates, agent forwarding, keyboard-interactive). +- Changing host-key policy defaults. +- TLS/QUIC/tokio upgrades (Transports M004). +- Release/tag/publish. + +## 6. Required production changes + +### A. Bump the dependency + +Change `Cargo.toml:93` to a `0.65.x` line (prefer `0.65.2` or the latest +`0.65.x` patch) while keeping `default-features = false` and the existing +`ring`, `flate2`, and `rsa` features. Do not enable `aws-lc-rs`; the workspace +is ring-only. + +Run `cargo update -p russh` and verify the lock resolves `russh >= 0.65.0`, +`crypto-bigint`/`ctutils` at fixed versions, and no duplicate `russh` line. + +### B. Adapt `CompatClient` + +Migrate the `russh::client::Handler` implementation: + +- `check_server_key` must accept `&russh::keys::PublicKeyOrCertificate` and + return the new future type. Extract the public key (reject certificate + variants unless the current behavior intentionally supports them) before + calling `check_known_hosts`/`check_known_hosts_path`. +- Keep the exact policy branch: `KnownHosts`, `KnownHostsFile`, and + `InsecureCompatibility`. Preserve the warning on new insecure sessions. +- Adapt `server_channel_open_forwarded_tcpip` and any `ChannelOpenHandle` + accept/reject calls to the 0.65 signature. +- Adapt `connect_stream`, `authenticate_*`, and channel-open calls only where + the compiler requires it; do not replace the session model. + +### C. Keep the compatibility boundary + +Do not use the migration as an opportunity to enable agent forwarding, remote +commands, SFTP, or certificate-based host keys. Keep the existing feature gates +and the cache policy key. + +### D. Verification + +Run both the crate-level OpenSSH regression and the embed feature-boundary +regression. If OpenSSH tools are unavailable, record the skip; CI installs +`openssh-server` and treats the embed test as required. + +## 7. Ordered work packages + +### Work package A — Pin, compile, and resolve the fixed graph + +Intent: get the new API compiling with no behavior change. + +Acceptance evidence: `cargo check` for `eggress-transport-ssh`, +`eggress-embed` with `ssh` and `ssh,pproxy-compat`, and the CLI feature slice; +`cargo tree -i russh` shows `0.65.x`; `cargo audit` no longer reports the SSH +advisories. + +### Work package B — Host-key and channel API adaptation + +Intent: preserve the known-hosts and forwarded-channel policy under the new +trait signatures. + +Acceptance evidence: unit tests for known_hosts file policy, insecure policy +scoping, rejected host key, and forwarded channel accept/reject. + +### Work package C — OpenSSH regression and redaction + +Intent: prove real-server compatibility and no secret leak. + +Acceptance evidence: OpenSSH tests green (or explicitly skipped with reason); +`error_redaction` remains green; `SshAuth`/session-key Debug still redacted. + +## 8. Failure, cancellation, restart, and contention semantics + +- Host-key rejection fails the connection; it never falls back to + `InsecureCompatibility`. +- Cache lookup remains policy-keyed; a session authenticated under one policy is + never reused under another. +- Cancellation during authentication/channel open drops the session without + leaving a cache entry. +- Concurrent cache access remains mutex-protected and bounded. +- Shutdown clears cached sessions as before. + +## 9. Compatibility and migration + +- The `ssh` feature remains opt-in; default CLI/embed/Python feature sets are + unchanged. +- No pproxy tier changes. If the migration changes observable SSH behavior + (for example certificate host keys), update the manifest/evidence or preserve + the old behavior. +- The public `SshHostKeyPolicy`/`SshAuth` types remain source-compatible where + possible; `russh` types are not part of the public Eggress API. + +## 10. Required tests + +### Focused unit tests + +- `KnownHosts` missing/unreadable file rejects. +- `KnownHostsFile` accepts a matching key and rejects a mismatch. +- `InsecureCompatibility` is only constructed under the compatibility feature + and warns. +- Session cache keys include the policy and cannot cross-reuse. +- Forwarded-channel accept/reject still observes the configured limits. +- `SshAuth`/session-key `Debug` contains `****`. + +### Integration tests + +- `eggress-transport-ssh --test openssh`. +- `eggress-embed --test ssh` with `ssh,pproxy-compat`. +- Outbound chain execution through an SSH hop (existing runtime tests). + +### Security and negative tests + +- Host-key mismatch fails closed. +- No password/private-key path in errors. +- No new forwarding surface (remote command/SFTP) is reachable. + +## 11. Required verification commands + +```bash +cargo test -p eggress-transport-ssh +EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked \ + --no-default-features --features ssh,pproxy-compat --test ssh -- --nocapture +cargo check -p eggress-embed --locked --no-default-features --features ssh +cargo check -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat +cargo check -p eggress-cli --locked --no-default-features \ + --features full,ssh,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +cargo audit --ignore RUSTSEC-2023-0071 +``` + +Do not use `--all-features` (drags in test-only `insecure-quic`). + +## 12. Documentation updates + +- `architecture/transports-ssh-quic-h3.md` — API/session notes if changed. +- `docs/SECURITY_REVIEW.md` — SSH host-key policy statement remains + accurate; note the fixed `russh` line. +- `docs/RUST_API.md` only if a public SSH type/signature changes. +- `plans/subsystems/transports-roadmap.md` status table. + +## 13. Acceptance criteria + +- Workspace resolves `russh >= 0.65.0`; `cargo audit` no longer reports + RUSTSEC-2026-0492/-0495 or the `crypto-bigint`/`ctutils` SSH path. +- `ssh` and `ssh,pproxy-compat` compile; OpenSSH regression is green where + required. +- Known-hosts default and insecure compatibility scoping are unchanged. +- No credential/private-key leak appears in Debug/errors. +- No new forwarding surface is exposed. +- Default feature graph and pproxy claims are unchanged. + +## 14. Stop conditions + +Stop and report if: + +- `russh 0.65.x` requires a redesign of the session/cache model; +- certificate host keys cannot be handled without changing policy; +- the API migration would require exposing `russh` types in Eggress's public API; +- OpenSSH regression cannot be run and the release gate requires it; +- MSRV 1.89 is insufficient; +- the upgrade pulls an aws-lc/C dependency. + +## 15. Closure evidence required + +- Dependency diff and `cargo tree -i russh`. +- `cargo audit`/`cargo deny` output for the SSH graph. +- OpenSSH/embed regression output, including skip reasons if applicable. +- Unit tests for host-key policy, cache scoping, and Debug redaction. +- Feature-slice compile output. +- Documentation diff and explicit no-release statement. + +## 16. Handoff notes + +- SSH is optional; do not block the default TLS fix on this plan. +- Preserve the exact `KnownHosts` fail-closed behavior; do not “simplify” it to + `known_hosts=None`. +- Keep the `ring` feature set; do not accept `russh` defaults that pull + `aws-lc-rs`. +- The OpenSSH test fixture may skip only when tools are genuinely unavailable; + CI installs `openssh-server` and requires it. diff --git a/plans/registry.md b/plans/registry.md index fce479cb..0e7c8bba 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -29,20 +29,29 @@ Complementary authority: `docs/ROADMAP.md` (canonical roadmap), `docs/parity/ppr |---|---|---|---|---| | Proxy core and relay | closed | `plans/subsystems/proxy-core-relay-roadmap.md` | All milestones closed; 1.0.10 H2/pool correctives qualified | None. Historical evidence in `plans/archive/phase-records/`. | | Server, runtime lifecycle, and configuration | closed | `plans/subsystems/server-runtime-config-roadmap.md` | All milestones closed | None. | -| Routing, health, metrics, and admin | closed | `plans/subsystems/routing-health-observability-roadmap.md` | All milestones closed | None. | -| Edge protocols | closed | `plans/subsystems/protocols-edge-roadmap.md` | All milestones closed | None. | -| Transports | active | `plans/subsystems/transports-roadmap.md` | M003 downstream-safe bounded WebSocket composition API | Ready on published v1.0.11; additive downstream API seam. | +| Routing, health, metrics, and admin | closed | `plans/subsystems/routing-health-observability-roadmap.md` | All milestones closed; M003 CIDR/admin exposure qualified | None. | +| Edge protocols | closed | `plans/subsystems/protocols-edge-roadmap.md` | All milestones closed; M003 SOCKS4/UDP/auth-transport qualified | None. | +| Transports | active | `plans/subsystems/transports-roadmap.md` | M003 downstream-safe WebSocket API | M004/M005 closed 2026-11-16; M003 remains ready (additive, no hard blocker). | | Outbound chains and connectors | closed | `plans/subsystems/outbound-chains-roadmap.md` | All milestones closed; pooled-transport/H2/ALPN correctives qualified | None. | -| Parity contract and compatibility translation | closed | `plans/subsystems/parity-compat-roadmap.md` | All milestones closed; manifest has no unresolved `gap` outside tiered boundaries | None. | -| Delivery (CLI, embed, Python, release) | active | `plans/subsystems/delivery-roadmap.md` | M003 Eggup archive/pair self-update adoption landed and shipped in published `v1.0.10` | Closed 2026-09-29 (`plans/closure/delivery/003-status.md`); `v1.0.11` patch release published 2026-09-30; `v1.0.12` patch release published 2026-10-08; next version bump is a separate maintainer-authorized release action. | +| Parity contract and compatibility translation | closed | `plans/subsystems/parity-compat-roadmap.md` | All milestones closed; M003 auth reuse/redaction qualified | Manifest claim unchanged; `check --json` raw-field follow-up tracked in the closure record. | +| Delivery (CLI, embed, Python, release) | closed | `plans/subsystems/delivery-roadmap.md` | All milestones closed; M004 updater trust/advisory gate qualified | M003 closed 2026-09-29 (`plans/closure/delivery/003-status.md`); M004 closed 2026-11-16 (`plans/closure/delivery/004-status.md`) with four `zip` advisories tracked in `deny.toml` (owner/review date recorded); `v1.0.12` published 2026-10-08; next version bump is a separate maintainer-authorized release action. | +| Security hardening (cross-cutting corrective) | closed (2026-11-16) | `plans/subsystems/security-hardening-roadmap.md` | S1–S6 implemented and verified | Four `zip 6.0.0` advisories remain as a narrow, commented `deny.toml` exception with owner and review date pending upstream `eggup-archive`; no release authorized. | -## Dependency-ready implementation plans +## Implementation plans and dependency state | Subsystem | Milestone | Status | Implementation plan | Dependency / consumer | |---|---|---|---|---| | Transports | M003 downstream-safe bounded WebSocket composition API | ready | `plans/implementation/transports/003-downstream-safe-bounded-websocket-composition-api.md` | Published v1.0.11 baseline; requested by Eggtunnel M019 to remove direct Tungstenite ownership. | +| Transports | M004 TLS trust/default advisory remediation | closed | `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` | `plans/closure/transports/004-status.md` | +| Transports | M005 `russh` 0.65 advisory migration | closed | `plans/implementation/transports/005-russh-065-advisory-migration.md` | `plans/closure/transports/005-status.md` | +| Protocols Edge | M003 SOCKS4 credential enforcement and UDP private-egress policy | closed | `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` | `plans/closure/protocols-edge/003-status.md` | +| Routing, health, metrics, admin | M003 CIDR canonicalization and admin exposure | closed | `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` | `plans/closure/routing-health-observability/003-status.md` | +| Delivery | M004 updater trust, advisory gate, and credential-output hardening | closed | `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` | `plans/closure/delivery/004-status.md` (tracked `zip` exception) | +| Parity Compat | M003 auth reuse semantics and compatibility redaction | closed | `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` | `plans/closure/parity-compat/003-status.md` | -Delivery M003 landed and closed 2026-09-29 (`plans/closure/delivery/003-status.md`). +The six security-corrective plans above closed on 2026-11-16 after the +coordinator broad gate. Delivery M003 landed and closed 2026-09-29 +(`plans/closure/delivery/003-status.md`). ## Current execution order and dependency gates @@ -54,11 +63,13 @@ Delivery M003 landed and closed 2026-09-29 (`plans/closure/delivery/003-status.m **Verification gate:** `docs/CI_STATUS.md` owns verification policy; `docs/TESTING.md` owns the suite inventory. Ordinary changes use the narrowest test first, then the broad gate before merging substantial Rust changes. +**Security corrective gate (closed 2026-11-16):** the 2026-11-16 audit corrective program at `plans/subsystems/security-hardening-roadmap.md` is implemented and verified. S1 removed the distrusted-root/webpki exposure and the default-graph TLS/QUIC/tokio advisories; S2 moved optional SSH to `russh 0.65.2`; S3 restored pproxy SOCKS4 full-credential semantics and enforced UDP private-egress policy after DNS; S4 canonicalized CIDR matching and added admin Host/Origin validation; S5 hardened the updater and added the advisory gate; S6 corrected the compatibility auth-reuse contract and redacted compat diagnostics. The only remaining audit item is the four `zip 6.0.0` advisories in the updater graph, tracked as a narrow, commented `deny.toml` exception (owner: Delivery M004; review by 2027-05-01) pending upstream `eggup-archive` with `zip >= 9.0.0`. No tag or publication is authorized by these plans. + **Eggup updater-convergence gate (closed 2026-09-28; consumer landed 2026-09-29):** Delivery M003 is registered at `plans/implementation/delivery/003-eggup-archive-pair-self-update-adoption.md` and closed in `plans/closure/delivery/003-status.md`. Eggup Archive M001d is runtime-qualified (`eggstack/eggup@18d83de`, hosted run `36335233644`), and the required post-M001d APIs shipped as compatible registry packages: `eggup-core 0.1.2` + `eggup-archive 0.1.2` (Eggup M009 closure, `eggstack/eggup@v0.1.2`). The final Cargo dependency cutover landed against the registry versions with hosted Linux/macOS/Windows updater evidence. Eggress release/checksum/version/CLI policy remains local. ## Blocked work -None. Delivery M003 was unblocked by Eggup M009 publication closure on 2026-09-28 (see ready plans above). +- **`zip 6.0.0` / `eggup-archive` (tracked residual)** — RUSTSEC-2026-0429/-0367/-0368/-0369 remain in the updater dependency graph. `eggup-archive 0.1.2` and `0.2.0` pin `zip = "6.0.0"`; an upstream Eggup release with `zip >= 9.0.0` is required. The vulnerable `ZipArchive::extract` APIs are not used by Eggup's bounded extractor, so the advisory gate carries a narrow, commented exception with owner (Delivery M004) and review date (2027-05-01); delete it when the upstream dependency lands. `cargo deny --workspace check` passes on 2026-11-16 with exactly this exception. ## Closure work and current control points @@ -67,4 +78,5 @@ None. Delivery M003 was unblocked by Eggup M009 publication closure on 2026-09-2 | 1.0.10 H2/pool/ALPN qualification | closed, published as `v1.0.10` (2026-09-24) | `plans/archive/phase-records/H2_PHYSICAL_SESSION_EVIDENCE_CORRECTIVE.md`, `ONE_ZERO_TEN_CLOSURE_EVIDENCE_PASS.md`, `H2_TLS_OVERRIDE_ALPN_PRESERVATION_AND_1_0_10_QUALIFICATION_CORRECTIVE.md`, `POOLED_TRANSPORT_POLICY_IDENTITY_AND_1_0_10_ROLLFORWARD.md`; implementation `c5826b3`; Rust CI `36032622797` | | Distribution/release maintenance | closed | `plans/archive/phase-records/DISTRIBUTION_AND_RELEASE_MAINTENANCE_ROADMAP.md`, `PYPI_WHEEL_MATRIX_EXPANSION.md`, `MANUAL_CRATES_IO_PUBLISHING_SIMPLIFICATION.md` | | Eggfetch 0.2 consolidation | closed | `plans/archive/phase-records/EGGFETCH_0_2_HTTP_CONNECT_CONSOLIDATION.md`, `EGGFETCH_0_2_CORRECTIVE_CLOSURE.md`, `EGGFETCH_0_2_EVIDENCE_DOCUMENTATION_CLEANUP.md` | +| Security corrective program (2026-11-16 audit) | closed 2026-11-16 | `plans/subsystems/security-hardening-roadmap.md`; closure records `transports/004`, `transports/005`, `protocols-edge/003`, `routing-health-observability/003`, `delivery/004`, `parity-compat/003`; tracked `zip` exception | | Pre-transition flat index | archived | `plans/archive/phase-records-README-legacy.md` (the former `plans/README.md`) | diff --git a/plans/subsystems/README.md b/plans/subsystems/README.md index 59418b59..d93b5c61 100644 --- a/plans/subsystems/README.md +++ b/plans/subsystems/README.md @@ -23,6 +23,11 @@ parity-compat-roadmap.md delivery-roadmap.md ``` +`security-hardening-roadmap.md` is a cross-cutting corrective program, not an +architectural subsystem. It coordinates security milestones that are owned by +the subsystem roadmaps above and MUST NOT duplicate their runtime/protocol/ +delivery ownership. + ## Required roadmap structure ```markdown diff --git a/plans/subsystems/delivery-roadmap.md b/plans/subsystems/delivery-roadmap.md index abc82456..39909b55 100644 --- a/plans/subsystems/delivery-roadmap.md +++ b/plans/subsystems/delivery-roadmap.md @@ -1,6 +1,6 @@ # Delivery (CLI, Embed, Python, Release) Roadmap -Status: active; M001-M003 closed (M003 Eggup archive/pair adoption landed on registry eggup-core/archive 0.1.2 with hosted Linux/macOS/Windows updater evidence) +Status: closed; M001-M004 closed; M004 carries a tracked `zip 6.0.0` upstream exception (owner and review date in `deny.toml`) Long-term references: @@ -47,6 +47,8 @@ CLI cleanup/version/self-update, distribution docs/policy, embed/Python stabiliz A newly qualified upstream convergence path was registered as M003: Eggup Archive M001d can replace Eggress's generic shell archive extraction and bespoke two-binary rollback transaction while Eggress retains GitHub/checksum/version/CLI policy. The implementation plan is complete and landed: Eggup M009 published compatible versioned `eggup-core 0.1.2` and `eggup-archive 0.1.2` to the registry on 2026-09-28, and M003 adopted them with hosted updater qualification (closure `plans/closure/delivery/003-status.md`). Permanent git/path dependencies are not acceptable for the publishable workspace. +A 2026-11-16 security audit found that release updater code still honors `EGRESS_UPDATE_BASE_URL`/`file://`, discovers `curl` and `sha256sum`/`shasum` through `PATH`, and stages in a predictable `/tmp/eggress-update-` directory. The same audit found `system-proxy inspect --json` serializes raw credential-bearing settings and that CI/release preflight has no advisory gate. M004 hardens those surfaces and tracks the `zip 6.0.0` advisory as an upstream `eggup-archive` blocker. + ## 5. Target architecture One version, verified artifacts, manual-gated publication, with generic self-update archive/transaction mechanics delegated to Eggup while Eggress retains release and CLI policy. The existing release architecture is attained; updater-mechanism convergence landed as M003. @@ -58,7 +60,8 @@ CLI surface (hard) +--> Embed facade (soft) +--> Python bindings/packaging (soft) +--> Release automation (operational: tags, PyPI env, crates.io manual) - `--> M003 Eggup updater convergence [CLOSED with registry 0.1.2 pair] + +--> M003 Eggup updater convergence [CLOSED with registry 0.1.2 pair] + `--> M004 updater trust/advisory gate [implemented; zip upstream blocker tracked as a deny.toml exception] ``` ## 7. Milestones @@ -83,21 +86,31 @@ Hard gate (satisfied 2026-09-28): Eggup's post-M001d `eggup-core` API and `eggup Exit requires shell extraction removed from the updater success path, local generic pair rollback removed, bound-source staging, exact candidate validation preserved, rollback/recovery fault evidence, package dry-run, Rust 1.89, Linux/macOS/Windows qualification, and recorded footprint delta. +### Milestone 4 — Updater trust, advisory gate, and credential-output hardening + +Plan: `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md`. + +Class: invariant / infrastructure. Status: closed 2026-11-16 — see `plans/closure/delivery/004-status.md`; the `zip 6.0.0` advisories remain an explicit, commented gate exception (owner/review date recorded) pending an upstream `eggup-archive` release. + +Objective: gate the updater test hook out of release builds; replace PATH-resolved integrity tools with trusted absolute paths and in-process SHA-256; use private staging; redact `system-proxy inspect --json`; add a CI/release advisory gate with a narrow tracked `zip` exception. + +Exit: default builds reject `EGRESS_UPDATE_BASE_URL`/`file://`; no PATH hash authority; staging is private/create-new/symlink-safe; JSON has no credentials; the gate runs; the `zip` blocker is recorded in the registry with a removal condition. No release/tag. + ## 8. Cross-cutting requirements Features: `eggress-cli full` excludes `ssh`/`quic`/`pproxy-legacy`/`legacy-crypto`/`pproxy-daemon` (extra check command for those paths); `eggress-embed full` includes `pproxy-legacy`; never `--all-features` (drags test-only `insecure-quic`). Python: maturin develop + pytest from root with `importlib` mode. Fuzz workspace standalone. Compat: Python `pproxy` namespace owned only by `python-pproxy-compat`. ## 9. Verification strategy -`cargo test -p eggress-cli --test cli_exit_codes`, embed feature-slice checks + OpenSSH regression for boundary changes, Python pytest (`python/tests`, `tests/compat`), `scripts/release-preflight.sh` for version/release changes, `cargo deny`/`cargo audit --ignore RUSTSEC-2023-0071` for dependency changes. +`cargo test -p eggress-cli --test cli_exit_codes`, embed feature-slice checks + OpenSSH regression for boundary changes, Python pytest (`python/tests`, `tests/compat`), `scripts/release-preflight.sh` for version/release changes, `cargo deny`/`cargo audit --ignore RUSTSEC-2023-0071` for dependency changes. M004 additionally requires updater negative tests (env/file/PATH/symlink/TOCTOU), in-process SHA-256 vectors, and `system-proxy --json` redaction tests. ## 10. Risks and decision points -Tag-push discipline remains critical because both publish workflows fire on `v*`. M003 carries Windows running-image qualification risk and default-binary footprint risk now that its registry-package dependency gate is closed. The current whole-archive SHA-256 release evidence is sufficient for Eggup extraction because member expectations are optional; do not invent a new member manifest solely for this migration. +Tag-push discipline remains critical because both publish workflows fire on `v*`. M003 carries Windows running-image qualification risk and default-binary footprint risk now that its registry-package dependency gate is closed. The current whole-archive SHA-256 release evidence is sufficient for Eggup extraction because member expectations are optional; do not invent a new member manifest solely for this migration. M004's `zip 6.0.0` advisory cannot be removed until `eggup-archive` publishes a `zip >= 9` dependency; the vulnerable `extract()` APIs are not used by Eggup's bounded extractor, so only a narrow, commented gate exception is acceptable in the interim. ## 11. Completion definition -Existing delivery surfaces are qualified and 1.0.10 is published as `v1.0.10` (2026-09-24). M003 landed the updater convergence with the versioned Eggup dependency gate closed 2026-09-28 and hosted qualification green. +Existing delivery surfaces are qualified and 1.0.10 is published as `v1.0.10` (2026-09-24). M003 landed the updater convergence with the versioned Eggup dependency gate closed 2026-09-28 and hosted qualification green. M004 is complete when the updater trust/output/advisory controls are closed, with the `zip` upstream dependency either fixed or explicitly accepted and tracked. ## 12. Milestone status @@ -106,3 +119,4 @@ Existing delivery surfaces are qualified and 1.0.10 is published as `v1.0.10` (2 | 1 | closed (historical) | archive CLI/embed/python records | archive + Git history | — | | 2 | closed | archive distribution records | registry control points | maintainer release action (out of planning scope) | | 3 | closed | `plans/implementation/delivery/003-eggup-archive-pair-self-update-adoption.md` | `plans/closure/delivery/003-status.md` | — (registry 0.1.2 pair adopted; updater lanes green) | +| 4 | closed | `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` | `plans/closure/delivery/004-status.md` | Four `zip 6.0.0` advisories remain as a narrow, commented `deny.toml` exception with an owner and review date, pending an upstream `eggup-archive` release with `zip >= 9.0.0` | diff --git a/plans/subsystems/parity-compat-roadmap.md b/plans/subsystems/parity-compat-roadmap.md index 17d2e62e..4d20e243 100644 --- a/plans/subsystems/parity-compat-roadmap.md +++ b/plans/subsystems/parity-compat-roadmap.md @@ -1,6 +1,6 @@ # Parity Contract and Compatibility Translation Roadmap -Status: closed +Status: closed — M003 auth-reuse/redaction corrective implemented and verified 2026-11-16 Long-term references: @@ -44,6 +44,8 @@ Architecture: `architecture/pproxy-compat.md`; contract: `docs/parity/pproxy_cap Manifest complete with no unresolved `gap` outside tiered boundaries; report generated from manifest with CI consistency check; differential suites (27 + 11 scenarios, Python structural tests) complete under the two-gate strategy. External interop suites remain opt-in. +A 2026-11-16 security audit found that the security-differences docs conflate `--auth` with authentication: pproxy credentials come from the URI fragment, while `--auth` is the source-IP reuse interval (default 30 days, global IP-keyed cache). The same audit found raw credentialed UDP remote URIs in compat errors, raw argv in `translate --annotate`, and plaintext `auth_password` in compat IR `Debug`. M003 corrects the docs/warnings and redacts those paths; it does not change pproxy defaults or tiers. + ## 5. Target architecture Manifest-governed claim set with derived reports and gated evidence — attained. @@ -67,21 +69,35 @@ Class: capability. Objective: translator + tiers + matrix + validator. Exit: Pha Class: capability/polish. Objective: differential/interop evidence, strict phases 0–10, consistency passes. Exit: manifest `gap`-free per §4. Status: closed. Evidence: archive `PPROXY_*`, `MILESTONES_A_C_*`, `API_BOUNDARY_*` records. +### Milestone 3 — Auth reuse semantics and compatibility redaction + +Class: invariant / polish. Status: closed 2026-11-16 — implementation landed; +closure record `plans/closure/parity-compat/003-status.md` (coordinator +workspace-wide `fmt`/`clippy`/`test` gate passed). + +Implementation plan: + +- `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` + +Objective: correct the `--auth`/URI-fragment authentication contract, document and warn about the 30-day global source-IP reuse cache, redact raw UDP remote URIs and `translate --annotate` argv, and make compat IR `Debug` redact `auth_password`. + +Exit: security/migration docs accurately separate credentials from reuse; startup warns about the compatibility cache; malformed UDP remote errors and annotated argv contain no raw credentials; compat Debug hides `auth_password`; manifest claim unchanged or updated with oracle/differential evidence. No release/tag. + ## 8. Cross-cutting requirements -Compat: five-tier diagnostics never disagree (single owner). Security: redaction in repr/TOML. CI: `--check-report` consistency; external suites only when the claim changed. Docs: parity README + matrix + skill updates together. +Compat: five-tier diagnostics never disagree (single owner). Security: redaction in repr/TOML; M003 adds raw-URI/argv/Debug redaction and makes the pproxy source-IP reuse contract explicit. CI: `--check-report` consistency; external suites only when the claim changed. Docs: parity README + matrix + skill updates together. ## 9. Verification strategy -Manifest validator (strict + report-check), differential suites, opt-in external interop (`EGRESS_REQUIRE_EXTERNAL_INTEROP=1 … differential_pproxy --ignored`, `EGRESS_REQUIRE_SHADOWSOCKS_INTEROP=1 … interoperability_shadowsocks --ignored`), each only when claims changed. +Manifest validator (strict + report-check), differential suites, opt-in external interop (`EGRESS_REQUIRE_EXTERNAL_INTEROP=1 … differential_pproxy --ignored`, `EGRESS_REQUIRE_SHADOWSOCKS_INTEROP=1 … interoperability_shadowsocks --ignored`), each only when claims changed. M003 additionally requires Rust/Python redaction tests and a startup-warning test. ## 10. Risks and decision points -None active. Any new parity claim requires manifest + evidence + matrix regeneration. +The pproxy `--auth` default/global IP cache is intentional compatibility behavior; M003 documents and warns rather than changing it. Any behavior change beyond docs/warnings requires a manifest update plus oracle/differential evidence. SOCKS4 full-credential enforcement is owned by Protocols Edge M003; coordinate the shared-cache test. ## 11. Completion definition -Manifest-authoritative contract with `gap`-free tiered coverage and derived reports — attained. +Manifest-authoritative contract with `gap`-free tiered coverage and derived reports, plus M003 auth-reuse/redaction correction closed — attained when both are true. ## 12. Milestone status @@ -89,3 +105,4 @@ Manifest-authoritative contract with `gap`-free tiered coverage and derived repo |---|---|---|---|---| | 1 | closed (historical) | archive parity records | archive + manifest history | — | | 2 | closed (historical) | archive strict/differential records | manifest + CI history | — | +| 3 | closed | `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` | `plans/closure/parity-compat/003-status.md` | — (manifest claim unchanged; `check --json` raw-field follow-up tracked in the closure §10) | diff --git a/plans/subsystems/protocols-edge-roadmap.md b/plans/subsystems/protocols-edge-roadmap.md index c2043b50..c9a09ed2 100644 --- a/plans/subsystems/protocols-edge-roadmap.md +++ b/plans/subsystems/protocols-edge-roadmap.md @@ -1,6 +1,6 @@ # Edge Protocols Roadmap -Status: closed +Status: closed — M003 implemented and verified 2026-11-16 Long-term references: @@ -45,6 +45,8 @@ Architecture: `architecture/protocols-http.md`, `protocols-socks.md`, `protocols Phases 1/3/4/5 plus post-parity SOCKS5 correctness, reverse/UDP composition, and strict-phase protocol corrections complete. Standing feature-gated boundaries (SSR framing/plugins, legacy crypto, QUIC/H3 optional) are intentional and manifest-recorded. +A 2026-11-16 security audit found two inbound-enforcement gaps: SOCKS4 auth compares only the username (the configured password is never enforced and a success can seed the shared IP reuse cache), and `allow_private_egress = false` is bypassable for UDP domain targets because the promised post-DNS check is absent from the direct flow. The same audit found the shared private/reserved-IP classifier missing CGNAT and IPv4-embedding IPv6 forms, and no warning when non-loopback HTTP/SOCKS password auth runs without TLS. M003 closes those gaps without changing the pproxy default or adding a protocol. + ## 5. Target architecture Any listener protocol pairable with any valid upstream chain through the boxed boundary — attained within documented tiers. @@ -57,6 +59,7 @@ TCP listener protocols (hard) `--> Upstream client roles (hard) `--> Reverse composition (soft) `--> Strict-phase corrections (soft) + `--> M003 SOCKS4/UDP/auth-transport corrective (implemented) ``` ## 7. Milestones @@ -69,21 +72,33 @@ Class: capability. Objective: protocol set integrated on both sides of the chain Class: capability/polish. Objective: post-parity SOCKS5, reverse/UDP, SSR/plugin bounds, legacy-cipher boundaries. Exit: strict phases closed per manifest. Status: closed. Evidence: archive `POST_PARITY_*`, `PPROXY_STRICT_PHASE_*` records. +### Milestone 3 — SOCKS4 credential enforcement and UDP private-egress policy + +Class: invariant. Status: closed 2026-11-16 — closure record `plans/closure/protocols-edge/003-status.md` (coordinator workspace-wide gate passed). + +Implementation plan: + +- `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` + +Objective: enforce the full pproxy SOCKS4 user-ID credential, apply `allow_private_egress` after DNS on all locally resolving UDP paths, extend CGNAT/NAT64/6to4/Teredo classification, and warn when non-loopback HTTP/SOCKS auth has no TLS. + +Exit: SOCKS4 username-only/wrong-password attempts fail without seeding the reuse cache; private-resolving UDP domains are dropped when the policy disallows private egress; classification tests cover the new ranges; the auth-without-TLS warning is emitted; existing `allow_private_egress = true` behavior remains green. No release/tag. + ## 8. Cross-cutting requirements -Config: per-listener protocol validation. Compat: manifest tiers per protocol behavior. Security: auth checks, bounded handshakes, redaction. Concurrency: association/flow bounds, shutdown drain. Performance: `udp_relay`/`http_connect_upstream` benches informational. Docs: protocol deep dives + `udp.md`. +Config: per-listener protocol validation. Compat: manifest tiers per protocol behavior. Security: auth checks, post-DNS destination policy, bounded handshakes, redaction; M003 adds the SOCKS4 full-credential rule and resolved-target UDP enforcement. Concurrency: association/flow bounds, shutdown drain. Performance: `udp_relay`/`http_connect_upstream` benches informational. Docs: protocol deep dives + `udp.md`. ## 9. Verification strategy -Protocol unit/integration tests, UDP relay flow tests, differential suites for HTTP/SOCKS (`EGRESS_REQUIRE_EXTERNAL_INTEROP` gated interop only when the claim changed). +Protocol unit/integration tests, UDP relay flow tests, differential suites for HTTP/SOCKS (`EGRESS_REQUIRE_EXTERNAL_INTEROP` gated interop only when the claim changed). M003 additionally requires SOCKS4 auth tests, private-domain UDP drop tests, classifier tables, and the auth-without-TLS config warning. ## 10. Risks and decision points -None active. New listener roles or framing changes require composition validation plus manifest review. +M003's SOCKS4 change is a compatibility-sensitive restore of the pinned pproxy full-credential user-ID behavior; if the manifest claim changes, the oracle/differential gate applies. UDP domain filtering must reuse the existing lookup and must not change the default `allow_private_egress = true`. CIDR matcher semantics and admin exposure are owned by Routing M003. New listener roles or framing changes require composition validation plus manifest review. ## 11. Completion definition -Protocol coverage closed within tiered boundaries with differential/interop evidence — attained. +Protocol coverage closed within tiered boundaries with differential/interop evidence, plus M003 inbound-auth/UDP security correction closed — attained when both are true. ## 12. Milestone status @@ -91,3 +106,4 @@ Protocol coverage closed within tiered boundaries with differential/interop evid |---|---|---|---|---| | 1 | closed (historical) | archive phase records | archive phase records | — | | 2 | closed (historical) | archive strict/post-parity records | Git history + suite evidence | — | +| 3 | closed | `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` | `plans/closure/protocols-edge/003-status.md` | — | diff --git a/plans/subsystems/routing-health-observability-roadmap.md b/plans/subsystems/routing-health-observability-roadmap.md index 8e3302c8..7e6bafc9 100644 --- a/plans/subsystems/routing-health-observability-roadmap.md +++ b/plans/subsystems/routing-health-observability-roadmap.md @@ -1,6 +1,6 @@ # Routing, Health, Metrics, and Admin Roadmap -Status: closed +Status: closed — M003 CIDR/admin exposure corrective implemented and verified 2026-11-16 Long-term references: @@ -44,6 +44,8 @@ Architecture: `architecture/routing.md`, `architecture/metrics.md`, `architectur All Phase 2 routing/health/operations milestones plus corrective integration tests complete. No active blocker. +A 2026-11-16 security audit found that `destination_cidr`/`source_cidr` matching passes raw `IpAddr` values to `ipnet`, so IPv4 CIDRs do not match IPv4-mapped IPv6 literals, and the docs present CIDR rules as a complete private-network ACL even though domains never match. The admin HTTP surface also has no `Host`/`Origin` validation, so an unauthenticated loopback admin can be read through DNS rebinding; non-loopback admin is plaintext HTTP and the client rejects `https://`. M003 closes the canonical matching gap, makes the literal-only CIDR contract explicit, and adds admin Host/Origin validation plus a plaintext warning. + ## 5. Target architecture Snapshot-shared routing/observability plane with atomic state swaps — attained. @@ -67,21 +69,33 @@ Class: capability. Objective: full Phase 2 scope (rules through reload). Exit: Class: polish. Objective: end-to-end corrective tests (2.11–2.20). Exit: integration evidence green. Status: closed. Evidence: archive phase records + Git history. +### Milestone 3 — CIDR canonicalization and admin exposure + +Class: invariant. Status: closed 2026-11-16 — closure record `plans/closure/routing-health-observability/003-status.md` (coordinator workspace-wide gate passed). + +Implementation plan: + +- `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` + +Objective: canonicalize IPv4-mapped IPv6 before CIDR matching; add a config warning and docs for the literal-only/domain limitation; add `[admin] allowed_hosts` plus Host/Origin validation for DNS-rebinding defense; warn on plaintext non-loopback admin. + +Exit: `::ffff:10.0.0.1` matches `10.0.0.0/8` in destination/source matchers; CIDR rules remain synchronous and literal-only with a warning/docs; admin rejects unexpected Host/Origin while default loopback clients still work; non-loopback admin warns; existing route/admin/auth/limiter tests remain green. No release/tag. + ## 8. Cross-cutting requirements -Config: rule/group/health TOML validation. Compat: translator-generated `[[rules]]`/`[health]` entries diagnosed. Security: bounded metric cardinality, redaction. Concurrency: ArcSwap snapshot reads. Docs: `architecture/routing.md`, `architecture/metrics.md`, `architecture/admin.md`. +Config: rule/group/health TOML validation; M003 adds `admin.allowed_hosts`. Compat: translator-generated `[[rules]]`/`[health]` entries diagnosed. Security: bounded metric cardinality, redaction, canonical CIDR matching, admin Host/Origin validation, plaintext-admin warning. Concurrency: ArcSwap snapshot reads; no DNS or blocking work added to routing. Docs: `architecture/routing.md`, `architecture/metrics.md`, `architecture/admin.md`. ## 9. Verification strategy -`cargo test -p eggress-routing`, `cargo bench --bench route_match` (informational), admin/health integration tests. +`cargo test -p eggress-routing`, `cargo bench --bench route_match` (informational), admin/health integration tests. M003 additionally requires mapped-IPv6 CIDR tests, CIDR-literal-only warning tests, admin Host/Origin/content-type tests, and the plaintext-admin warning. ## 10. Risks and decision points -None active. +CIDR remains literal-IP-only by contract; do not add DNS resolution to route evaluation. Domain private-egress protection belongs to the resolved-target guard (protocols-edge) and upstream trust policy. Admin TLS is not implemented in M003; remote admin remains loopback/VPN/TLS-terminator only, with `allowed_hosts` required for reverse proxies. Default loopback admin access must keep working without configuration. ## 11. Completion definition -Routing/observability plane closed with health-aware selection and ordered lifecycle — attained. +Routing/observability plane closed with health-aware selection and ordered lifecycle, plus M003 CIDR/admin exposure correction closed — attained when both are true. ## 12. Milestone status @@ -89,3 +103,4 @@ Routing/observability plane closed with health-aware selection and ordered lifec |---|---|---|---|---| | 1 | closed (historical) | archive phase records | archive phase records | — | | 2 | closed (historical) | archive corrective records | Git history + suite evidence | — | +| 3 | closed | `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` | `plans/closure/routing-health-observability/003-status.md` | — | diff --git a/plans/subsystems/security-hardening-roadmap.md b/plans/subsystems/security-hardening-roadmap.md new file mode 100644 index 00000000..2aafc5b4 --- /dev/null +++ b/plans/subsystems/security-hardening-roadmap.md @@ -0,0 +1,417 @@ +# Security Hardening Roadmap + +Status: closed (2026-11-16) — corrective security program implemented and verified + +Long-term references: + +- `plans/000-long-term-specification.md` §4 (invariants 2, 3, 7, 8, 9, 10), §6 (end-state acceptance) +- `plans/001-terminology-and-domain-model.md` §2–§4 (listener roles, route/upstream identity, tier vs status) +- `plans/002-long-term-roadmap.md` (dependency-ordered work; no security phase was previously opened) +- `plans/003-planning-process.md` §7 (corrective passes) and §9–§10 (registry/review) + +Related ADRs: + +- `plans/adrs/ADR-0001-planning-conventions.md` (process only) + +## 1. Purpose and ownership boundary + +This roadmap coordinates the corrective security work identified by the +2026-11-16 repository audit. It is a **program**, not a new runtime subsystem: +it owns sequencing, evidence requirements, and cross-subsystem consistency, but +each milestone delegates production changes to the owning subsystem roadmap and +implementation plan. + +It MUST NOT: + +- add new proxy capabilities or change compatibility tiers as a side effect; +- take ownership of protocol framing, routing, admin, transports, or delivery code; +- authorize a version bump, tag, or publication; +- silently relax a canonical invariant to make a finding disappear. + +The owning boundaries remain: + +- TLS/QUIC/SSH mechanics → **transports**; +- listener auth, SOCKS4, UDP target handling, protocol bounds → **protocols-edge**; +- routing matchers and admin HTTP → **routing-health-observability**; +- CLI/updater/release/CI and operator output → **delivery**; +- pproxy translation, manifest/tier claims, and compatibility diagnostics → **parity-compat**. + +Architecture references: `architecture/overview.md`, +`architecture/transports-tls.md`, `architecture/transports-ssh-quic-h3.md`, +`architecture/protocols-socks.md`, `architecture/udp.md`, +`architecture/routing.md`, `architecture/admin.md`, `architecture/cli.md`. + +## 2. Work classification + +### Invariants + +- Outbound TLS verifies the peer against a current, trusted root set; insecure + verification is never the default and is visible when selected. +- Credentials, secret-bearing URIs, TLS private keys, and auth material are + absent from logs, diagnostics, errors, JSON, and Debug output. +- Destination policy fails closed: a policy that says “no private egress” is + enforced after name resolution on every locally resolving path, not only for + literal targets. +- CIDR matching is canonical and family-correct; its contract is explicit about + literal IPs versus names. +- Compatibility authentication follows the pinned pproxy 2.7.9 contract or is + explicitly documented as a supported difference with evidence. +- Dependency advisories are visible in CI and release preflight; unreachable + advisory paths require a narrow, justified, reviewable exception. + +### Capabilities + +No new user-facing capability is introduced. The program preserves existing +SOCKS/HTTP/TLS/UDP/admin/updater behavior while closing bypasses and exposure. + +### Infrastructure + +- A shared destination-policy/address-classification helper where duplication + currently allows UDP and TCP to disagree. +- An advisory gate in CI/release preflight. +- Redacting Debug/serialization for compiled security-sensitive structures. +- In-process updater hashing and private staging mechanics. + +### Polish + +- Security documentation truth: root-store description, unsafe-code statement, + handshake-timeout statement, `--auth` semantics, CIDR limitations, admin + transport, insecure TLS reachability. +- Structured, redacted diagnostics for the corrected paths. + +## 3. Non-goals + +- New proxy protocols, transports, listeners, or routing actions. +- Changing pproxy compatibility tiers without a manifest update plus + oracle/differential/interop evidence. +- Replacing rustls, ring, or the boxed-stream architecture. +- Implementing admin TLS, unified TCP/UDP egress policy, or DNS-aware routing + matchers in this program; these are recorded as residual/deferred decisions. +- Publishing a release or pushing a tag. + +## 4. Current state + +The 2026-11-16 audit found the following corrective items. Severity is the +audit severity; the plans may refine exploitability conditions. + +| ID | Severity | Finding | Owning plan | +|---|---|---|---| +| H1 | High | Bundled TLS roots include a distrusted emSign root and the webpki verifier accepts known-compromised intermediates (CVE-2026-111943) | `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` | +| H2 | High | SOCKS4 auth checks only the username; password is not enforced and success can seed the IP reuse cache | `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` | +| M3 | Medium | `allow_private_egress = false` is bypassable for UDP domain targets; the promised post-DNS check is absent | same protocols-edge plan | +| M4 | Medium | CIDR route rules are bypassable with domain names and IPv4-mapped IPv6 literals; docs present them as a private-network ACL | `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` | +| M5 | Medium | pproxy-compatible auth reuse is always on with a 30-day default and a global IP-keyed cache; security docs misdescribe `--auth` | `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` | +| M6 | Medium | Updater trusts `EGRESS_UPDATE_BASE_URL`/`file://`, PATH-resolved `curl`/`sha256sum`, and a predictable staging directory | `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` | +| M7 | Medium | 21 RustSec advisories in the lockfile; no CI/release advisory gate | delivery 004 plus transports 004/005 | +| M8 | Medium | Password auth can run over plaintext on non-loopback listeners; admin is HTTP-only and rejects `https://` | protocols-edge 003 (listener warning) and routing 003 (admin) | +| L9 | Low | Credential-redaction gaps in compat errors, `translate --annotate`, `system-proxy inspect --json`, and latent Debug | parity 003 and delivery 004 | +| L10 | Low | Private/reserved-IP classification misses CGNAT and IPv4-embedding IPv6 forms | protocols-edge 003 | +| L11 | Low | Insecure TLS is compiled into the default CLI and reachable via `?insecure`, contrary to “API-only” docs | transports 004 | +| L12 | Low | Admin HTTP lacks Host/Origin validation; DNS rebinding can read unauthenticated topology | routing 003 | + +The audit did not find a pre-auth memory-safety RCE. The highest-impact items +are H1 and H2; the rest are policy/enforcement, supply-chain, or exposure +correctives. + +## 5. Target architecture + +The program restores the already-intended boundaries rather than adding a new +security layer: + +1. **Verified transport default.** `eggress-transport-tls` builds outbound TLS + from a current trust store and rejects known-distrusted paths; insecure + verification is explicit, warned, and documented. +2. **One inbound-auth contract per protocol.** SOCKS5/HTTP/H2/WebSocket/reverse + keep their constant-time credential checks; SOCKS4 is aligned with the + pinned pproxy full-credential user-ID semantics instead of username-only + acceptance. +3. **Resolved-target policy.** Locally resolving direct paths apply the same + private/reserved-IP policy after resolution. Upstream chains remain + explicitly trust-dependent because the upstream resolves names. +4. **Canonical routing inputs.** IPv4-mapped IPv6 is normalized before CIDR + matching; CIDR rules remain literal-IP-only and are documented as such. + Private-network protection for names comes from the egress guard, not CIDR. +5. **Explicit operator exposure.** Non-loopback auth without TLS and + non-loopback admin over plaintext HTTP are warned about; admin Host + validation blocks DNS-rebinding reads. +6. **Redacted by construction.** Secret-bearing Debug/serialization and + compatibility diagnostics are redacted at the type or formatter boundary, + not at individual call sites. +7. **Supply-chain visibility.** CI and release preflight run an advisory gate; + optional-feature advisories are either fixed or explicitly accepted with a + tracked upstream dependency. + +## 6. Dependency graph + +```text +S1 TLS trust/advisory remediation (transports 004) + | +S2 russh migration (transports 005) S5 advisory gate (delivery 004) + | ^ + +---------------------------------------------+ + ^ +S6 compat auth/redaction (parity 003) -----------+ + +S3 inbound auth/UDP policy (protocols-edge 003) independent + +S4 CIDR/admin exposure (routing 003) independent +``` + +- **S1 → S5** is a soft dependency: the gate can land with a documented `zip` + exception, but a clean gate needs S1 and S2. +- **S2 → S5** is soft/operational because SSH is an optional feature. +- **S6 → S5** is soft: the gate should not permanently ignore redaction tests. +- **S3/S4** are independent of the dependency upgrades and can proceed in parallel. + +## 7. Milestones + +### Milestone S1 — TLS trust and default-build advisory remediation + +Class: invariant. + +Plan: `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` + +Objective: remove the distrusted-root and webpki verification exposure from the +default outbound TLS graph; upgrade resolvable QUIC/tokio advisories; document +and warn on the insecure TLS surface. + +Dependencies: none hard. `rustls 0.23.46+`, `rustls-webpki 0.103.16+`, +`webpki-roots 1.0.10+` are available; `cargo update` dry-run resolves +`rustls 0.23.46`, `rustls-webpki 0.103.17`, `webpki-roots 1.0.12`, +`quinn 0.11.12`, `quinn-proto 0.11.19`, `quinn-udp 0.5.16`, +`rustls-platform-verifier 0.7.1`, `webpki-root-certs 1.0.12`, and +`tokio 1.54.1`. + +Exit: default TLS verification uses the fixed trust store; the listed default +graph advisories are absent; insecure TLS is documented and warned; transport +tests and broad Rust gates are green. + +### Milestone S2 — SSH dependency advisory migration + +Class: invariant (optional feature). + +Plan: `plans/implementation/transports/005-russh-065-advisory-migration.md` + +Objective: migrate `eggress-transport-ssh` from `russh 0.62.6` to a fixed +`0.65.x` line, preserving known-hosts verification, compatibility host-key +scoping, password/private-key redaction, and the restricted forwarding surface. + +Dependencies: none hard; SSH remains optional. `cargo update` only offers +`russh 0.62.7`, which does not carry the `>=0.63.1`/`>=0.65.0` fixes, so this is +an explicit breaking API migration. + +Exit: `ssh` and `ssh,pproxy-compat` feature slices compile; OpenSSH regression +is required and green where available; no SSH graph advisory remains; no +host-key/auth regression. + +### Milestone S3 — Inbound authentication and UDP destination policy + +Class: invariant. + +Plan: `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` + +Objective: enforce the configured SOCKS4 credential as pproxy does; apply +`allow_private_egress` after DNS on all locally resolving UDP paths; extend +special-purpose address classification; warn when non-loopback password auth +runs without TLS. + +Dependencies: none hard. The SOCKS4 behavior is defined by the pinned pproxy +2.7.9 oracle (`userid in users`, where `users` holds full `user:pass` strings). + +Exit: SOCKS4 username-only and wrong-password connections fail; UDP domains +resolving private are dropped when the policy disallows private egress; +classification tests cover CGNAT/NAT64/6to4/Teredo; listener warning is emitted. + +### Milestone S4 — CIDR canonicalization and admin exposure + +Class: invariant. + +Plan: `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` + +Objective: make CIDR matching family-correct for IPv4-mapped IPv6, make the +literal-only CIDR contract explicit, and block admin DNS-rebinding reads with +Host/Origin validation and a non-loopback plaintext warning. + +Dependencies: none hard. The decision to keep routing CIDR matching literal-only +preserves the existing synchronous route contract; domain private-egress +protection remains the responsibility of the resolved-target guard. + +Exit: `::ffff:10.0.0.1` matches `10.0.0.0/8` in destination and source matchers; +config/docs warn that CIDR does not resolve names; admin rejects unexpected +`Host`/`Origin`; non-loopback admin without TLS is warned; admin tests green. + +### Milestone S5 — Updater trust, advisory gate, and credential-output hardening + +Class: invariant / infrastructure. + +Plan: `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` + +Objective: remove production updater test hooks, make checksum verification +independent of PATH, use private staging, redact `system-proxy inspect --json`, +and add an advisory gate to CI and release preflight. + +Dependencies: S1/S2/S6 soft for a clean gate. The `zip 6.0.0` advisory remains +blocked on an upstream `eggup-archive` release with `zip >= 9.0.0`; the plan +must either carry a narrow documented exception or defer the clean-gate claim. + +Exit: release builds reject `EGRESS_UPDATE_BASE_URL`/`file://`; no PATH-resolved +hash tool; staging is private and non-symlink-following; JSON has no +credentials; the gate runs and any temporary `zip` exception is explicit and +tracked. + +### Milestone S6 — Compatibility auth reuse and redaction + +Class: invariant / polish. + +Plan: `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` + +Objective: make pproxy `--auth` semantics and the global source-IP cache +explicitly documented and warned; redact raw compatibility URIs in errors and +`translate --annotate`; redact compat Debug structures. + +Dependencies: none hard. Any behavior change (rather than documentation/warning) +must update the manifest and run the oracle/differential suite. + +Exit: security-differences docs correctly describe credentials-from-fragment and +`--auth` as the reuse interval; startup warns about the 30-day global IP cache; +raw UDP remote URIs and annotated argv are redacted; compat Debug output hides +`auth_password`. + +## 8. Cross-cutting requirements + +### Config and migration + +- Preserve pproxy-compatible defaults unless a finding requires fail-closed + behavior. New config fields must be optional with secure defaults. +- No listener-topology hot-reload semantics change. +- Admin Host validation must allow configured reverse-proxy hostnames, not only + loopback names. + +### Protocol and compatibility + +- H2 and SOCKS4 behavior changes are compatibility-sensitive. If a manifest + claim changes, update `docs/parity/pproxy_capability_manifest.toml` and run the + oracle/differential/interop suite; generated reports follow the manifest. +- The SOCKS4 full-credential comparison is intended to match the pinned pproxy + behavior, not to introduce a new tier. + +### Security and authorization + +- No credential, private key, or secret may appear in errors, logs, metrics + labels, admin JSON, Debug, or `--annotate`. +- Destination policy failures are fail-closed and observable (metrics/reason), + never a silent fallback. +- Insecure TLS remains opt-in; any warning must not echo credentials. + +### Concurrency, cancellation, and recovery + +- UDP resolution and validation must occur before flow creation and must respect + existing idle/cancellation bounds. +- Admin Host validation must not introduce blocking work in the request path. +- Updater staging must remain safe under concurrent update attempts; use + create-new/private directory semantics. + +### Observability and audit + +- Auth failures remain counted; SOCKS4 failures should join the same metric. +- Advisory-gate exceptions must be visible in `deny.toml` comments and the + registry blocked-work section. +- Security docs are part of closure evidence, not optional polish. + +### Performance and resource use + +- No new DNS resolution on hot paths where a literal target already exists. +- UDP domain validation must reuse the existing lookup result; do not resolve + twice. +- Admin Host checks are constant-time enough for a local operator surface; no + unbounded header parsing is added. + +### Documentation and operations + +- Update the security docs listed in each plan with the code. +- Do not claim a control is enforced when only warned. +- Do not claim “system roots” when bundled roots are used. + +## 9. Verification strategy + +Each plan owns its focused tests. Program-level closure additionally requires: + +```bash +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings +cargo test --workspace --locked +cargo audit --ignore RUSTSEC-2023-0071 +cargo deny check +``` + +Optional-feature slices: + +```bash +cargo check -p eggress-cli --locked --no-default-features \ + --features full,ssh,quic,pproxy-legacy,legacy-crypto,pproxy-daemon --bins +cargo check -p eggress-embed --locked --no-default-features --features ssh +cargo check -p eggress-embed --locked --no-default-features --features pproxy-compat +cargo check -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat +EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked \ + --no-default-features --features ssh,pproxy-compat --test ssh -- --nocapture +``` + +For SOCKS4/auth changes, run the oracle/differential suite only if the manifest +claim changes; if the change restores the existing `matched` claim, add focused +regression evidence and record it in closure. + +## 10. Risks and decision points + +- **`zip` upstream block.** `eggup-archive 0.1.2` and `0.2.0` both pin + `zip = "6.0.0"`; no registry version currently resolves the zip advisories. + The vulnerable `extract()` APIs are not used by Eggup’s bounded extractor, so + the interim risk is accepted only with an explicit gate exception and tracked + upstream dependency. +- **`russh` breaking migration.** `0.65.2` changes `Handler::check_server_key` + to an async/future signature and `PublicKeyOrCertificate`; the SSH feature is + optional, so this can land after the default-graph TLS fix. +- **CIDR domain limitation.** Routing remains literal-only; private-egress + protection for names is enforced by the resolved-target guard, not CIDR. + Upstream chains remain trust-dependent and must be documented. +- **Admin TLS.** This program adds Host/Origin validation and warnings, not + native admin TLS. Remote admin remains a loopback/VPN/TLS-terminator + responsibility. +- **TCP literal private egress.** This program does not change the documented + pproxy-compatible default that allows explicit private IP targets. Any future + unified `allow_private_egress` for TCP is a separate decision. + +## 11. Completion definition + +The program is complete when: + +- every milestone S1–S6 is closed with a closure record and evidence; +- the default and optional feature graphs are advisory-clean, or every remaining + advisory has a narrow, reviewed, expiring exception with a tracked upstream + dependency; +- the security docs agree with code and tests; +- `plans/registry.md` and `docs/ROADMAP.md` agree that no security corrective + milestone remains active; +- no high/medium audit finding remains unclosed or explicitly accepted with a + recorded owner and date. + +## 12. Milestone status + +| Milestone | Status | Implementation plan | Closure record | Blockers | +|---|---|---|---|---| +| S1 TLS trust/default advisories | closed | `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` | `plans/closure/transports/004-status.md` | — | +| S2 SSH `russh` migration | closed | `plans/implementation/transports/005-russh-065-advisory-migration.md` | `plans/closure/transports/005-status.md` | — | +| S3 SOCKS4/UDP/classification | closed | `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` | `plans/closure/protocols-edge/003-status.md` | — | +| S4 CIDR/admin exposure | closed | `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` | `plans/closure/routing-health-observability/003-status.md` | — | +| S5 Updater/advisory gate/output | closed | `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` | `plans/closure/delivery/004-status.md` | Four `zip 6.0.0` advisories remain as a tracked, commented `deny.toml` exception with an owner and review date pending upstream `eggup-archive` with `zip >= 9.0.0` | +| S6 Compat auth/reuse/redaction | closed | `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` | `plans/closure/parity-compat/003-status.md` | — | + +Program disposition (2026-11-16): all six milestones are implemented and their +closure records are `closed`. The coordinator broad gate passed — workspace +`fmt`, `clippy -D warnings`, `test --workspace --locked`, the documented CLI and +embed feature slices, the embed OpenSSH regression, and +`cargo deny --workspace check` (advisories/bans/licenses/sources). The only +remaining audit item is the four `zip 6.0.0` advisories in the updater graph, +tracked as a narrow, commented `deny.toml` exception (owner: Delivery M004; +review by 2027-05-01) pending an upstream `eggup-archive` release with +`zip >= 9.0.0`. No commit, tag, or publication was authorized or created by +this program. diff --git a/plans/subsystems/server-runtime-config-roadmap.md b/plans/subsystems/server-runtime-config-roadmap.md index 558464cd..ae3cac4b 100644 --- a/plans/subsystems/server-runtime-config-roadmap.md +++ b/plans/subsystems/server-runtime-config-roadmap.md @@ -45,6 +45,12 @@ Architecture: `architecture/server.md`, `architecture/runtime.md`, `architecture Runtime supervisor decomposition, lean-runtime phases, and maintenance phases complete. No active lifecycle blocker; 1.0.10 qualified. +Cross-boundary security corrective: Protocols Edge M003 adds a non-fatal +`eggress-config` warning when a non-loopback HTTP/SOCKS listener has password +auth without TLS. This roadmap remains closed for its original scope; the +config-validation change is owned by the Protocols Edge plan and must preserve +the existing warning mechanism and shutdown/reload semantics. + ## 5. Target architecture Snapshot-compiled runtime with atomic reload and ordered shutdown — attained. diff --git a/plans/subsystems/transports-roadmap.md b/plans/subsystems/transports-roadmap.md index eca56ea3..aadaac3c 100644 --- a/plans/subsystems/transports-roadmap.md +++ b/plans/subsystems/transports-roadmap.md @@ -1,6 +1,6 @@ # Transports Roadmap -Status: active — M003 downstream-safe bounded WebSocket composition API ready +Status: active — M003 downstream-safe bounded WebSocket composition API ready; M004/M005 closed 2026-11-16 Long-term references: @@ -47,6 +47,8 @@ H2 physical-session evidence, ALPN preservation, and pooled-transport policy-ide A downstream audit in Eggtunnel found one concrete remaining WebSocket ownership leak: consumers that require an explicit frame/message ceiling must currently pass `tokio_tungstenite::WebSocketConfig` into Eggress's `*_with_config` methods. Eggtunnel therefore carries a direct Tungstenite dependency solely to preserve its 1 MiB hostile-input bound. M003 adds a small implementation-independent bounded WebSocket configuration seam so downstream consumers can remain behind the Eggress adapter boundary. +A 2026-11-16 security audit found the default outbound TLS graph exposed to a distrusted emSign root and known-compromised intermediates (CVE-2026-111943), plus fixable QUIC/tokio advisories. M004 is a lockfile/source-light corrective that upgrades rustls, rustls-webpki, webpki-roots, rustls-platform-verifier, quinn, and tokio, and makes the insecure-TLS surface match its documentation. M005 is a separate breaking migration of the optional `russh` SSH line to 0.65.x for RUSTSEC-2026-0492/-0495 and the `crypto-bigint`/`ctutils` path. Neither milestone changes a pproxy claim; M004 is the release-blocking default-graph fix. + ## 5. Target architecture Policy-scoped, trust-preserving transport upgrades remain behind the boxed boundary. For WebSocket tunnel composition, downstream callers that only need finite transport bounds should not need to name Tungstenite implementation types. M003 closes that remaining public composition seam without changing existing methods or defaults. @@ -58,6 +60,8 @@ TLS upgrade (hard) +--> SSH upstream compat [feature-gated] (soft) +--> QUIC/H3 roles [feature-gated] (soft) +--> H2 pool/ALPN correctives (closed for 1.0.10) + +--> M004 TLS trust/default advisory remediation (closed 2026-11-16) + +--> M005 russh 0.65 advisory migration (closed 2026-11-16, optional ssh) `--> M003 bounded WebSocket composition seam (ready; additive) ``` @@ -83,21 +87,47 @@ Objective: let downstream consumers select finite WebSocket message/frame ceilin Exit: additive client/server over-stream bounded APIs, oversize/backpressure/Ping/close regressions green, downstream-shaped compile evidence with no direct Tungstenite import, broad Rust gates green. Source closure does not imply a release; publication remains a separate maintainer-authorized action. +### Milestone 4 — TLS trust and default-graph advisory remediation + +Class: invariant. Status: closed 2026-11-16 (closure record `plans/closure/transports/004-status.md`; coordinator broad gate passed). + +Implementation plan: + +- `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` + +Objective: move default outbound TLS to fixed rustls/webpki-roots/rustls-webpki versions, upgrade resolvable quinn/tokio advisories, and make insecure TLS truthful in docs/warnings. + +Exit: default TLS no longer trusts the distrusted emSign path; `cargo audit` no longer reports RUSTSEC-2026-0381/-0382 or the named quinn/tokio IDs for the default graph; TLS private keys do not appear in Debug; existing custom-CA/ALPN/mTLS/H2 tests green. No release/tag. + +### Milestone 5 — `russh` 0.65 advisory migration + +Class: invariant (optional `ssh`). Status: closed 2026-11-16 +(closure record `plans/closure/transports/005-status.md`; coordinator broad gate +passed, including the embed OpenSSH regression). + +Implementation plan: + +- `plans/implementation/transports/005-russh-065-advisory-migration.md` + +Objective: move the optional SSH transport to `russh >= 0.65.0`, fixing RUSTSEC-2026-0492/-0495 and the `crypto-bigint`/`ctutils` path while preserving known-hosts policy, insecure compatibility scoping, redaction, and the restricted forwarding surface. + +Exit: `ssh` and `ssh,pproxy-compat` compile; OpenSSH regression is green where required; no SSH graph advisory remains; default feature graph and pproxy claims unchanged. No release/tag. + ## 8. Cross-cutting requirements Config: per-hop TLS/SSH/QUIC validation; insecure combinations rejected explicitly. Compat: manifest transport entries. Security: trust-policy isolation, no silent insecure substitution. Concurrency: pool scoping under route isolation. Docs: transport deep dives. ## 9. Verification strategy -Transport unit tests (including `custom_ca_tls_override_survives_h2_alpn_adaptation`, `h2_pool_does_not_cross_*`, `tls_override_plus_insecure_fails_closed*`), `cargo bench --bench tls_setup` (informational), feature-gated CLI check for `ssh,quic` paths. +Transport unit tests (including `custom_ca_tls_override_survives_h2_alpn_adaptation`, `h2_pool_does_not_cross_*`, `tls_override_plus_insecure_fails_closed*`), `cargo bench --bench tls_setup` (informational), feature-gated CLI check for `ssh,quic` paths. M004 additionally requires `cargo audit`/`cargo deny` evidence for the TLS/QUIC/tokio graph; M005 requires the embed OpenSSH regression with `ssh,pproxy-compat`. ## 10. Risks and decision points -None active. New reuse/pooling semantics require evidence and must not change the 64 KiB relay buffer or add UDP pooling without proof. +M004's TLS upgrade is release-blocking and source-light; do not widen it into a rustls architecture change. M005 is an optional breaking `russh` migration and must not weaken known-hosts defaults. `zip` remains a delivery/upstream blocker, not a transport dependency. New reuse/pooling semantics require evidence and must not change the 64 KiB relay buffer or add UDP pooling without proof. ## 11. Completion definition -Transport upgrades trust-preserving and policy-scoped with 1.0.10 evidence — attained. +Transport upgrades trust-preserving and policy-scoped with 1.0.10 evidence, plus M004/M005 advisory closure — attained when both security correctives are closed. ## 12. Milestone status @@ -106,3 +136,5 @@ Transport upgrades trust-preserving and policy-scoped with 1.0.10 evidence — a | 1 | closed (historical) | archive phase records | archive phase records | — | | 2 | closed | archive H2/pool/ALPN records | §Controlling evidence in `plans/registry.md` | — | | 3 | ready | `plans/implementation/transports/003-downstream-safe-bounded-websocket-composition-api.md` | pending | Published v1.0.11 baseline; no hard blocker. | +| 4 | closed | `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` | `plans/closure/transports/004-status.md` | — | +| 5 | closed | `plans/implementation/transports/005-russh-065-advisory-migration.md` | `plans/closure/transports/005-status.md` | — | diff --git a/scripts/release-preflight.sh b/scripts/release-preflight.sh index 026fde1d..ec8b1232 100755 --- a/scripts/release-preflight.sh +++ b/scripts/release-preflight.sh @@ -18,6 +18,11 @@ # 6. the checked-out commit is exactly the tagged commit; # 7. the working tree is clean (local/manual mode; CI checkouts are clean). # +# This script is offline and gate-only for version/tag coherence. The dependency +# advisory gate (`cargo deny --workspace check`, Delivery M004) runs right after +# it in the `release-binaries.yml` preflight job and is also reproduced by the +# CI `advisories` job; run it locally with the same command before tagging. +# # The binary release workflow builds from the tag commit, never from whatever # happens to be the default-branch head. Manual dispatch must supply an # existing tag; it never synthesizes an untagged production release. From 97b0d107473eb191f632fb56d1b19dce9f795b69 Mon Sep 17 00:00:00 2001 From: CI Test Date: Tue, 17 Nov 2026 13:16:48 +0000 Subject: [PATCH 2/2] ci: track 2026-11-17 RustSec advisories in the advisory gate The advisory database published RUSTSEC-2026-0545/-0547/-0548 (zip 6.0.0) and RUSTSEC-2026-0543 (chrono unmaintained via russh-util) after the security-corrective closure. All are unreachable-by-feature or unmaintained-only and remain blocked upstream: - zip: eggup-archive pins 6.0.0; Eggress verifies the archive SHA-256, uses no extract()/ZipStreamReader API, and Eggup disables aes-crypto. - chrono: unconditional russh-util dependency in the latest russh 0.65.2; reachable only through the optional ssh feature. Add narrow, commented ignores with owners and 2027-05-01 review dates and record the changed residual set in the closure records, registry, roadmap, and CI/release docs. --- deny.toml | 28 +++++++++++++++++-- docs/CI_STATUS.md | 2 +- docs/ROADMAP.md | 13 +++++---- docs/release/RELEASE_PROCESS.md | 5 ++-- docs/security/SECURE_CONFIGURATION.md | 5 ++-- plans/closure/delivery/004-status.md | 8 ++++-- plans/closure/transports/004-status.md | 8 ++++-- plans/closure/transports/005-status.md | 10 ++++++- plans/registry.md | 9 +++--- .../subsystems/security-hardening-roadmap.md | 17 +++++------ 10 files changed, 73 insertions(+), 32 deletions(-) diff --git a/deny.toml b/deny.toml index 3af4220b..8530fa9a 100644 --- a/deny.toml +++ b/deny.toml @@ -32,16 +32,38 @@ ignore = [ # members through object-bound handles under finite size limits. Eggress # additionally verifies the whole archive SHA-256 before extraction. # - # Removal condition: delete these four entries (do not carry them + # Advisories published after the gate landed (2026-11-17) are covered by + # the same upstream block and are not reachable through Eggup's feature + # set: `eggup-archive` disables `zip` defaults and enables only + # `deflate-flate2`, so the `aes-crypto` path (-0545) is not compiled; it + # never uses `ZipStreamReader` (-0548); and the -0547 legacy decoders are + # outside the supported release-asset entry set, with the archive + # SHA-256-verified before extraction and members read under finite + # per-member/total limits. + # + # Removal condition: delete every `zip` entry here (do not carry them # forward) as soon as an `eggup-archive` release depending on # `zip >= 9.0.0` is adopted. # - # Owner: Delivery M004. Reviewed 2026-11-16. Re-review by 2027-05-01 - # even if no upstream release has landed; do not renew silently. + # Owner: Delivery M004. Reviewed 2026-11-16, extended 2026-11-17. + # Re-review by 2027-05-01 even if no upstream release has landed; do not + # renew silently. "RUSTSEC-2026-0367", "RUSTSEC-2026-0368", "RUSTSEC-2026-0369", "RUSTSEC-2026-0429", + "RUSTSEC-2026-0545", + "RUSTSEC-2026-0547", + "RUSTSEC-2026-0548", + # `chrono` is unmaintained (RUSTSEC-2026-0543), not a vulnerability. It is + # pulled unconditionally by `russh-util 0.52.0` -> `russh 0.65.2`, which + # is the latest published `russh` line and the fixed line for the SSH + # advisories this program closed. Reachable only through the optional + # `ssh` feature; no safe upgrade exists. + # + # Owner: Transports M005. Reviewed 2026-11-17. Re-review at the next + # `russh`/`russh-util` release or by 2027-05-01, whichever comes first. + "RUSTSEC-2026-0543", ] # `rustls-pemfile` (RUSTSEC-2025-0134) was replaced by `rustls-pki-types` PEM diff --git a/docs/CI_STATUS.md b/docs/CI_STATUS.md index 12ceebc5..8240aea9 100644 --- a/docs/CI_STATUS.md +++ b/docs/CI_STATUS.md @@ -113,7 +113,7 @@ Run these only when their trigger condition applies: The commands remain documented in `docs/TESTING.md`, `docs/DIFFERENTIAL_TESTING.md`, and `AGENTS.md`. Their existence does not make them routine merge gates. -The advisory gate runs `cargo deny --workspace check`, not a bare `cargo deny check`: the root manifest is the `eggress-bench` package (not a virtual manifest), so a root-only graph silently omits `eggress-cli` — and with it `eggup-archive -> zip` — and prints a misleading `advisories ok`. `deny.toml` sets `[graph] all-features = true` so optional-only dependencies (`russh`, QUIC/H3, the `zip` subtree) are scanned as well. `deny.toml` carries exactly four commented `zip 6.0.0` ignores; add nothing to that list without the same owner/removal-condition treatment. +The advisory gate runs `cargo deny --workspace check`, not a bare `cargo deny check`: the root manifest is the `eggress-bench` package (not a virtual manifest), so a root-only graph silently omits `eggress-cli` — and with it `eggup-archive -> zip` — and prints a misleading `advisories ok`. `deny.toml` sets `[graph] all-features = true` so optional-only dependencies (`russh`, QUIC/H3, the `zip` subtree) are scanned as well. `deny.toml` carries seven commented `zip 6.0.0` ignores plus one commented `chrono`/`russh-util` ignore (unmaintained only, optional `ssh`); add nothing to that list without the same owner/removal-condition treatment. ## Evidence and completion records diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index d8d237c7..a052d589 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -116,12 +116,13 @@ tiers. ([closure](../plans/closure/parity-compat/003-status.md)). The workspace `fmt`/`clippy`/`test` gate, the documented feature slices, the -embed OpenSSH regression, and `cargo deny --workspace check` all pass. The only -remaining audit item is the four `zip 6.0.0` advisories in the updater graph, -tracked as a narrow, commented `deny.toml` exception with an owner and review -date pending an upstream `eggup-archive` release with `zip >= 9.0.0`. No version -bump, tag, or publication was authorized; `v1.0.12` remains the current -published release. +embed OpenSSH regression, and `cargo deny --workspace check` all pass. The +remaining audit items are the seven `zip 6.0.0` advisories in the updater graph +and the unmaintained `chrono` transitive through `russh-util` on the optional +`ssh` path, both tracked as narrow, commented `deny.toml` exceptions with owners +and a 2027-05-01 review date pending an upstream `eggup-archive` release with +`zip >= 9.0.0` and a `russh`/`russh-util` update. No version bump, tag, or +publication was authorized; `v1.0.12` remains the current published release. ### Active maintenance — Eggup archive/pair self-update convergence diff --git a/docs/release/RELEASE_PROCESS.md b/docs/release/RELEASE_PROCESS.md index e3a34210..02819618 100644 --- a/docs/release/RELEASE_PROCESS.md +++ b/docs/release/RELEASE_PROCESS.md @@ -59,8 +59,9 @@ cargo audit --ignore RUSTSEC-2023-0071 package, so a bare `cargo deny check` roots the graph there and silently skips `eggress-cli` (and `eggup-archive -> zip`), printing a misleading `advisories ok`. `deny.toml` audits the all-features graph and carries only the -tracked `zip 6.0.0` ignores; the release workflow runs the same command in its -preflight job, so a tag cannot ship with an unreviewed advisory. +tracked `zip 6.0.0` ignores plus the unmaintained `chrono`/`russh-util` ignore; +the release workflow runs the same command in its preflight job, so a tag +cannot ship with an unreviewed advisory. Run specialized interoperability, Python, performance, or cross-platform checks only when the release contains relevant changes or makes claims that depend on them. The selection policy is in `docs/TESTING.md`. For example, a release containing SSH/embed changes must run the required OpenSSH embed regression (`EGRESS_REQUIRE_OPENSSH_TESTS=1 cargo test -p eggress-embed --locked --no-default-features --features ssh,pproxy-compat --test ssh`); a skipped fixture is not release evidence for such a version. diff --git a/docs/security/SECURE_CONFIGURATION.md b/docs/security/SECURE_CONFIGURATION.md index 02bd50bf..b6657557 100644 --- a/docs/security/SECURE_CONFIGURATION.md +++ b/docs/security/SECURE_CONFIGURATION.md @@ -266,8 +266,9 @@ candidate verification. Its trust boundary is deliberately narrow: download with a remediation message. - **Advisories are gated.** CI and the release preflight run `cargo deny --workspace check`. The only ignores are the tracked - `zip 6.0.0` advisories inherited from `eggup-archive`; they are listed with - their removal condition in `deny.toml`. + `zip 6.0.0` advisories inherited from `eggup-archive` and the unmaintained + `chrono` transitive through the optional `ssh` path (`russh-util`); both are + listed with owners and removal/review conditions in `deny.toml`. For a fully operator-controlled deployment, prefer the OS package flow (install to a root-owned directory, update through the package manager) and let diff --git a/plans/closure/delivery/004-status.md b/plans/closure/delivery/004-status.md index 356b9b32..1e697ac7 100644 --- a/plans/closure/delivery/004-status.md +++ b/plans/closure/delivery/004-status.md @@ -171,6 +171,10 @@ cargo deny --workspace check — exactly `RUSTSEC-2026-0429`, `-0367`, `-0368`, `-0369`, all `zip 6.0.0` (`patched >= 9.0.0`), plus 1 allowed warning (`wnaf 0.14.0` yanked). `RUSTSEC-2026-0486` (rustix) is gone after the 1.1.6 update. + Advisory-database note (2026-11-17): `RUSTSEC-2026-0545`, `-0547`, and `-0548` + (all `zip 6.0.0`) were published after this run and added to the same tracked + exception; `cargo audit` now reports 7 `zip` vulnerabilities plus the + unmaintained `chrono` warning tracked by Transports M005. See §10. - `cargo deny --workspace check`: `advisories ok, bans ok, licenses ok, sources ok`; zero `advisory-not-detected` warnings (all four ignores matched `zip 6.0.0` nodes); remaining output is warnings only (duplicate versions, @@ -286,8 +290,8 @@ reports only the four tracked `zip 6.0.0` advisories. The condition recorded in | low | Bare `cargo deny check` still prints `advisories ok` while skipping `eggress-cli`/`zip` (root-package graph) | A maintainer running the wrong command can believe the gate passed | Mitigated: CI/preflight/docs all use `cargo deny --workspace check`, and `deny.toml` documents the trap. Consider making `--workspace` the only documented form in `AGENTS.md` at the next docs pass. | | low | `tempfile`'s default directory mode is umask-derived (`0755`), not `0700` | Would have left staged archives readable by other local users | Fixed: `staging_dir()` passes an explicit `0700` mode; asserted by test | | low | `Apache-2.0 WITH LLVM-exception` (`target-lexicon`, via `pyo3-build-config`) had to be allow-listed once the gate scanned the whole workspace | Gate could not pass without it | Fixed in `deny.toml`; permissive license, no policy change | -| medium | Four `zip 6.0.0` advisories remain in the updater graph | Upstream `eggup-archive` blocker; Eggup's bounded extractor does not call the vulnerable `extract()` APIs and Eggress verifies the whole-archive SHA-256 first | Tracked as a narrow commented `deny.toml` exception; remove when `eggup-archive` depends on `zip >= 9.0.0` | -| low | Workspace-wide fmt/clippy/test gate not run in this wave | Cross-crate regressions outside the touched crates would be caught later | Coordinator runs it after all corrective waves | +| medium | Seven `zip 6.0.0` advisories remain in the updater graph (four at closure; RUSTSEC-2026-0545/-0547/-0548 published 2026-11-17 and added to the same tracked exception) | Upstream `eggup-archive` blocker; Eggup's bounded extractor does not call the vulnerable `extract()`/`ZipStreamReader` APIs, disables `aes-crypto`, and Eggress verifies the whole-archive SHA-256 first | Tracked as a narrow commented `deny.toml` exception; remove when `eggup-archive` depends on `zip >= 9.0.0` | +| low | Workspace-wide fmt/clippy/test gate not run in this wave | Cross-crate regressions outside the touched crates would be caught later | Coordinator ran it after all corrective waves (recorded in §4) | ## 11. Roadmap disposition diff --git a/plans/closure/transports/004-status.md b/plans/closure/transports/004-status.md index daa74fe0..f01f1246 100644 --- a/plans/closure/transports/004-status.md +++ b/plans/closure/transports/004-status.md @@ -298,9 +298,11 @@ reports only the four tracked `zip 6.0.0` advisories. The condition recorded in Post-wave note (2026-11-16): the `russh`/`crypto-bigint`/`ctutils` and `zip` findings listed above are owned by Transports M005 and Delivery M004. M005 -cleared the SSH graph, and M004 added the advisory gate with a tracked `zip` -exception and cleared the `rustix` advisory via `rustix 1.1.6`. No finding in -this table remains open for M004 scope. +cleared the SSH vulnerability set, and M004 added the advisory gate with a +tracked `zip` exception and cleared the `rustix` advisory via `rustix 1.1.6`. +A later unmaintained-only advisory (`chrono`, RUSTSEC-2026-0543, published +2026-11-17) is tracked in M005. No finding in this table remains open for M004 +scope. ## 11. Roadmap disposition diff --git a/plans/closure/transports/005-status.md b/plans/closure/transports/005-status.md index 58ddbeea..0028d987 100644 --- a/plans/closure/transports/005-status.md +++ b/plans/closure/transports/005-status.md @@ -170,6 +170,7 @@ Remaining `cargo audit` findings: | `zip 6.0.0` | RUSTSEC-2026-0369 | Delivery M004 | | `rustix 1.1.4` | RUSTSEC-2026-0486 (`unsound` warning, not a vulnerability) | Pre-existing via `tempfile`; unchanged here | | `wnaf 0.14.0` | yanked (warning only) | Pre-existing; not on the SSH path | +| `chrono 0.4.45` | RUSTSEC-2026-0543 (unmaintained, published 2026-11-17) | Transports M005 (`russh-util` is unconditional; optional `ssh` only; no safe upgrade) | **Coordinator broad gate (2026-11-16, after all six corrective waves):** pass — `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, @@ -300,9 +301,16 @@ reports only the four tracked `zip 6.0.0` advisories. The condition recorded in Post-wave note (2026-11-16): the `rustix` advisory was cleared by the `rustix 1.1.6` update in Delivery M004, and the `cargo deny` graph-scope finding was -fixed by the `cargo deny --workspace check` gate in M004. The four `zip` +fixed by the `cargo deny --workspace check` gate in M004. The seven `zip` advisories remain tracked there. +Advisory-database note (2026-11-17): RUSTSEC-2026-0543 (`chrono` unmaintained) +was published after this closure. It is not a vulnerability, is reachable only +through the optional `ssh` feature, and has no safe upgrade because +`russh-util 0.52.0` is unconditional in `russh 0.65.2` (the latest published +line). It is added to the narrow `deny.toml` exception with owner Transports +M005 and a 2027-05-01 review date; the SSH *vulnerability* set remains closed. + ## 11. Roadmap disposition **Closed.** Production implementation for Transports M005 is complete: the diff --git a/plans/registry.md b/plans/registry.md index 0e7c8bba..1964c166 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -34,8 +34,8 @@ Complementary authority: `docs/ROADMAP.md` (canonical roadmap), `docs/parity/ppr | Transports | active | `plans/subsystems/transports-roadmap.md` | M003 downstream-safe WebSocket API | M004/M005 closed 2026-11-16; M003 remains ready (additive, no hard blocker). | | Outbound chains and connectors | closed | `plans/subsystems/outbound-chains-roadmap.md` | All milestones closed; pooled-transport/H2/ALPN correctives qualified | None. | | Parity contract and compatibility translation | closed | `plans/subsystems/parity-compat-roadmap.md` | All milestones closed; M003 auth reuse/redaction qualified | Manifest claim unchanged; `check --json` raw-field follow-up tracked in the closure record. | -| Delivery (CLI, embed, Python, release) | closed | `plans/subsystems/delivery-roadmap.md` | All milestones closed; M004 updater trust/advisory gate qualified | M003 closed 2026-09-29 (`plans/closure/delivery/003-status.md`); M004 closed 2026-11-16 (`plans/closure/delivery/004-status.md`) with four `zip` advisories tracked in `deny.toml` (owner/review date recorded); `v1.0.12` published 2026-10-08; next version bump is a separate maintainer-authorized release action. | -| Security hardening (cross-cutting corrective) | closed (2026-11-16) | `plans/subsystems/security-hardening-roadmap.md` | S1–S6 implemented and verified | Four `zip 6.0.0` advisories remain as a narrow, commented `deny.toml` exception with owner and review date pending upstream `eggup-archive`; no release authorized. | +| Delivery (CLI, embed, Python, release) | closed | `plans/subsystems/delivery-roadmap.md` | All milestones closed; M004 updater trust/advisory gate qualified | M003 closed 2026-09-29 (`plans/closure/delivery/003-status.md`); M004 closed 2026-11-16 (`plans/closure/delivery/004-status.md`) with seven `zip` advisories tracked in `deny.toml` (owner/review date recorded); `v1.0.12` published 2026-10-08; next version bump is a separate maintainer-authorized release action. | +| Security hardening (cross-cutting corrective) | closed (2026-11-16) | `plans/subsystems/security-hardening-roadmap.md` | S1–S6 implemented and verified | Seven `zip 6.0.0` advisories plus the unmaintained `chrono` transitive (`russh-util`) remain as narrow, commented `deny.toml` exceptions with owner and review date; no release authorized. | ## Implementation plans and dependency state @@ -63,13 +63,14 @@ coordinator broad gate. Delivery M003 landed and closed 2026-09-29 **Verification gate:** `docs/CI_STATUS.md` owns verification policy; `docs/TESTING.md` owns the suite inventory. Ordinary changes use the narrowest test first, then the broad gate before merging substantial Rust changes. -**Security corrective gate (closed 2026-11-16):** the 2026-11-16 audit corrective program at `plans/subsystems/security-hardening-roadmap.md` is implemented and verified. S1 removed the distrusted-root/webpki exposure and the default-graph TLS/QUIC/tokio advisories; S2 moved optional SSH to `russh 0.65.2`; S3 restored pproxy SOCKS4 full-credential semantics and enforced UDP private-egress policy after DNS; S4 canonicalized CIDR matching and added admin Host/Origin validation; S5 hardened the updater and added the advisory gate; S6 corrected the compatibility auth-reuse contract and redacted compat diagnostics. The only remaining audit item is the four `zip 6.0.0` advisories in the updater graph, tracked as a narrow, commented `deny.toml` exception (owner: Delivery M004; review by 2027-05-01) pending upstream `eggup-archive` with `zip >= 9.0.0`. No tag or publication is authorized by these plans. +**Security corrective gate (closed 2026-11-16):** the 2026-11-16 audit corrective program at `plans/subsystems/security-hardening-roadmap.md` is implemented and verified. S1 removed the distrusted-root/webpki exposure and the default-graph TLS/QUIC/tokio advisories; S2 moved optional SSH to `russh 0.65.2`; S3 restored pproxy SOCKS4 full-credential semantics and enforced UDP private-egress policy after DNS; S4 canonicalized CIDR matching and added admin Host/Origin validation; S5 hardened the updater and added the advisory gate; S6 corrected the compatibility auth-reuse contract and redacted compat diagnostics. The remaining audit items are the seven `zip 6.0.0` advisories in the updater graph (owner: Delivery M004) and the unmaintained `chrono` transitive through `russh-util` on the optional `ssh` path (owner: Transports M005), both tracked as narrow, commented `deny.toml` exceptions with review by 2027-05-01. No tag or publication is authorized by these plans. **Eggup updater-convergence gate (closed 2026-09-28; consumer landed 2026-09-29):** Delivery M003 is registered at `plans/implementation/delivery/003-eggup-archive-pair-self-update-adoption.md` and closed in `plans/closure/delivery/003-status.md`. Eggup Archive M001d is runtime-qualified (`eggstack/eggup@18d83de`, hosted run `36335233644`), and the required post-M001d APIs shipped as compatible registry packages: `eggup-core 0.1.2` + `eggup-archive 0.1.2` (Eggup M009 closure, `eggstack/eggup@v0.1.2`). The final Cargo dependency cutover landed against the registry versions with hosted Linux/macOS/Windows updater evidence. Eggress release/checksum/version/CLI policy remains local. ## Blocked work -- **`zip 6.0.0` / `eggup-archive` (tracked residual)** — RUSTSEC-2026-0429/-0367/-0368/-0369 remain in the updater dependency graph. `eggup-archive 0.1.2` and `0.2.0` pin `zip = "6.0.0"`; an upstream Eggup release with `zip >= 9.0.0` is required. The vulnerable `ZipArchive::extract` APIs are not used by Eggup's bounded extractor, so the advisory gate carries a narrow, commented exception with owner (Delivery M004) and review date (2027-05-01); delete it when the upstream dependency lands. `cargo deny --workspace check` passes on 2026-11-16 with exactly this exception. +- **`zip 6.0.0` / `eggup-archive` (tracked residual)** — RUSTSEC-2026-0429/-0367/-0368/-0369 and, published 2026-11-17, -0545/-0547/-0548 remain in the updater dependency graph. `eggup-archive 0.1.2` and `0.2.0` pin `zip = "6.0.0"`; an upstream Eggup release with `zip >= 9.0.0` is required. The vulnerable `extract`/`ZipStreamReader` APIs are not used by Eggup's bounded extractor and `aes-crypto` is disabled, so the advisory gate carries a narrow, commented exception with owner (Delivery M004) and review date (2027-05-01); delete it when the upstream dependency lands. +- **`chrono` unmaintained / `russh-util` (tracked residual)** — RUSTSEC-2026-0543 is unmaintained (not a vulnerability) and is pulled unconditionally by `russh-util 0.52.0` through `russh 0.65.2`, the latest published and fixed SSH line. Reachable only through the optional `ssh` feature; no safe upgrade exists. Narrow, commented exception with owner (Transports M005) and review by 2027-05-01. `cargo deny --workspace check` passes on 2026-11-17 with exactly these exceptions. ## Closure work and current control points diff --git a/plans/subsystems/security-hardening-roadmap.md b/plans/subsystems/security-hardening-roadmap.md index 2aafc5b4..e0e3a266 100644 --- a/plans/subsystems/security-hardening-roadmap.md +++ b/plans/subsystems/security-hardening-roadmap.md @@ -399,19 +399,20 @@ The program is complete when: | Milestone | Status | Implementation plan | Closure record | Blockers | |---|---|---|---|---| | S1 TLS trust/default advisories | closed | `plans/implementation/transports/004-tls-trust-and-dependency-advisory-remediation.md` | `plans/closure/transports/004-status.md` | — | -| S2 SSH `russh` migration | closed | `plans/implementation/transports/005-russh-065-advisory-migration.md` | `plans/closure/transports/005-status.md` | — | +| S2 SSH `russh` migration | closed | `plans/implementation/transports/005-russh-065-advisory-migration.md` | `plans/closure/transports/005-status.md` | RUSTSEC-2026-0543 (`chrono` unmaintained via `russh-util`) is a tracked, commented `deny.toml` exception with owner and review date; optional `ssh` only | | S3 SOCKS4/UDP/classification | closed | `plans/implementation/protocols-edge/003-socks4-auth-and-udp-private-egress.md` | `plans/closure/protocols-edge/003-status.md` | — | | S4 CIDR/admin exposure | closed | `plans/implementation/routing-health-observability/003-cidr-canonicalization-and-admin-exposure.md` | `plans/closure/routing-health-observability/003-status.md` | — | -| S5 Updater/advisory gate/output | closed | `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` | `plans/closure/delivery/004-status.md` | Four `zip 6.0.0` advisories remain as a tracked, commented `deny.toml` exception with an owner and review date pending upstream `eggup-archive` with `zip >= 9.0.0` | +| S5 Updater/advisory gate/output | closed | `plans/implementation/delivery/004-updater-trust-and-advisory-gate.md` | `plans/closure/delivery/004-status.md` | Seven `zip 6.0.0` advisories remain as a tracked, commented `deny.toml` exception with an owner and review date pending upstream `eggup-archive` with `zip >= 9.0.0` | | S6 Compat auth/reuse/redaction | closed | `plans/implementation/parity-compat/003-auth-reuse-and-compat-redaction.md` | `plans/closure/parity-compat/003-status.md` | — | Program disposition (2026-11-16): all six milestones are implemented and their closure records are `closed`. The coordinator broad gate passed — workspace `fmt`, `clippy -D warnings`, `test --workspace --locked`, the documented CLI and embed feature slices, the embed OpenSSH regression, and -`cargo deny --workspace check` (advisories/bans/licenses/sources). The only -remaining audit item is the four `zip 6.0.0` advisories in the updater graph, -tracked as a narrow, commented `deny.toml` exception (owner: Delivery M004; -review by 2027-05-01) pending an upstream `eggup-archive` release with -`zip >= 9.0.0`. No commit, tag, or publication was authorized or created by -this program. +`cargo deny --workspace check` (advisories/bans/licenses/sources). The +remaining audit items are the seven `zip 6.0.0` advisories in the updater graph +and the unmaintained `chrono` transitive through `russh-util` on the optional +`ssh` path, both tracked as narrow, commented `deny.toml` exceptions with owners +and a 2027-05-01 review date pending an upstream `eggup-archive` release with +`zip >= 9.0.0` and a `russh`/`russh-util` update. No commit, tag, or publication +was authorized or created by this program.