From 86a87036ed5e1249dcc8aca0a5e64a57dc901ab1 Mon Sep 17 00:00:00 2001 From: PQCrypta Date: Sat, 5 Dec 2026 19:35:54 -0600 Subject: [PATCH] fix(admin): the canary action reads its body with the JSON extractor; fix(security): keys, nonces and tokens from AWS-LC's DRBG admin: POST /pools/{pool}/servers/{id}/canary has its own route, matched ahead of the other pool actions, and reads {"weight": n} through axum's JSON extractor: only as application/json, only the fields the request names; no body is still the pool's ramp. The other actions read no body. security: src/secure_random.rs draws every key, nonce and token (the generated admin token, signing nonces, challenge secrets, request and session IDs, DNS message IDs, WebSocket keys) from AWS-LC's CTR-DRBG, the generator the TLS stack uses; rand stays for choices that protect nothing, through rand::random_range, and clippy refuses rand::random and rand::fill. licensing: REUSE 3.3: LICENSES/ and REUSE.toml name every file's licence and copyright, each vendored fork its upstream's; CI checks it. ci: a Coverage job (cargo-llvm-cov, the proxy's own code); CI and CodeQL run on each release PR, which Release Please opens with a token that starts no workflow; the unused release job, which uploaded archives without provenance, is gone. docs: docs/SECURE-DESIGN.md (principles, common errors and their countermeasures) and docs/CRYPTOGRAPHY.md (libraries, defaults, key lengths, randomness, protocol-mandated legacy algorithms); CONTRIBUTING.md states the test policy and the checks; SECURITY.md links the advisories and the design; .github/SECURITY.md, an older policy GitHub showed in place of SECURITY.md, is removed; each release that fixed a published advisory lists it under Security in CHANGELOG.md; .bestpractices.json holds the OpenSSF Best Practices answers. BEGIN_COMMIT_OVERRIDE fix(admin): the canary action has a route of its own and reads its body with the JSON extractor, as application/json with known fields only fix(security): every key, nonce and token is drawn from AWS-LC's DRBG (secure_random); rand is kept for choices that protect nothing END_COMMIT_OVERRIDE --- .bestpractices.json | 136 ++++++++++++ .github/SECURITY.md | 64 ------ .github/workflows/ci.yml | 81 +++++-- .github/workflows/codeql.yml | 3 + .github/workflows/release-please.yml | 24 ++ CHANGELOG.md | 33 +++ CONTRIBUTING.md | 314 +++++++++------------------ LICENSES/Apache-2.0.txt | 73 +++++++ LICENSES/BSD-2-Clause.txt | 9 + LICENSES/ISC.txt | 7 + LICENSES/MIT.txt | 18 ++ README.md | 8 +- REUSE.toml | 65 ++++++ SECURITY.md | 17 ++ clippy.toml | 9 + docs/CRYPTOGRAPHY.md | 105 +++++++++ docs/SECURE-DESIGN.md | 70 ++++++ examples/speedtest-probe.rs | 6 +- src/acme_dns.rs | 4 +- src/admin.rs | 232 +++++++++++++++----- src/admin_client.rs | 2 +- src/bin/ech-keygen.rs | 2 +- src/challenge.rs | 6 +- src/conformance/session.rs | 9 +- src/connect_ip.rs | 2 +- src/host_names.rs | 2 +- src/http_listener/mod.rs | 2 +- src/lib.rs | 1 + src/load_balancer.rs | 2 +- src/quic_listener/mod.rs | 2 +- src/rate_limiter.rs | 2 +- src/request_id.rs | 5 +- src/route_gate.rs | 6 +- src/secure_random.rs | 154 +++++++++++++ src/telemetry.rs | 6 +- src/ws_tunnel.rs | 3 +- 36 files changed, 1094 insertions(+), 390 deletions(-) create mode 100644 .bestpractices.json delete mode 100644 .github/SECURITY.md create mode 100644 LICENSES/Apache-2.0.txt create mode 100644 LICENSES/BSD-2-Clause.txt create mode 100644 LICENSES/ISC.txt create mode 100644 LICENSES/MIT.txt create mode 100644 REUSE.toml create mode 100644 docs/CRYPTOGRAPHY.md create mode 100644 docs/SECURE-DESIGN.md create mode 100644 src/secure_random.rs diff --git a/.bestpractices.json b/.bestpractices.json new file mode 100644 index 00000000..6b4ffc5a --- /dev/null +++ b/.bestpractices.json @@ -0,0 +1,136 @@ +{ + "description_good_status": "Met", + "description_good_justification": "The README opens by saying what the software is and does: an HTTP/3, QUIC and WebTransport reverse proxy with hybrid post-quantum TLS. https://github.com/PQCrypta/pqcrypta-proxy#readme", + "interact_status": "Met", + "interact_justification": "Obtain: the README's Quick Start and the release page (https://github.com/PQCrypta/pqcrypta-proxy#quick-start, https://github.com/PQCrypta/pqcrypta-proxy/releases). Feedback: GitHub Issues and Discussions. Contribute: CONTRIBUTING.md. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#reporting", + "contribution_status": "Met", + "contribution_justification": "CONTRIBUTING.md describes the process: fork, branch from main, run the CI checks, open a pull request, review, merge. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#making-a-change", + "contribution_requirements_status": "Met", + "contribution_requirements_justification": "CONTRIBUTING.md sets the requirements: tests with every change, rustfmt, clippy pedantic/nursery with no warnings, unsafe only at C/kernel boundaries, documentation, and the checks every PR passes. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#what-a-change-must-meet", + "floss_license_status": "Met", + "floss_license_justification": "MIT OR Apache-2.0, at the user's option.", + "floss_license_osi_status": "Met", + "floss_license_osi_justification": "MIT and Apache-2.0 are both OSI-approved.", + "license_location_status": "Met", + "license_location_justification": "LICENSE-APACHE and LICENSE-MIT at the top of the repository, the licence texts in LICENSES/, and every file's licence in REUSE.toml (REUSE 3.3, checked in CI). https://github.com/PQCrypta/pqcrypta-proxy/tree/main/LICENSES", + "documentation_basics_status": "Met", + "documentation_basics_justification": "The README covers installation, configuration, deployment, operation and security. https://github.com/PQCrypta/pqcrypta-proxy#quick-start", + "documentation_interface_status": "Met", + "documentation_interface_justification": "Every configuration setting is in docs/CONFIG.md, and the README documents the command line and the admin API; tests/docs.rs fails CI if they drift from the code. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CONFIG.md", + "sites_https_status": "Met", + "sites_https_justification": "The website (pqcrypta.com), the repository (github.com) and the downloads (GitHub Releases, ghcr.io) are all served over HTTPS only.", + "discussion_status": "Met", + "discussion_justification": "GitHub Issues, pull requests and Discussions: searchable, addressable by URL, open to anyone, no proprietary client. https://github.com/PQCrypta/pqcrypta-proxy/discussions", + "english_status": "Met", + "english_justification": "All documentation is in English, and bug reports and comments are accepted in English.", + "maintained_status": "Met", + "maintained_justification": "Actively maintained: releases every few days, issues answered within two days. https://github.com/PQCrypta/pqcrypta-proxy/releases", + "repo_public_status": "Met", + "repo_public_justification": "Public git repository on GitHub. https://github.com/PQCrypta/pqcrypta-proxy", + "repo_track_status": "Met", + "repo_track_justification": "Git records what changed, who changed it and when.", + "repo_interim_status": "Met", + "repo_interim_justification": "Every change lands on main through a pull request, between releases; Release Please cuts each release from main. https://github.com/PQCrypta/pqcrypta-proxy/pulls?q=is%3Apr", + "repo_distributed_status": "Met", + "repo_distributed_justification": "Git.", + "version_unique_status": "Met", + "version_unique_justification": "Each release has its own version (Cargo.toml) and tag v. https://github.com/PQCrypta/pqcrypta-proxy/tags", + "version_semver_status": "Met", + "version_semver_justification": "Semantic Versioning, set by Release Please from Conventional Commits.", + "version_tags_status": "Met", + "version_tags_justification": "Each release is a git tag v. https://github.com/PQCrypta/pqcrypta-proxy/tags", + "release_notes_status": "Met", + "release_notes_justification": "Each release has notes, grouped into Security, Features and Bug Fixes, on its release page and in CHANGELOG.md. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CHANGELOG.md", + "release_notes_vulns_status": "Met", + "release_notes_vulns_justification": "Each release that fixed a published vulnerability lists its advisory under Security in its notes (for example 0.26.2). No CVE ID has been assigned yet; each advisory's GHSA ID is listed. https://github.com/PQCrypta/pqcrypta-proxy/security/advisories", + "report_process_status": "Met", + "report_process_justification": "Bugs and feature requests go to GitHub Issues, as CONTRIBUTING.md describes. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#reporting", + "report_tracker_status": "Met", + "report_tracker_justification": "GitHub Issues. https://github.com/PQCrypta/pqcrypta-proxy/issues", + "report_responses_status": "Met", + "report_responses_justification": "No bug reports were filed in the 2-12 month window. The two filed since (#184, #223) were each acknowledged within 36 hours and fixed in a release the same day.", + "enhancement_responses_status": "Met", + "enhancement_responses_justification": "No enhancement requests have been filed; issues are answered as above.", + "report_archive_status": "Met", + "report_archive_justification": "GitHub Issues are public and searchable. https://github.com/PQCrypta/pqcrypta-proxy/issues?q=is%3Aissue", + "vulnerability_report_process_status": "Met", + "vulnerability_report_process_justification": "SECURITY.md: report privately, what to include, what happens next, and where advisories are published. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/SECURITY.md", + "vulnerability_report_private_status": "Met", + "vulnerability_report_private_justification": "GitHub private vulnerability reporting (https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/new), or email; SECURITY.md says how. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/SECURITY.md#reporting-a-vulnerability", + "vulnerability_report_response_status": "Met", + "vulnerability_report_response_justification": "Both vulnerability reports received in the last 6 months (#184, #223) were answered within 36 hours, far inside 14 days; SECURITY.md commits to an acknowledgement within three days.", + "build_status": "Met", + "build_justification": "Cargo builds the proxy from source with cargo build --release; CI builds it on Linux, macOS and Windows. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#building-and-testing", + "build_common_tools_status": "Met", + "build_common_tools_justification": "Cargo, Rust's standard build tool.", + "build_floss_tools_status": "Met", + "build_floss_tools_justification": "Rust, Cargo, OpenSSL and every dependency are free software.", + "test_status": "Met", + "test_justification": "Unit, integration and documentation tests, run with cargo test, are in the repository; CI runs them on every push and pull request. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#building-and-testing", + "test_invocation_status": "Met", + "test_invocation_justification": "cargo test, the standard Rust test command.", + "test_most_status": "Met", + "test_most_justification": "Unit tests across the modules, integration tests in tests/, each vendored fork's own tests, and fuzz targets for every parser of client bytes. CI's Coverage job measures line, region and function coverage of the proxy's own code on every push (cargo-llvm-cov). https://github.com/PQCrypta/pqcrypta-proxy/actions/workflows/ci.yml", + "test_continuous_integration_status": "Met", + "test_continuous_integration_justification": "GitHub Actions runs the tests, clippy, CodeQL, cargo-deny, cargo-audit, REUSE, coverage and fuzzing on every push and pull request. https://github.com/PQCrypta/pqcrypta-proxy/actions/workflows/ci.yml", + "test_policy_status": "Met", + "test_policy_justification": "CONTRIBUTING.md: every change that adds or changes behaviour comes with tests, and a bug fix with a test that fails without it; a PR without them is not merged. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#tests", + "tests_are_added_status": "Met", + "tests_are_added_justification": "Recent major changes added tests with the code: #355 (CONNECT-IP, 10 new tests) and #357 (QUIC close and compression, 5 new tests plus a fuzz seed). https://github.com/PQCrypta/pqcrypta-proxy/pull/355", + "tests_documented_added_status": "Met", + "tests_documented_added_justification": "The test policy is part of the contribution instructions. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/CONTRIBUTING.md#tests", + "warnings_status": "Met", + "warnings_justification": "Clippy's all, pedantic and nursery groups at warning level, unsafe_code denied, in Cargo.toml [lints]; CI runs clippy with -D warnings for all features and each feature set. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/Cargo.toml", + "warnings_fixed_status": "Met", + "warnings_fixed_justification": "CI fails on any warning, so main builds with none.", + "warnings_strict_status": "Met", + "warnings_strict_justification": "As strict as Rust offers in practice: clippy pedantic and nursery, every warning an error, plus project lints in clippy.toml.", + "know_secure_design_status": "Met", + "know_secure_design_justification": "The primary developer designs for security: docs/SECURE-DESIGN.md sets out the principles applied (fail-safe defaults, complete mediation, least privilege, separation of privilege, economy of mechanism, open design) and where each is in the code. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/SECURE-DESIGN.md", + "know_common_errors_status": "Met", + "know_common_errors_justification": "docs/SECURE-DESIGN.md lists the errors a reverse proxy is known for (request smuggling, path confusion, header spoofing, resource exhaustion, panics on input, replay, brute force, SSRF, ReDoS, weak crypto, supply chain), each with its CWE and its countermeasure. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/SECURE-DESIGN.md#common-errors-and-their-countermeasures", + "crypto_published_status": "Met", + "crypto_published_justification": "Only published, reviewed protocols and algorithms: TLS 1.3, QUIC, ML-KEM (FIPS 203), ML-DSA (FIPS 204), X25519, ECDSA, AES-GCM, ChaCha20-Poly1305, HPKE (RFC 9180), HMAC-SHA-256. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md", + "crypto_call_status": "Met", + "crypto_call_justification": "No primitive is implemented in the proxy: it calls rustls with AWS-LC, OpenSSL and RustCrypto. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md#libraries-not-our-own-primitives", + "crypto_floss_status": "Met", + "crypto_floss_justification": "Every cryptographic library used (rustls, AWS-LC, OpenSSL, RustCrypto, liboqs) is free software.", + "crypto_keylength_status": "Met", + "crypto_keylength_justification": "Defaults: 256-bit AEAD keys, ML-KEM at NIST level 3 or 5, curves of 256 bits or more. AWS-LC and OpenSSL (security level 2) refuse RSA under 2048 bits; pqc.require_hybrid or downgrade_action = block disables the classical groups. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md#key-lengths", + "crypto_working_status": "Met", + "crypto_working_justification": "No default depends on a broken algorithm. SHA-1 (OCSP CertID, WebSocket accept) and MD5 (JA3 labels) appear only where a protocol defines them, never as protection; the risks are documented. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md#legacy-algorithms-where-a-protocol-requires-them", + "crypto_weaknesses_status": "Met", + "crypto_weaknesses_justification": "No default mechanism uses SHA-1 or CBC: TLS 1.3 with AEAD suites by default, and TLS 1.2 (opt-in) only with ECDHE and AEAD.", + "crypto_pfs_status": "Met", + "crypto_pfs_justification": "Every key exchange is ephemeral: TLS 1.3 always, ECDHE only on TLS 1.2. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md#forward-secrecy", + "crypto_password_storage_status": "N/A", + "crypto_password_storage_justification": "The proxy stores no passwords: it authenticates no end user by password. Its own secrets are supplied as systemd credentials and compared in constant time. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md#secrets-and-passwords", + "crypto_random_status": "Met", + "crypto_random_justification": "Every key, nonce and token comes from AWS-LC's CTR-DRBG (NIST SP 800-90A), seeded from the OS, through src/secure_random.rs; clippy refuses rand::random and rand::fill. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/docs/CRYPTOGRAPHY.md#random-numbers", + "delivery_mitm_status": "Met", + "delivery_mitm_justification": "Releases are downloaded over HTTPS from GitHub Releases and ghcr.io.", + "delivery_unsigned_status": "Met", + "delivery_unsigned_justification": "No hash is fetched over HTTP. Each release binary and container image carries a Sigstore-signed SLSA provenance attestation, verified with gh attestation verify or cosign. https://github.com/PQCrypta/pqcrypta-proxy#release-binary", + "vulnerabilities_fixed_60_days_status": "Met", + "vulnerabilities_fixed_60_days_justification": "Every published advisory names a released fix, and cargo-audit and cargo-deny fail CI on any known advisory in a dependency. https://github.com/PQCrypta/pqcrypta-proxy/security/advisories", + "vulnerabilities_critical_fixed_status": "Met", + "vulnerabilities_critical_fixed_justification": "Reported vulnerabilities were fixed and released within a day: #184 in 0.7.0 ten hours after the report, #223 in 0.14.0 nine hours after.", + "no_leaked_credentials_status": "Met", + "no_leaked_credentials_justification": "gitleaks runs on every push and pull request, and GitHub secret scanning with push protection is on, with no open alerts. https://github.com/PQCrypta/pqcrypta-proxy/actions/workflows/secret-scan.yml", + "static_analysis_status": "Met", + "static_analysis_justification": "CodeQL (security-and-quality queries for Rust) and clippy (pedantic, nursery, warnings as errors) run on every push and pull request; cargo-deny and cargo-audit check the dependencies. https://github.com/PQCrypta/pqcrypta-proxy/actions/workflows/codeql.yml", + "static_analysis_common_vulnerabilities_status": "Met", + "static_analysis_common_vulnerabilities_justification": "CodeQL's security queries look for CWE-classified flaws: injection, unsafe deserialization, cleartext logging of secrets, hard-coded credentials.", + "static_analysis_fixed_status": "Met", + "static_analysis_fixed_justification": "Confirmed findings are fixed, not suppressed; the one open CodeQL alert was fixed in the admin API's canary route.", + "static_analysis_often_status": "Met", + "static_analysis_often_justification": "On every push and pull request, and weekly.", + "dynamic_analysis_status": "Met", + "dynamic_analysis_justification": "Coverage-guided fuzzing (cargo-fuzz) of every parser of client bytes, run by ClusterFuzzLite on pull requests and for an hour daily; a WAF regression and pentest gate runs before each deployment. https://github.com/PQCrypta/pqcrypta-proxy/tree/main/fuzz", + "dynamic_analysis_unsafe_status": "Met", + "dynamic_analysis_unsafe_justification": "The proxy is Rust with unsafe denied outside C and kernel boundaries, and links OpenSSL (C). Its fuzz targets run under AddressSanitizer, which covers those boundaries.", + "dynamic_analysis_enable_assertions_status": "Met", + "dynamic_analysis_enable_assertions_justification": "Fuzz builds use cargo fuzz build -O -a: optimized, with debug assertions and overflow checks on; the tests run in the debug profile. https://github.com/PQCrypta/pqcrypta-proxy/blob/main/.clusterfuzzlite/build.sh", + "dynamic_analysis_fixed_status": "Met", + "dynamic_analysis_fixed_justification": "Findings from fuzzing and the pentest gate are fixed before release; ClusterFuzzLite fails a pull request that introduces a crash." +} \ No newline at end of file diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index e4ae07e8..00000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,64 +0,0 @@ -# Security Policy - -## Supported Versions - -| Version | Supported | -|---------|-----------| -| 0.2.x | ✅ Active security fixes | -| < 0.2 | ❌ End of life — upgrade required | - -## Reporting a Vulnerability - -**Please do not report security vulnerabilities through GitHub Issues.** - -### Private Disclosure - -Email **security@pqcrypta.com** with: - -1. **Description** — A clear summary of the vulnerability and its impact. -2. **Steps to reproduce** — A minimal, self-contained reproduction case. -3. **Affected versions** — Which versions or commits are affected. -4. **Suggested severity** — Critical / High / Medium / Low. -5. **CVE request** — Let us know if you need a CVE assigned (we can assist). - -PGP-encrypted reports are welcome. Our public key is available at -`https://pqcrypta.com/.well-known/security.txt`. - -### Response Timeline - -| Milestone | Target | -|-----------|--------| -| Acknowledgement | Within 48 hours | -| Initial assessment | Within 5 business days | -| Patch / mitigation | Within 90 days for High/Critical | -| Public disclosure | Coordinated with reporter | - -We follow a **90-day coordinated disclosure** policy. If a patch cannot be -issued within 90 days we will notify you and agree on an extension or limited -disclosure. - -## Scope - -**In scope:** -- `pqcrypta-proxy` binary and all Rust source files in this repository -- PQC TLS key exchange implementation (`src/pqc_tls.rs`) -- Admin API authentication (`src/admin.rs`) -- Rate limiting and DoS protection (`src/rate_limiter.rs`, `src/security.rs`) -- Configuration parsing and validation (`src/config.rs`) -- HTTP/QUIC/WebTransport handling - -**Out of scope:** -- Third-party dependencies (report to the respective maintainers) -- Vulnerabilities in OpenSSL 3.5+ itself (report to the OpenSSL project) -- Issues requiring physical access to the server -- Social engineering attacks - -## Security Hardening - -For operational security hardening guidance see [`docs/SECURITY.md`](../docs/SECURITY.md). - -## Hall of Fame - -We thank responsible security researchers who help keep PQCrypta Proxy secure. -Reporters who follow this policy will be acknowledged (with permission) in -release notes and credited in the fix commit. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5db32c96..76d45813 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,8 +5,9 @@ on: branches: [main, develop] pull_request: branches: [main] - release: - types: [created] + # Release Please starts it on each release PR (release-please.yml), whose + # pushes start no workflow of their own + workflow_dispatch: # Read only unless a job asks for more permissions: @@ -492,36 +493,70 @@ jobs: cache-to: type=gha,mode=max # ============================================================================= - # Release Builds + # Coverage # ============================================================================= - release: - name: Release + # The Linux test run again, under LLVM's source-based coverage of the + # proxy's own code (the forks under vendor/ have their jobs above): each + # file's lines, regions and functions, and the totals, go to the run's + # summary, and the lcov report is kept with the run. + coverage: + name: Coverage runs-on: ubuntu-latest - needs: [build, test, integration, security] - if: github.event_name == 'release' - steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Download all artifacts - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + - uses: dtolnay/rust-toolchain@89b12181fb390509a0842a86cc55eeb8eb928c1d # the toolchain rust-toolchain.toml names with: - path: artifacts + toolchain: "1.99.0" + components: llvm-tools-preview - - name: Create release archives - run: | - cd artifacts - for dir in */; do - target=$(basename "$dir") - tar -czvf "../${target}.tar.gz" -C "$dir" . - done - - - name: Upload release assets - uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + key: coverage + + - uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11 with: - files: "*.tar.gz" + tool: cargo-llvm-cov + + - name: Setup OpenSSL (Linux) + uses: ./.github/actions/setup-openssl-linux + + - name: Install Redis + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + sudo systemctl stop redis-server || true + + - name: Tests under coverage env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PQCRYPTA_REQUIRE_REDIS: "1" + run: cargo llvm-cov --all-features --ignore-filename-regex '(^|/)vendor/' --lcov --output-path lcov.info + + - name: Summary + run: | + { + echo '## Coverage of the proxy'"'"'s own code' + echo + echo '```' + cargo llvm-cov report --summary-only --ignore-filename-regex '(^|/)vendor/' + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: lcov + path: lcov.info + + # ============================================================================= + # Licensing + # ============================================================================= + # Every file's licence and copyright named (REUSE.toml, LICENSES/) + reuse: + name: Licensing (REUSE) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0 # ============================================================================= # Documentation diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 10a8d957..d1d12e63 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -7,6 +7,9 @@ on: branches: [main] schedule: - cron: '0 4 * * 0' # Sunday 04:00 UTC + # Release Please starts it on each release PR (release-please.yml), whose + # pushes start no workflow of their own + workflow_dispatch: # Read only unless a job asks for more permissions: diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index cbb39459..e8f14deb 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -29,6 +29,8 @@ jobs: outputs: release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} + prs_created: ${{ steps.release.outputs.prs_created }} + pr: ${{ steps.release.outputs.pr }} steps: - uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0 id: release @@ -45,6 +47,28 @@ jobs: # binary runs without either installed. release-please creates the release as a # draft (release-please-config.json): the asset goes up, then the release is # published, as immutable releases require. + # The release PR is opened and updated with this workflow's GITHUB_TOKEN, + # and GitHub starts no workflow for a push made with that token, so its + # commit would merge with neither CI nor CodeQL behind it. A + # workflow_dispatch made with the same token does start one: both run on the + # release branch, and their checks are on the commit the PR merges. + release-pr-checks: + name: CI and CodeQL on the release PR + needs: release-please + if: needs.release-please.outputs.prs_created == 'true' + runs-on: ubuntu-latest + permissions: + actions: write + steps: + - name: Start them on the release branch + env: + GH_TOKEN: ${{ github.token }} + BRANCH: ${{ fromJSON(needs.release-please.outputs.pr).headBranchName }} + run: | + for workflow in ci.yml codeql.yml; do + gh workflow run "$workflow" --repo "$GITHUB_REPOSITORY" --ref "$BRANCH" + done + binary: name: Release binary needs: release-please diff --git a/CHANGELOG.md b/CHANGELOG.md index dd521a39..806a333b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,6 +135,11 @@ ## [0.26.3](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.26.2...v0.26.3) (2026-11-29) +### Security + +* [GHSA-v682-4ff3-5pjm](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-v682-4ff3-5pjm): The response cache stored a 304 Not Modified and served it to requests that held no copy (all versions before 0.26.3). +* [GHSA-xfc5-32cw-xrqq](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-xfc5-32cw-xrqq): CRS skipped the body of a request without a Content-Length once it reached max_body_scan_bytes (all versions before 0.26.3). + ### Bug Fixes * **cache:** a 304 is never stored ([bce8c55](https://github.com/PQCrypta/pqcrypta-proxy/commit/bce8c553525a77b7aa4f2fe65e9384b02044ea13)) @@ -143,6 +148,12 @@ ## [0.26.2](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.26.1...v0.26.2) (2026-11-29) +### Security + +* [GHSA-572v-6rjh-r9j9](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-572v-6rjh-r9j9): Forwarding headers a client sent about itself were passed to backends (all versions before 0.26.2). +* [GHSA-8gjp-crm8-qg5w](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-8gjp-crm8-qg5w): 0-RTT replay protection could be skipped by a ClientHello split across TCP segments (all versions before 0.26.2). +* [GHSA-86jw-h76p-26gg](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-86jw-h76p-26gg): A percent-encoded spelling of a path could be routed past the guard of the route that names it (all versions before 0.26.2). + ### Bug Fixes * **routing:** the path routed, limited and judged is the name the origin serves; forwarding fields a client claims stay with the client ([48be282](https://github.com/PQCrypta/pqcrypta-proxy/commit/48be282b5281dd27605f006e99e14f710f374ba7)) @@ -157,6 +168,10 @@ ## [0.26.0](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.25.0...v0.26.0) (2026-11-28) +### Security + +* [GHSA-c6c9-wxf2-mh63](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-c6c9-wxf2-mh63): Over TCP, a signed route's request body reached the backend before its Content-Digest was checked (versions 0.18.0 to 0.25.0). + ### Features * **pqc:** the key-exchange policy in every QUIC application's own terms ([02b3533](https://github.com/PQCrypta/pqcrypta-proxy/commit/02b3533461c92d7fc59b744b7209d6c7ffff18da)) @@ -408,6 +423,12 @@ WebTransport over HTTP/3 as draft-ietf-webtrans-http3-17 has it, on the QUIC lis ## [0.17.0](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.16.0...v0.17.0) (2026-11-18) +### Security + +* [GHSA-xp2j-wp95-2j2f](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-xp2j-wp95-2j2f): A generated admin API token was written to standard error and the log (versions 0.3.0 to 0.16.0). +* [GHSA-p42p-5q6x-h4h9](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-p42p-5q6x-h4h9): Extended CONNECT requests on HTTP/3 and WebTransport sessions bypassed route gates, per-route limits and route policy (versions 0.3.0 to 0.16.0). +* [GHSA-96wm-f558-px7v](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-96wm-f558-px7v): A signed request could be accepted again after its HMAC nonce was forgotten (versions 0.3.0 to 0.16.0). + ### Features * `--admin METHOD PATH`, a signed request to this node's admin API ([772ae8c](https://github.com/PQCrypta/pqcrypta-proxy/commit/772ae8c39b85a8b9a8462ffbe3cea8188e97d563)) @@ -449,6 +470,10 @@ WebTransport over HTTP/3 as draft-ietf-webtrans-http3-17 has it, on the QUIC lis ## [0.14.0](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.13.3...v0.14.0) (2026-11-16) +### Security + +* [GHSA-6vmf-v85f-vxrc](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-6vmf-v85f-vxrc): WebTransport streams that withheld their end grew the proxy's memory until it was killed (versions 0.2.1 to 0.13.3); reported in #223. + ### Features * backend health probed in the background, by HTTP where a path is set ([84913a3](https://github.com/PQCrypta/pqcrypta-proxy/commit/84913a3c305c4ef450e646b2440d245c1bc9fa1a)) @@ -516,6 +541,10 @@ WebTransport over HTTP/3 as draft-ietf-webtrans-http3-17 has it, on the QUIC lis ## [0.11.1](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.11.0...v0.11.1) (2026-11-13) +### Security + +* [GHSA-2x5f-g7rf-883h](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-2x5f-g7rf-883h): Tables keyed by client-chosen values grew without bound or cost a full pass per new key (all versions before 0.11.1). + ### Bug Fixes * bound every table a client can add to; decline early data the replay guard cannot vouch for ([d3bbf13](https://github.com/PQCrypta/pqcrypta-proxy/commit/d3bbf13068b482da8c2c8cdeaf4b0511b0c2f128)), closes [#184](https://github.com/PQCrypta/pqcrypta-proxy/issues/184) @@ -622,6 +651,10 @@ WebTransport over HTTP/3 as draft-ietf-webtrans-http3-17 has it, on the QUIC lis ## [0.7.0](https://github.com/PQCrypta/pqcrypta-proxy/compare/v0.6.0...v0.7.0) (2026-11-12) +### Security + +* [GHSA-932f-949c-8mmf](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories/GHSA-932f-949c-8mmf): Unique failing HTTP/3 paths grew the per-endpoint error table without bound (versions 0.3.0 to 0.6.0); reported in #184. + ### Features * **masque:** allowed_clients names the clients a CONNECT-UDP session is relayed for ([f7ac1ac](https://github.com/PQCrypta/pqcrypta-proxy/commit/f7ac1ac180f64a0ae2b06c3da3a9ae27aa128df3)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e8cc6ee3..cb9e79a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,150 +1,96 @@ # Contributing to PQCrypta Proxy -Thank you for your interest in contributing to PQCrypta Proxy! This document provides guidelines for contributing to the project. +Thank you for helping. This file says how to report a problem, how a change +is made and reviewed, and what a change must meet to be merged. -## Code of Conduct +## Reporting -This project follows the [Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). Please be respectful and constructive in all interactions. +- **A bug or a feature request:** open a + [GitHub issue](https://github.com/PQCrypta/pqcrypta-proxy/issues). Name the + version (`pqcrypta-proxy --version`), the configuration it needs, what you + did and what happened. Issues are answered, and they stay public and + searchable. +- **A question or an idea to discuss:** + [Discussions](https://github.com/PQCrypta/pqcrypta-proxy/discussions). +- **A vulnerability:** never in a public issue. Report it privately, as + [SECURITY.md](SECURITY.md) describes. -## Getting Started +## Code of conduct -### Prerequisites +This project follows the +[Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). -- Rust 1.75+ (install via [rustup](https://rustup.rs/)) -- OpenSSL 3.x development libraries -- Git +## Building and testing -### Development Setup +- Rust: the toolchain [`rust-toolchain.toml`](rust-toolchain.toml) pins, + which [rustup](https://rustup.rs/) installs on the first `cargo` command + in the repository. +- OpenSSL 3.5 or later with its development headers (CI builds against + 4.0.3, as `.github/actions/setup-openssl-linux` does), or build with + `--no-default-features --features "metrics admin-api geoip acme"` for + rustls alone. ```bash -# Clone the repository git clone https://github.com/PQCrypta/pqcrypta-proxy.git cd pqcrypta-proxy - -# Build cargo build - -# Run tests -cargo test - -# Run with example config +cargo test # unit, integration and documentation tests +cargo test --all-features # what CI runs on Linux cargo run -- --config config/example-config.toml --validate ``` -## Making Changes - -### Branching Strategy - -- `main` - The development branch (target for PRs); releases are tagged from it -- `feature/*` - Feature branches -- `fix/*` - Bug fix branches - -### Pull Request Process +The distributed rate limiter's tests start a `redis-server` of their own +when one is installed, and are skipped when it is not +(`PQCRYPTA_REQUIRE_REDIS=1` makes a missing one a failure, as in CI). -1. **Fork the repository** and create your branch from `main` +## Making a change -2. **Make your changes**: - - Write clear, concise commit messages - - Add tests for new functionality - - Update documentation as needed - -3. **Ensure quality**: +1. Fork the repository and branch from `main`. +2. Make the change, with its tests and documentation (below). +3. Run what CI runs: ```bash - # Format code - cargo fmt - - # Run linter + cargo fmt -p pqcrypta-proxy -- --check cargo clippy --all-targets --all-features -- -D warnings - - # Run tests - cargo test + cargo test --all-features ``` +4. Open a pull request against `main`. Describe what changes and why, and + link the issue it addresses. A maintainer reviews it, and it merges once + every check below passes. -4. **Submit PR**: - - Provide a clear description of changes - - Reference any related issues - - Request review from maintainers - -### Commit Messages - -Follow [Conventional Commits](https://www.conventionalcommits.org/): - -``` -type(scope): description - -[optional body] - -[optional footer] -``` +### Commit messages -Types: -- `feat`: New feature -- `fix`: Bug fix -- `docs`: Documentation changes -- `style`: Code style changes (formatting, etc.) -- `refactor`: Code refactoring -- `test`: Adding or modifying tests -- `chore`: Build, CI, or tooling changes +[Conventional Commits](https://www.conventionalcommits.org/): `feat(scope):`, +`fix(scope):`, `docs:`, `test:`, `refactor:`, `ci:`, `chore:`. Release +Please reads them: a `feat` makes the next release a minor one, a `fix` a +patch, and each one's subject becomes a line of the release notes in +[CHANGELOG.md](CHANGELOG.md), so write the subject for someone deciding +whether to upgrade. -Examples: -``` -feat(quic): add connection migration support -fix(tls): handle certificate reload race condition -docs(readme): update PQC setup instructions ``` - -## Code Style - -### Rust Guidelines - -- Follow [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/) -- Use `rustfmt` for formatting -- Address all `clippy` warnings -- Document public APIs with doc comments - -### Error Handling - -- Use `anyhow` for application errors -- Use `thiserror` for library errors -- Provide context in error messages - -```rust -// Good -.context("failed to load TLS certificate")? - -// Bad -.expect("certificate") +feat(quic): connection migration for WebTransport sessions +fix(tls): a certificate reloaded mid-handshake is served whole ``` -### Logging +## What a change must meet -Use the `tracing` crate with appropriate levels: +### Tests -```rust -use tracing::{debug, info, warn, error}; - -info!("Server starting on {}", addr); -debug!(connection_id = %id, "New connection"); -warn!("Certificate expires in {} days", days); -error!(error = %e, "Failed to process request"); -``` - -### Testing - -- Write unit tests for all new functionality -- Add integration tests for end-to-end scenarios -- Use property-based testing for complex logic +Every change that adds or changes behaviour comes with tests that exercise +it, and a bug fix comes with a test that fails without the fix. A pull +request without them is not merged. Unit tests sit beside the code +(`#[cfg(test)]`), end-to-end tests in `tests/`. A test makes its own secrets +and nonces (`secure_random`) rather than fixing them in the source, so that +it shows the code verifies whatever it is given. ### Fuzzing Release builds abort on a panic, so a parser that panics on a client's bytes ends the process. `fuzz/` holds coverage-guided targets (cargo-fuzz) for each -family of parsers a client or a peer reaches: ClientHello records (where the -acceptor's and the passthrough router's SNI must agree), DNS messages, -request bodies (never decoded past their limit), PROXY protocol headers, -fetched documents, CONNECT-UDP targets and session tickets. Their entry -points are `src/fuzzing.rs`, compiled only under `cfg(fuzzing)`; seeds are in -`fuzz/seeds//`. With a nightly toolchain and `cargo install cargo-fuzz`: +family of parsers a client or a peer reaches; their entry points are +`src/fuzzing.rs`, compiled only under `cfg(fuzzing)`, and their seeds are in +`fuzz/seeds//`. A parser added where client bytes arrive gets an +entry there and a target. With a nightly toolchain and +`cargo install cargo-fuzz`: ```bash cd fuzz @@ -152,102 +98,46 @@ cd fuzz cargo +nightly fuzz run client_hello corpus/client_hello seeds/client_hello -- -max_total_time=60 ``` -ClusterFuzzLite runs every target on pull requests that touch the code they -reach, and for an hour each day. A parser added where client bytes arrive -gets an entry in `src/fuzzing.rs` and a target. - -```rust -#[test] -fn test_route_matching() { - // ... -} - -#[tokio::test] -async fn test_admin_health_endpoint() { - // ... -} -``` - -## Architecture - -### Module Structure - -``` -src/ -├── main.rs # Entry point and CLI -├── lib.rs # Library exports -├── config.rs # Configuration parsing and validation -│ # - TlsMode enum (terminate, reencrypt, passthrough) -│ # - PassthroughRoute for SNI routing -│ # - HeadersConfig for security headers -│ # - CorsConfig for CORS handling -│ # - RateLimitConfig, CompressionConfig -├── http_listener.rs # HTTP/1.1/2 reverse proxy -│ # - TLS termination and re-encryption -│ # - TLS passthrough (SNI routing) -│ # - Security headers middleware -│ # - CORS handling -│ # - HTTP→HTTPS redirect server -├── security.rs # Security middleware (NEW) -│ # - Rate limiting (governor crate) -│ # - DoS protection & connection limits -│ # - IP blocking (manual + auto) -│ # - GeoIP blocking (MaxMind DB) -│ # - JA3/JA4 TLS fingerprinting -│ # - Circuit breaker -├── compression.rs # Compression middleware (NEW) -│ # - Brotli, Zstd, Gzip, Deflate -│ # - Content negotiation -│ # - Skip pre-compressed content -├── http3_features.rs # HTTP/3 advanced features (NEW) -│ # - Early Hints (103) -│ # - Priority Hints (RFC 9218) -│ # - Request Coalescing -├── tls.rs # TLS provider with PQC support -├── quic_listener.rs # QUIC/HTTP3 listener -├── webtransport_server.rs # WebTransport session handling -├── proxy.rs # Backend connection pool -├── admin.rs # Admin API server -└── handlers/ - ├── mod.rs - └── webtransport.rs # WebTransport handlers -``` - -### Key Design Decisions - -1. **Hot reload**: Use `arc_swap` for atomic configuration updates -2. **Async runtime**: Use `tokio` for async I/O -3. **TLS**: Use `rustls` with optional OpenSSL for PQC -4. **QUIC**: Use `quinn` crate for QUIC protocol -5. **Admin API**: Use `axum` for HTTP server - -## Security Considerations - -### Reporting Security Issues - -**Do not** report security vulnerabilities via public GitHub issues. - -Instead, email security@pqcrypta.com with: -- Description of the vulnerability -- Steps to reproduce -- Potential impact -- Suggested fix (if any) - -### Security Best Practices - -When contributing: -- Never commit secrets or credentials -- Validate all user input -- Use constant-time comparisons for secrets -- Avoid panics in production code paths -- Consider timing attacks in crypto code - -## License - -By contributing, you agree that your contributions will be licensed under the same terms as the project (MIT/Apache-2.0 dual license). - -## Questions? - -- Open a [GitHub Discussion](https://github.com/PQCrypta/pqcrypta-proxy/discussions) -- Join our [Discord](https://discord.gg/pqcrypta) -- Email: dev@pqcrypta.com +ClusterFuzzLite runs every target under AddressSanitizer on pull requests +that touch the code it reaches, and for an hour each day. + +### Code + +- rustfmt, and clippy with `all`, `pedantic` and `nursery` at warning level, + every warning an error in CI ([`Cargo.toml`](Cargo.toml) `[lints]`, + [`clippy.toml`](clippy.toml)). +- No `unsafe` outside a C or kernel boundary, and each `unsafe` block states + why it is sound in a `// SAFETY:` comment. +- Errors carry context (`anyhow::Context`) rather than `expect` on a path a + client can reach; log with `tracing`. +- A key, nonce or token comes from `secure_random`; `rand::random_range` is + for choices that protect nothing. +- Every input from a client is bounded: in size, in time, and in the room it + takes in any table it adds to (`bounded.rs`). +- Secrets are never logged and never committed. Compare them in constant + time. +- [docs/SECURE-DESIGN.md](docs/SECURE-DESIGN.md) lists the mistakes a + reverse proxy is known for and what counters each; a change near one keeps + its countermeasure. + +### Documentation + +A new or changed setting is documented in [docs/CONFIG.md](docs/CONFIG.md) +(`tests/docs.rs` holds its defaults, and the README's lists of options, +admin routes and modules, to the code), and a feature in the +[README](README.md). + +### Checks every pull request passes + +rustfmt; clippy, for all features and each feature set; tests on Linux and +macOS; the integration tests; each vendored fork's tests; cargo-deny and +cargo-audit; CodeQL; the REUSE licensing check; coverage; the fuzz targets +the change reaches; and secret scanning. + +## Licensing + +The proxy is licensed under either of the [Apache License 2.0](LICENSE-APACHE) +or the [MIT license](LICENSE-MIT), at your option. Unless you say otherwise, +a contribution you submit is licensed the same way, without any additional +terms. [REUSE.toml](REUSE.toml) names every file's licence; a change to a +fork under `vendor/` stays under that fork's upstream licence. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 00000000..137069b8 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSES/BSD-2-Clause.txt b/LICENSES/BSD-2-Clause.txt new file mode 100644 index 00000000..5f662b35 --- /dev/null +++ b/LICENSES/BSD-2-Clause.txt @@ -0,0 +1,9 @@ +Copyright (c) + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/LICENSES/ISC.txt b/LICENSES/ISC.txt new file mode 100644 index 00000000..e80998f0 --- /dev/null +++ b/LICENSES/ISC.txt @@ -0,0 +1,7 @@ +ISC License + +Copyright + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 00000000..d817195d --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 7079ac0a..940a9c99 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ | **Admin Loopback Enforcement** | ✅ | `require_loopback = true` (default) aborts startup when admin API is bound to a non-loopback address | | **Shared Security State** | ✅ | **Every** listener — QUIC and all three TCP paths — shares one `SecurityState`. Blocked IPs, rate limiter counters, the fingerprint corpus and DB-synced blocklists are visible across all of them. The TCP listeners previously each constructed their own, so an IP blocked on one was not blocked on another and the admin API could not clear it | | **Audit Events at Their Source** | ✅ | Each event is recorded where it happens: the admin API (actions, refused requests), the security layer (WAF verdicts, address blocks), the rate limiter, the TLS provider (every reload, whatever asked for it), the configuration reload handler and the handshake policy | -| **Cryptographically Secure Admin Token** | ✅ | Ephemeral admin tokens use `OsRng` instead of `thread_rng` | +| **Cryptographically Secure Keys and Tokens** | ✅ | Every key, nonce and token, the generated admin token included, is drawn from AWS-LC's DRBG (`secure_random`); clippy refuses `rand::random` and `rand::fill` | | **`zero_trust_mode`** | ✅ | Startup validation enforcing mTLS, no plaintext backends, no CIDR trust, and admin HMAC proof-of-possession | | **Per-Route HMAC Signing** | ✅ | `X-Request-Signature`, hex HMAC-SHA256 of `METHOD\nPATH_AND_QUERY\nTIMESTAMP\nNONCE\nCONTENT_DIGEST`, the last the request's `Content-Digest` field (RFC 9530, with a `sha-256` member) or empty; the body is held to that digest as it is forwarded (a request without the field has no body), so neither request nor body can be changed. A required `X-Request-Nonce` (8–128 characters) is bound into the signature and accepted once within the window, so a signed request cannot be replayed | | **Internal Route Auto-mTLS** | ✅ | `internal = true` routes default to requiring client certificate | @@ -269,7 +269,7 @@ - **Access Logging**: Per-request structured logging in JSON or plain-text format; configurable output file, includes method, path, status, latency, bytes, client IP, and upstream; user-controlled fields sanitized to prevent log injection - **Audit Logging**: Async structured JSON audit log for security-relevant events — admin actions, auth failures, WAF blocks/detects, IP blocks, rate limit hits, PQC downgrade events, config and TLS reloads, JA3 replay/drift detections - **Log Rotation via SIGHUP**: Sending `SIGHUP` to the proxy reopens all log file handles without dropping connections or restarting — compatible with standard logrotate `postrotate` hooks (`systemctl kill -s HUP pqcrypta-proxy`) -- **Admin API**: Health checks, Prometheus metrics, config reload, graceful shutdown, QUIC health, WebTransport health, canary status and live weight/suspend/resume control, live blocklist inspection (`GET /blocklist`), manual block (`POST /blocklist/block/:ip?duration_secs=N`) and immediate unblock (`POST /blocklist/unblock/:ip`); `GET /security/status`, `/security/geoip/:ip`, `/security/fingerprints` and `/security/threats`; rate-limit statistics (`GET /ratelimit`) and per-client reset (`POST /ratelimit/reset/:key`) against the one advanced rate limiter every listener, port and protocol shares; loopback enforcement prevents plain-HTTP token exposure on non-loopback interfaces; ephemeral session tokens use `OsRng` for cryptographic security; per-IP and global lockout of failing callers with exponential back-off; the token is checked first, so a correct token is never refused by it (a client left on a stale token cannot lock out the rest) +- **Admin API**: Health checks, Prometheus metrics, config reload, graceful shutdown, QUIC health, WebTransport health, canary status and live weight/suspend/resume control, live blocklist inspection (`GET /blocklist`), manual block (`POST /blocklist/block/:ip?duration_secs=N`) and immediate unblock (`POST /blocklist/unblock/:ip`); `GET /security/status`, `/security/geoip/:ip`, `/security/fingerprints` and `/security/threats`; rate-limit statistics (`GET /ratelimit`) and per-client reset (`POST /ratelimit/reset/:key`) against the one advanced rate limiter every listener, port and protocol shares; loopback enforcement prevents plain-HTTP token exposure on non-loopback interfaces; generated session tokens are drawn from AWS-LC's DRBG; per-IP and global lockout of failing callers with exponential back-off; the token is checked first, so a correct token is never refused by it (a client left on a stale token cannot lock out the rest) - **Graceful Shutdown Drain**: Configurable drain timeout polls active connections at 100 ms intervals and exits as soon as they reach zero — no unnecessary delay on idle restarts; while it waits it says, every 2 s, what it is waiting for - **Restarts that refuse nothing (systemd socket activation)**: with the socket unit `pqcrypta-proxy --socket-unit FILE` writes from the configuration, the service manager holds every listening socket across a restart, so a connection that arrives while one process drains and the next starts waits in the kernel and is served, rather than refused; each listener takes the socket bound to its address and binds itself what was not passed - **Certificate Transparency**: New ACME-issued certs submitted via `POST /ct/v1/add-chain` for public auditability, to the configured logs or, by default, to one log per operator from the live CT log list whose temporal shard holds the certificate's expiry @@ -1986,6 +1986,7 @@ src/ ├── request_target.rs # The host a request names, resolved one way for every layer and transport ├── route_gate.rs # Per-route request gates, applied identically on every transport ├── secret_source.rs # Secret settings named by systemd credential or file rather than written in the configuration +├── secure_random.rs # Keys, nonces and tokens, from AWS-LC's DRBG ├── security.rs # Security middleware module ├── service_notify.rs # The service manager's notification protocol (sd_notify(3)) ├── speedtest.rs # Native speed test session handler for WebTransport connections on /speedtest @@ -2267,7 +2268,8 @@ the client certificate; with `hmac_secret`, a signed request; `GET` of the three | `/canary/resume/{server_id}` | POST | Put a suspended canary back | | `/canary/weight/{server_id}` | POST | Set a canary's share of traffic | | `/pools` | GET | Load-balancer pools: servers, load, circuit breakers, draining | -| `/pools/{pool}/servers/{server_id}/{action}` | POST | `drain`, `undrain`, `healthy`, `unhealthy`, `canary` (`{"weight": n}`, or no body for the pool's ramp) or `promote` for one server | +| `/pools/{pool}/servers/{server_id}/canary` | POST | Make one server the pool's canary: `{"weight": n}` (as `application/json`) for a fixed share, or no body for the pool's ramp | +| `/pools/{pool}/servers/{server_id}/{action}` | POST | `drain`, `undrain`, `healthy`, `unhealthy` or `promote` for one server | | `/cache` | GET | Response cache statistics | | `/cache/purge` | POST | Purge the response cache: everything, one host and path prefix (`?host=&prefix=`), or one URL (`?host=&path=`) | | `/moq` | GET | Media over QUIC relay: versions, sessions, tracks, cache, counters (404 where `[moq]` is off) | diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 00000000..c8be0cec --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,65 @@ +# The licence and copyright of every file in the repository, machine-readable +# (REUSE 3.3, https://reuse.software/spec-3.3/). The proxy's own files are +# MIT OR Apache-2.0; each fork under vendor/ keeps its upstream's licence, +# with the upstream's copyright and ours for the changes the fork carries. +# The licence texts are in LICENSES/; LICENSE-APACHE and LICENSE-MIT stay at +# the top, where Cargo and GitHub look. CI's `reuse lint` holds every file to +# an entry here, so a file added under a new path or a new licence is named +# before it merges. +# +# When more than one entry matches a file, the last one applies. +version = 1 + +[[annotations]] +path = "**" +precedence = "closest" +SPDX-FileCopyrightText = "2025-2026 PQCrypta " +SPDX-License-Identifier = "MIT OR Apache-2.0" + +[[annotations]] +path = ["vendor/h3/**", "vendor/h3-noq/**"] +precedence = "override" +SPDX-FileCopyrightText = ["2020 h3 authors", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "MIT" + +[[annotations]] +path = "vendor/hyper/**" +precedence = "override" +SPDX-FileCopyrightText = ["2014-2026 Sean McArthur", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "MIT" + +[[annotations]] +path = "vendor/n0-qlog/**" +precedence = "override" +SPDX-FileCopyrightText = ["2018-2019 Cloudflare, Inc.", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "BSD-2-Clause" + +[[annotations]] +path = "vendor/noq/**" +precedence = "override" +SPDX-FileCopyrightText = ["2018-2025 The quinn Developers", "2025 N0, Inc.", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "MIT OR Apache-2.0" + +[[annotations]] +path = "vendor/rustls-fixed/**" +precedence = "override" +SPDX-FileCopyrightText = ["2016 Joseph Birr-Pixton ", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "Apache-2.0 OR ISC OR MIT" + +[[annotations]] +path = ["vendor/wtransport/**", "vendor/wtransport-proto/**"] +precedence = "override" +SPDX-FileCopyrightText = ["Biagio Festa", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "MIT OR Apache-2.0" + +[[annotations]] +path = "vendor/zentinel-modsec/**" +precedence = "override" +SPDX-FileCopyrightText = ["Zentinel Contributors", "2025-2026 PQCrypta "] +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = "vendor/pqcrypta-hpke-pq/**" +precedence = "override" +SPDX-FileCopyrightText = "2025-2026 PQCrypta " +SPDX-License-Identifier = "MIT" diff --git a/SECURITY.md b/SECURITY.md index 199f994a..71ef0b65 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -21,6 +21,23 @@ against hosts you do not operate. affected and fixed versions and credits the reporter (unless they would rather not be named). +## Advisories + +Every vulnerability fixed is published as a +[GitHub security advisory](https://github.com/PQCrypta/pqcrypta-proxy/security/advisories) +that names the affected and fixed versions, with a CVE requested through +GitHub. The fixing release's notes, on its +[release page](https://github.com/PQCrypta/pqcrypta-proxy/releases) and in +[CHANGELOG.md](CHANGELOG.md), list it under **Security**. + +## How the proxy is built to be secure + +[docs/SECURE-DESIGN.md](docs/SECURE-DESIGN.md) sets out the design principles +and, for each kind of mistake a reverse proxy is known for, what counters it; +[docs/CRYPTOGRAPHY.md](docs/CRYPTOGRAPHY.md) the algorithms, libraries, +defaults and key lengths; [docs/SECURITY.md](docs/SECURITY.md) how to run it +hardened. + ## Supported versions Fixes are made on `main` and released as the next version; the latest release diff --git a/clippy.toml b/clippy.toml index fe4ff8ee..7e540b2e 100644 --- a/clippy.toml +++ b/clippy.toml @@ -21,3 +21,12 @@ await-holding-invalid-types = [ { path = "dashmap::setref::multiple::RefMulti", reason = "a DashSet shard read lock taken while iterating; collect before awaiting" }, { path = "dashmap::iter_set::Iter", reason = "holds a DashSet shard read lock; collect before awaiting" }, ] + +# A key, nonce or token is drawn from crate::secure_random (AWS-LC's DRBG, the +# generator the TLS stack draws its own secrets from). `rand` is kept for +# choices that protect nothing, through `rand::random_range`; these two are +# how its generator hands out raw values, the shape a secret takes. +disallowed-methods = [ + { path = "rand::random", reason = "a key, nonce or token comes from crate::secure_random; a choice that protects nothing is rand::random_range" }, + { path = "rand::fill", reason = "a key, nonce or token comes from crate::secure_random; a choice that protects nothing is rand::random_range" }, +] diff --git a/docs/CRYPTOGRAPHY.md b/docs/CRYPTOGRAPHY.md new file mode 100644 index 00000000..b9d8b337 --- /dev/null +++ b/docs/CRYPTOGRAPHY.md @@ -0,0 +1,105 @@ +# Cryptography + +What the proxy uses, where it comes from, and what it does by default. Every +setting named here is in [CONFIG.md](CONFIG.md). + +## Libraries, not our own primitives + +The proxy implements no cryptographic primitive. It calls libraries built to +provide them, all free software: + +| Library | Licence | Used for | +|---------|---------|----------| +| [rustls](https://github.com/rustls/rustls) with the [aws-lc-rs](https://github.com/aws/aws-lc-rs) provider (AWS-LC) | Apache-2.0 / ISC / MIT | TLS on QUIC always, and on TCP under `pqc.provider = "rustls"`; ML-KEM, ML-DSA, AES-GCM, ChaCha20-Poly1305, HKDF, the random number generator | +| [OpenSSL](https://www.openssl.org/) 3.5 or later | Apache-2.0 | TLS on TCP under `pqc.provider = "auto"` (the default) or `"openssl"`; OCSP | +| [RustCrypto](https://github.com/RustCrypto) `hpke`, `ml-kem`, `x-wing`, `sha2`, `hmac`, `subtle` | MIT / Apache-2.0 | HPKE for Encrypted Client Hello, SHA-2, HMAC, constant-time comparison | +| [liboqs](https://github.com/open-quantum-safe/liboqs) through [oqs-provider](https://github.com/open-quantum-safe/oqs-provider), when loaded | MIT | Additional post-quantum groups (`pqc.experimental_groups`); never loaded by default | + +`vendor/rustls-fixed` adds server-side Encrypted Client Hello to rustls: it +reconstructs the inner ClientHello and calls rustls's own HPKE to open it. +`vendor/pqcrypta-hpke-pq` is an adapter that puts RustCrypto's post-quantum +HPKE suites behind rustls's HPKE trait; its tests open the HPKE working +group's published test vectors. Neither implements a primitive. + +The `fips` build feature links AWS-LC's FIPS 140-3 module instead. + +## Defaults + +| What | Default | Settings | +|------|---------|----------| +| Protocol | TLS 1.3 only. QUIC is TLS 1.3 by definition | `tls.min_version` (`"1.2"` adds TLS 1.2) | +| Cipher suites, TLS 1.3 | AES-256-GCM, then ChaCha20-Poly1305 (not under `fips`) | | +| Cipher suites, TLS 1.2 (only with `min_version = "1.2"`) | ECDHE with AES-256-GCM or ChaCha20-Poly1305 | | +| Key exchange | Hybrid ML-KEM (FIPS 203): X25519MLKEM768 preferred, SecP256r1MLKEM768 and SecP384r1MLKEM1024 offered; P-384, P-256 and X25519 for clients without ML-KEM | `pqc.preferred_kem`, `pqc.additional_kems`, `pqc.require_hybrid`, `pqc.fallback_to_classical`, `pqc.min_security_level`, `pqc.downgrade_action` | +| Server certificates | The operator's keys: ECDSA, Ed25519, RSA, or ML-DSA-87 (FIPS 204) per host name | `pqc.enable_signatures` | +| Session tickets | Sealed per ticket under an ML-KEM-1024 encapsulation, AES-256-GCM, keys rotated | `tls.pqc_session_tickets` | +| 0-RTT early data | Off; when on, replay protection `strict` and a 425 per route | `tls.enable_0rtt`, `tls.zero_rtt_replay_protection` | +| Encrypted Client Hello | HPKE configs X-Wing (ML-KEM-768 with X25519) first, then DHKEM(X25519); keys rotated | `scripts/ech-rotate.sh`, `ech-keygen` | + +QUIC Initial packets are protected with AES-128-GCM under keys derived from +the connection ID, as RFC 9001 §5.2 requires of every QUIC endpoint. They +carry the handshake's first flight; everything after it is under the +negotiated suite. + +## Key lengths + +Every default meets NIST's minimums through 2030 and beyond: 256-bit AEAD +keys, ML-KEM at NIST level 3 or 5, elliptic curves of 256 bits or more. + +Shorter keys are refused by the libraries, whatever the configuration: + +- AWS-LC (rustls) does not load an RSA private key shorter than 2048 bits. +- OpenSSL 3.5 and later run at security level 2 by default: no RSA or DH key + under 2048 bits, no elliptic curve under 224 bits, no SHA-1 signature. +- Client and backend certificates are verified by webpki, which accepts RSA + from 2048 bits. + +To disable the classical groups entirely, set `pqc.require_hybrid = true` +(every key exchange includes ML-KEM) or `pqc.downgrade_action = "block"` +(a connection whose key exchange is classical is refused). +`pqc.min_security_level` removes ML-KEM groups below a NIST level. + +## Forward secrecy + +Every key exchange is ephemeral: TLS 1.3 always, and the only TLS 1.2 suites +the proxy offers are ECDHE. A resumed session depends on the ticket key that +sealed its ticket until that key is rotated (`pqc_tickets.rs` describes the +bound). + +## Random numbers + +Every key, nonce and token the proxy makes (the generated admin token, +signing nonces, challenge secrets, request and session IDs, DNS message IDs, +WebSocket keys) is drawn from AWS-LC's generator, through `secure_random.rs`: +a CTR-DRBG (NIST SP 800-90A) seeded and reseeded from the operating system. +TLS, QUIC and HPKE draw from the same generator inside rustls and AWS-LC, or +from OpenSSL's own. The `rand` crate is kept for choices that protect +nothing (a load-balancing pick, a sampling roll); clippy refuses +`rand::random` and `rand::fill` (`clippy.toml`), so a secret cannot be drawn +from it by accident. + +## Secrets and passwords + +The proxy stores no user passwords: it authenticates no end user by +password. Its own secrets (the admin token, HMAC keys, the JWT key, the +challenge secret, the ACME EAB key) are given to it, never written by it into +its configuration: as systemd credentials, encrypted at rest under the host's +key or TPM, or as files only its user can read (`secret_source.rs`). The +admin token, the metrics token and the admin and route HMAC keys are refused +under 32 characters, and a JWT key shorter than its hash. Tokens and +signatures are compared in constant time. A signed request carries a timestamp and a nonce, +and each nonce is accepted once. + +## Legacy algorithms, where a protocol requires them + +None of these protects anything; each is a value a protocol defines. + +| Algorithm | Where | Why it is safe there | +|-----------|-------|----------------------| +| SHA-1 | OCSP `CertID` (RFC 6960 §4.1.1) | It names the certificate in a request. Responders that follow the lightweight profile (RFC 5019) answer only SHA-1 `CertID`s. The response's signature is verified, with the responder's own algorithm, before a response is stapled | +| SHA-1 | WebSocket `Sec-WebSocket-Accept` (RFC 6455 §4.2.2) | It shows the server read the handshake; it authenticates nothing | +| MD5 | JA3 fingerprints | The JA3 format is the MD5 of a ClientHello's fields: a label. A client chooses its own ClientHello, so a collision gains it nothing it could not do directly. JA4, used beside it, hashes with SHA-256 | + +## Reporting a problem + +See [SECURITY.md](../SECURITY.md). diff --git a/docs/SECURE-DESIGN.md b/docs/SECURE-DESIGN.md new file mode 100644 index 00000000..69c2b1b2 --- /dev/null +++ b/docs/SECURE-DESIGN.md @@ -0,0 +1,70 @@ +# Secure design + +How the proxy is built to be safe at the edge of a network: the principles +it follows, the mistakes a reverse proxy is known for and what counters each +one, and how that is checked. The cryptography is in +[CRYPTOGRAPHY.md](CRYPTOGRAPHY.md), operating guidance in +[SECURITY.md](SECURITY.md), and how to report a vulnerability in the +repository's [SECURITY.md](../SECURITY.md). + +## Principles + +- **Fail-safe defaults.** TLS 1.3 only, 0-RTT off, the admin API on loopback + (startup is refused otherwise unless `require_loopback` is turned off), a + MASQUE relay with no `allowed_targets` relays nothing, and a node whose PQC + provider does not load refuses to start (`require_pqc_provider`). Secrets + shorter than their minimum are refused at load. +- **Complete mediation.** Every listener (HTTP/1.1, HTTP/2, HTTP/3, + WebTransport, Extended CONNECT) routes on the same canonical path and + passes the same route gates, limits and policy; there is no transport a + request can take around them. +- **Least privilege.** The packaged unit + ([`pqcrypta-proxy.service`](../packaging/systemd/pqcrypta-proxy.service)) + runs it as its own user with one capability, `CAP_NET_BIND_SERVICE`, under + `NoNewPrivileges`, `ProtectSystem=strict`, `MemoryDenyWriteExecute`, + `SystemCallFilter=@system-service` and a restricted set of address + families. Secrets arrive as systemd credentials, decrypted for the service + alone. +- **Separation of privilege.** The admin API takes a token and, when + configured, requests signed with a separate HMAC key and a client + certificate. A scraper gets a metrics token that reads the metrics and + nothing else. +- **Economy of mechanism.** One canonical path builder, one forwarding-header + policy and one rate limiter, shared by every listener, so a fix lands + everywhere at once. +- **Open design.** The design and the code are public; what protects a + deployment is its keys. +- **Validation that matches the start.** `--validate` runs the checks a start + runs (key permissions, the PQC provider, the configuration), so a + configuration that passes is one that starts. + +## Common errors and their countermeasures + +| Class | Countermeasure | Where | +|-------|----------------|-------| +| Request smuggling, desync (CWE-444) | HTTP/1.1 is parsed by hyper; each request reaches a backend framed by the proxy's own client, with hop-by-hop headers removed. A request is sent again on a new connection only when it is idempotent. The WAF scores a request that carries both `Content-Length` and `Transfer-Encoding` | `proxy.rs`, `backend_client.rs`, `waf.rs` | +| Path confusion, route bypass (CWE-22, CWE-863) | One canonical path (dot segments resolved, percent-encoded unreserved characters decoded) is what every listener routes and forwards on | `path_canon.rs` | +| Spoofed client identity (CWE-348) | `X-Forwarded-For` is believed only from `trusted_proxies`; forwarding headers a client sends about itself are not passed to backends | `security.rs`, `http_listener/mod.rs`, `quic_listener/request.rs` | +| Resource exhaustion (CWE-400, CWE-770) | Every table keyed by a client's choice has a ceiling enforced where entries are made; request bodies have a size limit, a memory budget across all requests and a minimum arrival rate; connection limits in all and per address; QUIC's address validation and amplification limit | `bounded.rs`, `body_budget.rs`, `body_pace.rs`, `conn_limits.rs` | +| A panic on untrusted input (CWE-248) | Release builds abort on a panic, so every parser that reads a client's or a peer's bytes has a coverage-guided fuzz target, run under AddressSanitizer on each pull request that touches it and daily | `fuzz/`, `src/fuzzing.rs` | +| Memory safety (CWE-119, CWE-787) | Rust; `unsafe` is denied crate-wide and allowed only at a C or kernel boundary, each block with a `SAFETY` comment that clippy requires | `Cargo.toml` `[lints]` | +| Deadlock across `.await` (CWE-833) | Clippy refuses a lock guard held across an `.await`, the map shard guards included | `clippy.toml` | +| Replay (CWE-294) | 0-RTT is off by default; when on, a repeated ClientHello is refused and routes answer early data with 425. A signed request carries a timestamp and a nonce, each nonce accepted once | `early_data.rs`, `route_gate.rs` | +| Brute force, authentication bypass (CWE-307, CWE-287) | The admin token is compared in constant time; failing callers are locked out per address and globally with back-off, while a correct token always passes | `admin.rs` | +| Secrets in logs or source (CWE-532, CWE-798) | Secrets are read from systemd credentials or files, never logged; a generated admin token goes to a file only the proxy's user reads; gitleaks runs on every push and GitHub's secret scanning with push protection is on | `secret_source.rs`, `.github/workflows/secret-scan.yml` | +| Server-side request forgery, open relay (CWE-918) | Backends come from the configuration, and loopback and link-local backend addresses are refused; CONNECT-UDP and CONNECT-IP relay only to `allowed_targets`, for `allowed_clients` | `config.rs`, `connect_udp.rs`, `connect_ip.rs` | +| Regular-expression denial of service (CWE-1333) | Every pattern, the Core Rule Set's included, runs on the `regex` crate, whose matching time is linear in the input | `waf.rs`, `vendor/zentinel-modsec` | +| Command injection (CWE-78) | No input reaches a shell: the processes the proxy starts take their arguments as a list | | +| Weak or misused cryptography (CWE-327, CWE-338) | Library primitives only, TLS 1.3 by default, hybrid ML-KEM, keys and nonces from AWS-LC's generator | [CRYPTOGRAPHY.md](CRYPTOGRAPHY.md) | +| Vulnerable or tampered dependencies (CWE-1395) | cargo-deny (advisories, licences, sources, bans) and cargo-audit over every lockfile; GitHub Actions pinned by commit; releases with signed SLSA provenance | `deny.toml`, `.github/workflows/` | + +## How it is checked + +On every pull request and push to `main`, CI runs rustfmt, clippy (`all`, +`pedantic` and `nursery`, warnings as errors), the tests on Linux and macOS, +the integration tests, each vendored fork's own tests, cargo-deny, +cargo-audit, CodeQL's security and quality queries, the REUSE licensing +check, coverage and the fuzz targets a change reaches. ClusterFuzzLite runs +every fuzz target for an hour each day, CodeQL weekly, and the OpenSSF +Scorecard on every push. `pentests/` holds the WAF regression corpus and the +gate a deployment passes before it takes traffic. diff --git a/examples/speedtest-probe.rs b/examples/speedtest-probe.rs index 5d203edf..a272d9de 100644 --- a/examples/speedtest-probe.rs +++ b/examples/speedtest-probe.rs @@ -170,11 +170,13 @@ async fn download(conn: &Connection, streams: usize, secs: u64) -> (u64, f64) { /// runs ahead of the network by at most the send buffers, and is all a node /// without the meter can be judged by). async fn upload(conn: &Connection, streams: usize, secs: u64) -> Result<(Value, u64), Error> { - let test = format!("{:032x}", rand::random::()); + let test = pqcrypta_proxy::secure_random::hex::<16>(); let written = Arc::new(AtomicU64::new(0)); let deadline = Instant::now() + Duration::from_secs(secs); // Random bytes: nothing on the path can compress them. - let chunk: Arc> = Arc::new((0..64 * 1024).map(|_| rand::random::()).collect()); + let mut chunk = vec![0u8; 64 * 1024]; + pqcrypta_proxy::secure_random::fill(&mut chunk); + let chunk: Arc> = Arc::new(chunk); let tasks: Vec<_> = (0..streams) .map(|_| { let conn = conn.clone(); diff --git a/src/acme_dns.rs b/src/acme_dns.rs index edbafefd..dc264416 100644 --- a/src/acme_dns.rs +++ b/src/acme_dns.rs @@ -304,7 +304,7 @@ impl DnsUpdater { ttl: u32, rdata: &[u8], ) -> anyhow::Result<()> { - let id: u16 = rand::random(); + let id = crate::secure_random::u16(); let message = update_message(id, zone, owner, class, ttl, rdata)?; let (signed, mac) = sign(&message, &self.key, unix_now())?; let response = exchange(self.server, &signed).await?; @@ -421,7 +421,7 @@ fn unix_now() -> u64 { /// A standard query, recursion not asked for fn query(name: &str, rtype: u16) -> anyhow::Result> { let mut msg = Vec::with_capacity(HEADER_LEN + name.len() + 6); - msg.extend_from_slice(&rand::random::().to_be_bytes()); + msg.extend_from_slice(&crate::secure_random::bytes::<2>()); msg.extend_from_slice(&[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]); msg.extend(encode_name(name).ok_or_else(|| anyhow::anyhow!("{name} is not a domain name"))?); msg.extend_from_slice(&rtype.to_be_bytes()); diff --git a/src/admin.rs b/src/admin.rs index 392d734d..847c0b48 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -15,6 +15,7 @@ use std::time::{Duration, Instant}; use dashmap::DashMap; use subtle::ConstantTimeEq; +use axum::extract::rejection::JsonRejection; use axum::extract::{ConnectInfo, Path, Query, State}; use axum::http::{HeaderMap, StatusCode}; use axum::response::{IntoResponse, Json}; @@ -194,16 +195,9 @@ impl AdminServer { None } None => { - // P3-fix: use OsRng (cryptographically secure) instead of thread_rng - // (designed for simulation, not secret generation). - use rand::RngExt; - // The operating system's generator; rand's UnwrapErr makes its - // (fallible) source the infallible one sample_iter draws from - let token: String = rand::rand_core::UnwrapErr(rand::rngs::SysRng) - .sample_iter(&rand::distr::Alphanumeric) - .take(48) - .map(char::from) - .collect(); + // 48 letters and digits, each drawn evenly from the 62 + // (285 bits), from AWS-LC's generator + let token = crate::secure_random::alphanumeric(48); // SEC-06: the token goes to a file only its owner reads, never // to a log or a console: a service's stderr is its journal. let path = &self.config.generated_token_path; @@ -326,6 +320,10 @@ impl AdminServer { .route("/canary/resume/{server_id}", post(canary_resume_handler)) .route("/canary/weight/{server_id}", post(canary_weight_handler)) .route("/pools", get(pools_handler)) + .route( + "/pools/{pool}/servers/{server_id}/canary", + post(pool_canary_handler), + ) .route( "/pools/{pool}/servers/{server_id}/{action}", post(pool_server_handler), @@ -1668,7 +1666,6 @@ struct CanaryPoolRequest { pool: String, } -/// POST /canary/suspend/:server_id — suspend a canary server /// `GET /pools`: every load-balancer pool, its algorithm, queue and members. async fn pools_handler(State(state): State>) -> impl IntoResponse { match state.load_balancer { @@ -1685,18 +1682,83 @@ async fn pools_handler(State(state): State>) -> impl IntoRespons } } +/// `POST /pools/{pool}/servers/{server_id}/canary`: the member becomes the +/// pool's canary, taking `{"weight": n}` percent of new sessions, or, with no +/// body, stepping through the pool's ramp (`canary.ramp_percent`). Its own +/// route, matched ahead of the other actions', because it is the one action +/// with a body: read by the JSON extractor, which takes it only as +/// `application/json` and refuses a field [`CanaryStartRequest`] does not +/// name. A request without a body sends no Content-Type, as the admin +/// client's `--admin POST ` without `--admin-body` does. +async fn pool_canary_handler( + State(state): State>, + ConnectInfo(remote_addr): ConnectInfo, + Path((pool, server_id)): Path<(String, String)>, + request: Result>, JsonRejection>, +) -> impl IntoResponse { + let weight = match canary_weight(request) { + Ok(weight) => weight, + Err((status, error)) => { + return (status, Json(serde_json::json!({ "error": error }))).into_response(); + } + }; + let Some(ref lb) = state.load_balancer else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({"error": "load balancer not available"})), + ) + .into_response(); + }; + let started = lb.start_canary(&pool, &server_id, weight); + if let Some(ref logger) = state.audit_logger { + logger.log(AuditEvent::AdminAction { + ip: remote_addr.ip().to_string(), + action: "pool-server-canary".into(), + success: started.is_ok(), + detail: Some(format!("{pool}/{server_id}")), + }); + } + match started { + Ok(percent) => Json(serde_json::json!({ + "success": true, "pool": pool, "server": server_id, "action": "canary", + "weight_percent": percent, "ramp": weight.is_none(), + })) + .into_response(), + Err(error) => ( + StatusCode::CONFLICT, + Json(serde_json::json!({"error": error})), + ) + .into_response(), + } +} + +/// The share a canary request asks for: `Some(n)` from `{"weight": n}`, and +/// `None`, the pool's ramp, from a request without a body. A body that is not +/// `application/json`, is not JSON, or names a field the request does not +/// have is refused with the extractor's status and reason. +fn canary_weight( + request: Result>, JsonRejection>, +) -> Result, (StatusCode, String)> { + match request { + Ok(request) => Ok(request.and_then(|Json(r)| r.weight)), + Err(rejection) => Err(( + rejection.status(), + format!("body: {}", rejection.body_text()), + )), + } +} + /// `POST /pools/{pool}/servers/{server_id}/{action}`: `drain` (no new /// sessions; the ones it has kept for `connection_draining.timeout_secs`), /// `undrain`, `unhealthy` (out of rotation until marked healthy or its health /// check finds it), `healthy` (back in, breaker closed, in slow start where -/// the pool has it), `canary` (the pool's canary: `{"weight": n}` for a fixed -/// share, no body for the pool's ramp, `canary.ramp_percent`), `promote` (a -/// canary becomes a stable member and the members it replaces drain). +/// the pool has it), `promote` (a canary becomes a stable member and the +/// members it replaces drain). `canary` has a route of its own, +/// [`pool_canary_handler`]. None of these reads a body. async fn pool_server_handler( State(state): State>, ConnectInfo(remote_addr): ConnectInfo, Path((pool, server_id, action)): Path<(String, String, String)>, - body: axum::body::Bytes, ) -> impl IntoResponse { let Some(ref lb) = state.load_balancer else { return ( @@ -1711,43 +1773,6 @@ async fn pool_server_handler( "healthy" => lb.mark_healthy(&pool, &server_id), "unhealthy" => lb.mark_unhealthy(&pool, &server_id), "promote" => lb.promote(&pool, &server_id), - "canary" => { - let weight = if body.is_empty() { - None - } else { - match serde_json::from_slice::(&body) { - Ok(request) => request.weight, - Err(e) => { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({"error": format!("body: {e}")})), - ) - .into_response(); - } - } - }; - let started = lb.start_canary(&pool, &server_id, weight); - if let Some(ref logger) = state.audit_logger { - logger.log(AuditEvent::AdminAction { - ip: remote_addr.ip().to_string(), - action: "pool-server-canary".into(), - success: started.is_ok(), - detail: Some(format!("{pool}/{server_id}")), - }); - } - return match started { - Ok(percent) => Json(serde_json::json!({ - "success": true, "pool": pool, "server": server_id, "action": action, - "weight_percent": percent, "ramp": weight.is_none(), - })) - .into_response(), - Err(error) => ( - StatusCode::CONFLICT, - Json(serde_json::json!({"error": error})), - ) - .into_response(), - }; - } _ => { return ( StatusCode::BAD_REQUEST, @@ -2659,9 +2684,9 @@ mod auth_tests { #[tokio::test] async fn the_metrics_token_reads_the_metrics_unsigned_and_nothing_else() { // This run's own key and token, never values written into the tests - let metrics_token = hex::encode(rand::random::<[u8; 24]>()); + let metrics_token = crate::secure_random::hex::<24>(); let mut state = Arc::try_unwrap(state()).ok().expect("one owner"); - state.hmac_secret = Some(hex::encode(rand::random::<[u8; 32]>())); + state.hmac_secret = Some(crate::secure_random::hex::<32>()); state.metrics_token = Some(metrics_token.clone()); let auth = Arc::new(state); @@ -2720,3 +2745,102 @@ mod auth_tests { assert_eq!(call(&auth, TOKEN).await, StatusCode::OK); } } + +/// `POST /pools/{pool}/servers/{id}/canary` is the one pool action with a +/// body, and the only one that reads it +#[cfg(test)] +mod pool_canary_tests { + use super::*; + use axum::body::Body; + use tower::ServiceExt; + + /// The two routes as the admin router has them, each answering with the + /// handler it reached + fn router() -> Router { + Router::new() + .route( + "/pools/{pool}/servers/{server_id}/canary", + post( + |request: Result>, JsonRejection>| async move { + match canary_weight(request) { + Ok(weight) => (StatusCode::OK, format!("canary {weight:?}")), + Err((status, error)) => (status, error), + } + }, + ), + ) + .route( + "/pools/{pool}/servers/{server_id}/{action}", + post( + |Path((_, _, action)): Path<(String, String, String)>| async move { + (StatusCode::OK, format!("action {action}")) + }, + ), + ) + } + + async fn call( + path: &str, + content_type: Option<&str>, + body: &'static str, + ) -> (StatusCode, String) { + let mut request = axum::http::Request::builder().method("POST").uri(path); + if let Some(content_type) = content_type { + request = request.header("content-type", content_type); + } + let response = router() + .oneshot(request.body(Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let text = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + (status, String::from_utf8(text.to_vec()).unwrap()) + } + + #[tokio::test] + async fn canary_reaches_its_own_handler_and_the_other_actions_theirs() { + assert_eq!( + call("/pools/api/servers/a/canary", None, "").await, + (StatusCode::OK, "canary None".into()) + ); + assert_eq!( + call("/pools/api/servers/a/drain", None, "").await, + (StatusCode::OK, "action drain".into()) + ); + } + + #[tokio::test] + async fn a_weight_is_json_and_no_body_is_the_ramp() { + let json = Some("application/json"); + assert_eq!( + call("/pools/api/servers/a/canary", json, r#"{"weight": 25}"#).await, + (StatusCode::OK, "canary Some(25)".into()) + ); + assert_eq!( + call("/pools/api/servers/a/canary", json, "{}").await, + (StatusCode::OK, "canary None".into()) + ); + // Not JSON, a field the request does not have, a share past a u8, and + // a body that does not say it is JSON: each refused, none a ramp + for (content_type, body, status) in [ + (json, "{", StatusCode::BAD_REQUEST), + ( + json, + r#"{"weight": 25, "ramp": false}"#, + StatusCode::UNPROCESSABLE_ENTITY, + ), + (json, r#"{"weight": 300}"#, StatusCode::UNPROCESSABLE_ENTITY), + ( + Some("text/plain"), + r#"{"weight": 25}"#, + StatusCode::UNSUPPORTED_MEDIA_TYPE, + ), + ] { + let (got, text) = call("/pools/api/servers/a/canary", content_type, body).await; + assert_eq!(got, status, "{body}: {text}"); + assert!(text.starts_with("body: "), "{text}"); + } + } +} diff --git a/src/admin_client.rs b/src/admin_client.rs index bd697624..34c1567a 100644 --- a/src/admin_client.rs +++ b/src/admin_client.rs @@ -97,7 +97,7 @@ pub async fn send( .unwrap_or_default() .as_secs() .to_string(); - let nonce = hex::encode(rand::random::<[u8; 16]>()); + let nonce = crate::secure_random::hex::<16>(); let signature = crate::route_gate::admin_request_signature( secret, method.as_str(), diff --git a/src/bin/ech-keygen.rs b/src/bin/ech-keygen.rs index 51d78728..b7a3d5ae 100644 --- a/src/bin/ech-keygen.rs +++ b/src/bin/ech-keygen.rs @@ -229,7 +229,7 @@ fn pick_unused_config_id(out_dir: &std::path::Path) -> u8 { .collect(); loop { - let candidate: u8 = rand::random(); + let candidate = rand::random_range(0..=u8::MAX); if !used.contains(&candidate) { return candidate; } diff --git a/src/challenge.rs b/src/challenge.rs index 18184038..12caa482 100644 --- a/src/challenge.rs +++ b/src/challenge.rs @@ -150,7 +150,7 @@ impl Default for Challenger { impl Challenger { pub fn new() -> Self { Self { - process_secret: rand::random(), + process_secret: crate::secure_random::bytes(), spent: Mutex::new(HashMap::new()), issued: AtomicU64::new(0), passed: AtomicU64::new(0), @@ -177,10 +177,10 @@ impl Challenger { let max_number = config.max_number.max(1); let salt = format!( "{}?expires={}", - hex::encode(rand::random::<[u8; 12]>()), + crate::secure_random::hex::<12>(), now + CHALLENGE_TTL_SECS ); - let number = rand::random_range(0..=max_number); + let number = crate::secure_random::up_to(max_number); let challenge = hex::encode(Sha256::digest(format!("{salt}{number}"))); let signature = self.signature(config, &challenge, &salt, ip); self.issued.fetch_add(1, Ordering::Relaxed); diff --git a/src/conformance/session.rs b/src/conformance/session.rs index 027ba7a0..5b5ad872 100644 --- a/src/conformance/session.rs +++ b/src/conformance/session.rs @@ -1732,14 +1732,7 @@ impl Registry { /// only what the requester's own client did — but they are unguessable so that /// one developer's in-progress run is not trivially enumerable by another. fn new_session_id() -> String { - use std::fmt::Write as _; - let mut bytes = [0u8; 16]; - rand::fill(&mut bytes); - bytes.iter().fold(String::with_capacity(32), |mut acc, b| { - // Cannot fail: writing to a String is infallible. - let _ = write!(acc, "{b:02x}"); - acc - }) + crate::secure_random::hex::<16>() } #[cfg(test)] diff --git a/src/connect_ip.rs b/src/connect_ip.rs index c3e8dcfa..2a365f89 100644 --- a/src/connect_ip.rs +++ b/src/connect_ip.rs @@ -269,7 +269,7 @@ pub struct Assigned { /// This process's IPv6 unique local prefix (RFC 4193): fd00::/8 and a /// random 40-bit global ID, subnet 0 static ULA: LazyLock<[u8; 8]> = LazyLock::new(|| { - let id: [u8; 5] = rand::random(); + let id: [u8; 5] = crate::secure_random::bytes(); [0xfd, id[0], id[1], id[2], id[3], id[4], 0, 0] }); static NEXT_SESSION: AtomicU32 = AtomicU32::new(0); diff --git a/src/host_names.rs b/src/host_names.rs index 9cd43748..70500642 100644 --- a/src/host_names.rs +++ b/src/host_names.rs @@ -147,7 +147,7 @@ async fn resolve(resolver: SocketAddr, name: &str) -> anyhow::Result /// A recursive query that asks for the resolver's validation (AD, RFC 6840 §5.7) fn query(name: &str, rtype: u16) -> anyhow::Result> { let mut msg = Vec::with_capacity(HEADER_LEN + name.len() + 6); - msg.extend_from_slice(&rand::random::().to_be_bytes()); + msg.extend_from_slice(&crate::secure_random::bytes::<2>()); msg.extend_from_slice(&(FLAG_RD | FLAG_AD).to_be_bytes()); msg.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 0]); msg.extend(encode_name(name).ok_or_else(|| anyhow::anyhow!("{name} is not a domain name"))?); diff --git a/src/http_listener/mod.rs b/src/http_listener/mod.rs index b791e220..2b4b06d2 100644 --- a/src/http_listener/mod.rs +++ b/src/http_listener/mod.rs @@ -5942,7 +5942,7 @@ mod signed_body_tests { /// A value made for this run alone: the route's secret, a request's /// nonce. Nothing fixed is signed with or accepted fn fresh() -> String { - hex::encode(rand::random::<[u8; 16]>()) + crate::secure_random::hex::<16>() } /// What the recording backend saw: one entry per connection, the bytes it diff --git a/src/lib.rs b/src/lib.rs index 7ef28792..3e926dab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -191,6 +191,7 @@ pub mod request_id; pub mod request_target; pub mod route_gate; pub mod secret_source; +pub mod secure_random; pub mod security; pub mod service_notify; pub mod speedtest; diff --git a/src/load_balancer.rs b/src/load_balancer.rs index c7ee1277..71a2705a 100644 --- a/src/load_balancer.rs +++ b/src/load_balancer.rs @@ -1370,7 +1370,7 @@ impl BackendPool { let Some(factor) = chosen.ramp_factor() else { return chosen; }; - if rand::random::() < factor { + if rand::random_range(0.0..1.0) < factor { return chosen; } self.get_healthy_servers() diff --git a/src/quic_listener/mod.rs b/src/quic_listener/mod.rs index 7232a8fe..7236d6bf 100644 --- a/src/quic_listener/mod.rs +++ b/src/quic_listener/mod.rs @@ -3943,7 +3943,7 @@ mod connect_parity_tests { let ws = route(&format!( "name = \"ws\"\nbackend = \"b\"\nsupports_websocket = true\npath_prefix = \"/ws\"\n\ [security]\nhmac_secret = \"{}\"\n", - hex::encode(rand::random::<[u8; 32]>()) + crate::secure_random::hex::<32>() )); let config = proxy_config(vec![ws.clone()]); assert_eq!( diff --git a/src/rate_limiter.rs b/src/rate_limiter.rs index d118406b..04add37c 100644 --- a/src/rate_limiter.rs +++ b/src/rate_limiter.rs @@ -4418,7 +4418,7 @@ mod redis_limit_tests { let dir = std::env::temp_dir().join(format!( "pqcp-redis-{}-{}", std::process::id(), - rand::random::() + crate::secure_random::hex::<4>() )); std::fs::create_dir_all(&dir).unwrap(); let socket = dir.join("redis.sock"); diff --git a/src/request_id.rs b/src/request_id.rs index 445ec318..9e846726 100644 --- a/src/request_id.rs +++ b/src/request_id.rs @@ -28,10 +28,9 @@ pub fn resolve(request_headers: &HeaderMap, name: &HeaderName) -> HeaderValue { return v.clone(); } } - let mut id = [0u8; 16]; - rand::fill(&mut id); // Hex is always a valid header value. - HeaderValue::from_str(&hex::encode(id)).unwrap_or_else(|_| HeaderValue::from_static("0")) + HeaderValue::from_str(&crate::secure_random::hex::<16>()) + .unwrap_or_else(|_| HeaderValue::from_static("0")) } #[cfg(test)] diff --git a/src/route_gate.rs b/src/route_gate.rs index a36c4d62..043eaf62 100644 --- a/src/route_gate.rs +++ b/src/route_gate.rs @@ -618,13 +618,13 @@ mod tests { /// A secret of this run's own: the gate verifies against the route's /// configured secret, whatever it is, not one written into its tests. fn test_secret() -> String { - hex::encode(rand::random::<[u8; 32]>()) + crate::secure_random::hex::<32>() } /// A nonce of this run's own, as a client makes one: never a value /// written into the tests. fn test_nonce() -> String { - hex::encode(rand::random::<[u8; 16]>()) + crate::secure_random::hex::<16>() } fn route() -> RouteConfig { @@ -1065,7 +1065,7 @@ mod tests { use sha2::Sha256; // A key of this run's own: the signature is as good as one can be - let key = hex::encode(rand::random::<[u8; 32]>()); + let key = crate::secure_random::hex::<32>(); let mut r = route(); r.security = Some(crate::config::RouteSecurityPolicy { hmac_secret: Some(key.clone()), diff --git a/src/secure_random.rs b/src/secure_random.rs new file mode 100644 index 00000000..aeb41103 --- /dev/null +++ b/src/secure_random.rs @@ -0,0 +1,154 @@ +//! Keys, nonces and tokens: every value whose strength is that no one can +//! guess it comes from here. +//! +//! The source is AWS-LC's generator, the one the TLS stack draws its own +//! secrets from (`aws_lc_rs::rand`): a CTR-DRBG (NIST SP 800-90A), seeded and +//! reseeded from the operating system, whose state a forked child does not +//! share with its parent. `rand` stays for choices that protect nothing (a +//! load-balancing pick, a sampling roll, jitter), drawn with +//! `rand::random_range`; clippy refuses `rand::random` and `rand::fill` +//! (clippy.toml), so a secret is not drawn from a generator kept for those. + +use aws_lc_rs::rand::{SecureRandom, SystemRandom}; + +/// Fills `out` from the DRBG. +/// +/// # Panics +/// +/// If the generator fails, which AWS-LC reports only when the operating +/// system gives it no entropy. No secret can be made then, so none is. +pub fn fill(out: &mut [u8]) { + SystemRandom::new() + .fill(out) + .expect("the operating system gives AWS-LC's generator entropy"); +} + +/// `N` bytes from the DRBG. +/// +/// # Panics +/// +/// As [`fill`]. +#[must_use] +pub fn bytes() -> [u8; N] { + // The array comes out of the generator whole, as AWS-LC's `Random`: no + // value of this module's making is ever a key, not even for the moment + // before it is filled + aws_lc_rs::rand::generate(&SystemRandom::new()) + .expect("the operating system gives AWS-LC's generator entropy") + .expose() +} + +/// `N` bytes from the DRBG, as lowercase hex (`2 * N` characters). +/// +/// # Panics +/// +/// As [`fill`]. +#[must_use] +pub fn hex() -> String { + hex::encode(bytes::()) +} + +/// A `u16` from the DRBG: a DNS message ID, which an off-path spoofer must +/// guess (RFC 5452). +/// +/// # Panics +/// +/// As [`fill`]. +#[must_use] +pub fn u16() -> u16 { + u16::from_ne_bytes(bytes()) +} + +/// `len` characters, each drawn evenly from the 62 ASCII letters and digits +/// (5.95 bits a character): a token a person may copy. +/// +/// # Panics +/// +/// As [`fill`]. +#[must_use] +pub fn alphanumeric(len: usize) -> String { + const SYMBOLS: &[u8; 62] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + (0..len) + .map(|_| { + #[expect(clippy::cast_possible_truncation, reason = "up_to(61) is below 62")] + let index = up_to(61) as usize; + char::from(SYMBOLS[index]) + }) + .collect() +} + +/// An integer in `0..=max`, each as likely as any other. +/// +/// Draws below `2^64 mod (max + 1)` are drawn again, so the ones kept span +/// a whole number of `max + 1` blocks and the remainder favours none. +/// +/// # Panics +/// +/// As [`fill`]. +#[must_use] +pub fn up_to(max: u64) -> u64 { + let Some(span) = max.checked_add(1) else { + return u64::from_ne_bytes(bytes()); + }; + let rejected_below = span.wrapping_neg() % span; + loop { + let draw = u64::from_ne_bytes(bytes()); + if draw >= rejected_below { + return draw % span; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_draws_differ() { + assert_ne!(bytes::<32>(), bytes::<32>()); + assert_ne!(hex::<16>(), hex::<16>()); + } + + #[test] + fn alphanumeric_is_letters_and_digits_of_its_length() { + let token = alphanumeric(48); + assert_eq!(token.len(), 48); + assert!(token.bytes().all(|b| b.is_ascii_alphanumeric())); + assert_ne!(token, alphanumeric(48)); + } + + #[test] + fn hex_is_two_characters_a_byte() { + let token = hex::<24>(); + assert_eq!(token.len(), 48); + assert!(token + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())); + } + + #[test] + fn up_to_stays_in_range_and_reaches_both_ends() { + assert_eq!(up_to(0), 0); + let mut seen = [false; 4]; + for _ in 0..1000 { + let n = up_to(3); + assert!(n <= 3); + seen[usize::try_from(n).unwrap()] = true; + } + assert_eq!(seen, [true; 4]); + // The whole range, where no draw is ever rejected + let _ = up_to(u64::MAX); + } + + /// Each of three values is drawn about a third of the time + #[test] + fn up_to_is_even_over_its_range() { + let mut counts = [0u32; 3]; + for _ in 0..30_000 { + counts[usize::try_from(up_to(2)).unwrap()] += 1; + } + for count in counts { + assert!((9_000..=11_000).contains(&count), "{counts:?}"); + } + } +} diff --git a/src/telemetry.rs b/src/telemetry.rs index 5ef744ae..b6a0203d 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -125,7 +125,7 @@ const SESSION_MAX_DURATION: Duration = Duration::from_hours(1); // 60 minutes /// make them smaller than they are. static PAYLOAD: LazyLock> = LazyLock::new(|| { let mut bytes = vec![0u8; CHUNK_BYTES]; - rand::fill(bytes.as_mut_slice()); + crate::secure_random::fill(bytes.as_mut_slice()); bytes }); @@ -243,7 +243,7 @@ fn compute_intensity(cfg: &ImpairmentConfig, elapsed_s: f64) -> f64 { ImpairmentPattern::Fixed => cfg.intensity, ImpairmentPattern::Random => { - cfg.rand_min + rand::random::() * (cfg.rand_max - cfg.rand_min) + cfg.rand_min + rand::random_range(0.0..1.0) * (cfg.rand_max - cfg.rand_min) } ImpairmentPattern::Sine => { @@ -631,7 +631,7 @@ fn hold_back(imp: &ImpairmentConfig, elapsed_s: f64) -> Duration { let intensity = compute_intensity(imp, elapsed_s).max(0.0); let ms = match imp.imp_type { ImpairmentType::DelayMs => intensity, - ImpairmentType::JitterMs => rand::random::() * intensity * 2.0, + ImpairmentType::JitterMs => rand::random_range(0.0..1.0) * intensity * 2.0, _ => 0.0, }; Duration::from_secs_f64(ms.min(10_000.0) / 1000.0) diff --git a/src/ws_tunnel.rs b/src/ws_tunnel.rs index 0d67b03e..471093f3 100644 --- a/src/ws_tunnel.rs +++ b/src/ws_tunnel.rs @@ -153,8 +153,7 @@ where let made_key = client_key.is_none(); let key = client_key.unwrap_or_else(|| { - let mut nonce = [0u8; 16]; - rand::fill(&mut nonce); + let nonce = crate::secure_random::bytes::<16>(); HeaderValue::from_str(&base64::engine::general_purpose::STANDARD.encode(nonce)) .unwrap_or(HeaderValue::from_static("dGhlIHNhbXBsZSBub25jZQ==")) });