diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6180342d446..4901d5035a0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -99,7 +99,7 @@ jobs: RUST_BACKTRACE: 1 - name: cargo build (debug; no-std) - run: cargo build --locked --lib -p rustls $(admin/all-features-except std,brotli,read_buf rustls) + run: cargo build --locked --lib -p shaped-rustls $(admin/all-features-except std,brotli,read_buf shaped-rustls) - name: cargo build (debug; rustls-provider-example) run: cargo build --locked -p rustls-provider-example @@ -116,8 +116,8 @@ jobs: - name: cargo test (debug; rustls-provider-test; all features) run: cargo test --all-features -p rustls-provider-test - - name: cargo package --all-features -p rustls - run: cargo package --all-features -p rustls + - name: cargo package --all-features -p shaped-rustls + run: cargo package --all-features -p shaped-rustls msrv: name: MSRV @@ -130,16 +130,16 @@ jobs: - uses: dtolnay/rust-toolchain@master with: - toolchain: "1.71" + toolchain: "1.85" # zlib-rs is optional and requires a later MSRV - - run: cargo check --locked --lib $(admin/all-features-except zlib rustls) -p rustls + - run: cargo check --locked --lib $(admin/all-features-except zlib shaped-rustls) -p shaped-rustls - uses: dtolnay/rust-toolchain@master with: - toolchain: "1.75" + toolchain: "1.85" - - run: cargo check --locked --lib --all-features -p rustls + - run: cargo check --locked --lib --all-features -p shaped-rustls features: name: Features @@ -231,12 +231,6 @@ jobs: env: BOGO_SHIM_PROVIDER: aws-lc-rs-fips - - name: Run test suite (post-quantum) - working-directory: bogo - run: ./runme - env: - BOGO_SHIM_PROVIDER: post-quantum - fuzz: name: Smoke-test fuzzing targets runs-on: ubuntu-latest @@ -300,7 +294,7 @@ jobs: uses: dtolnay/rust-toolchain@nightly - name: cargo doc (rustls; all features) - run: cargo doc --locked --all-features --no-deps --document-private-items --package rustls + run: cargo doc --locked --all-features --no-deps --document-private-items --package shaped-rustls env: RUSTDOCFLAGS: -Dwarnings @@ -405,8 +399,8 @@ jobs: tool: bindgen-cli - name: Enable bindgen feature for aws-lc-sys (as needed for many cross targets) if: ${{ matrix.target != 'i686-unknown-linux-gnu' }} - run: cargo add --dev --features bindgen 'aws-lc-sys@>0.20' --package rustls --verbose - - run: cross test --package rustls --target ${{ matrix.target }} + run: cargo add --dev --features bindgen 'aws-lc-sys@>0.20' --package shaped-rustls --verbose + - run: cross test --package shaped-rustls --target ${{ matrix.target }} semver: name: Check semver compatibility @@ -417,7 +411,22 @@ jobs: with: persist-credentials: false + # The check compares the API with the latest release on crates.io. Before + # the first release there is nothing to compare with, and it can only fail. + - name: Look for a release to compare with + id: release + run: | + code=$(curl --silent --output /dev/null --write-out '%{http_code}' \ + --user-agent 'shaped-rustls-ci (github.com/aimalygin/shaped-rustls)' \ + https://crates.io/api/v1/crates/shaped-rustls) + case "$code" in + 200) echo "found=true" >> "$GITHUB_OUTPUT" ;; + 404) echo "shaped-rustls has no release on crates.io yet: nothing to compare with" ;; + *) echo "crates.io answered $code"; exit 1 ;; + esac + - name: Check semver + if: steps.release.outputs.found == 'true' uses: obi1kenobi/cargo-semver-checks-action@v2 format: @@ -480,26 +489,6 @@ jobs: components: clippy - run: ./admin/clippy -- --deny warnings - clippy-nightly: - name: Clippy (Nightly) - runs-on: ubuntu-latest - steps: - - name: Checkout sources - uses: actions/checkout@v4 - with: - persist-credentials: false - - - name: Install valgrind - if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y valgrind - - - name: Install rust toolchain - uses: dtolnay/rust-toolchain@nightly - with: - components: clippy - # Do not deny warnings, as nightly clippy sometimes has false negatives. - - run: ./admin/clippy - check-external-types: name: Validate external types appearing in public API runs-on: ubuntu-latest @@ -511,7 +500,7 @@ jobs: - name: Install rust toolchain uses: dtolnay/rust-toolchain@master with: - toolchain: nightly-2025-10-18 + toolchain: nightly-2026-03-20 # ^ sync with https://github.com/awslabs/cargo-check-external-types/blob/main/rust-toolchain.toml - name: Install cargo-check-external-types uses: taiki-e/cache-cargo-install-action@v3 @@ -521,23 +510,6 @@ jobs: working-directory: rustls/ run: cargo check-external-types - taplo: - name: Taplo - runs-on: ubuntu-latest - steps: - - name: Checkout sources - uses: actions/checkout@v4 - with: - persist-credentials: false - - - name: Install rust toolchain - uses: dtolnay/rust-toolchain@stable - - name: Install taplo-cli - uses: taiki-e/cache-cargo-install-action@v3 - with: - tool: taplo-cli - - run: taplo format --check - openssl-tests: name: Run openssl-tests runs-on: ubuntu-latest diff --git a/.github/workflows/cifuzz.yml b/.github/workflows/cifuzz.yml index 8f5cc258208..23030668741 100644 --- a/.github/workflows/cifuzz.yml +++ b/.github/workflows/cifuzz.yml @@ -7,6 +7,8 @@ concurrency: jobs: Fuzzing: + # OSS-Fuzz knows the upstream project only. + if: github.repository == 'rustls/rustls' runs-on: ubuntu-latest steps: - name: Build Fuzzers diff --git a/.github/workflows/daily-tests.yml b/.github/workflows/daily-tests.yml index f3b28127f2c..2a00a911548 100644 --- a/.github/workflows/daily-tests.yml +++ b/.github/workflows/daily-tests.yml @@ -149,7 +149,7 @@ jobs: - name: Check feature powerset run: > cargo hack check - --package rustls + --package shaped-rustls --feature-powerset --no-dev-deps --group-features aws_lc_rs,aws-lc-rs diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index caef3cfdf3b..25160d397bf 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -39,7 +39,7 @@ jobs: - name: cargo doc # keep features in sync with Cargo.toml `[package.metadata.docs.rs]` section - run: cargo doc --locked --features read_buf,ring --no-deps --package rustls + run: cargo doc --locked --features read_buf,ring --no-deps --package shaped-rustls env: RUSTDOCFLAGS: -Dwarnings --cfg=rustls_docsrs --html-after-content tag.html diff --git a/.github/workflows/shaped.yml b/.github/workflows/shaped.yml new file mode 100644 index 00000000000..27cef8d6aaf --- /dev/null +++ b/.github/workflows/shaped.yml @@ -0,0 +1,43 @@ +name: shaped-rustls + +permissions: + contents: read + +on: + push: + branches: ['shaped/**', 'xray/**'] + pull_request: + branches: ['shaped/**', 'xray/**'] + +concurrency: + group: shaped-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Tests (${{ matrix.features }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + features: + - ring + - ring,brotli,zlib + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - name: Library, integration and doc tests + run: cargo test --locked -p shaped-rustls --features ${{ matrix.features }} + + package: + name: Package + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - name: Build the crate as crates.io would receive it + run: cargo package --locked -p shaped-rustls diff --git a/Cargo.lock b/Cargo.lock index cdd379a4617..2f4fbe5fb84 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -39,9 +39,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -54,9 +54,9 @@ checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" [[package]] name = "alloc-stdlib" -version = "0.2.2" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ "alloc-no-stdlib", ] @@ -119,9 +119,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.102" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "asn1" @@ -135,9 +135,9 @@ dependencies = [ [[package]] name = "asn1-rs" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" dependencies = [ "asn1-rs-derive", "asn1-rs-impl", @@ -157,7 +157,7 @@ checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", "synstructure", ] @@ -169,7 +169,7 @@ checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -180,18 +180,18 @@ checksum = "cdccf849b54365e3693e9a90ad36e4482b79937e6373ac8e2cf229c985187b21" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "async-trait" -version = "0.1.89" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -202,29 +202,30 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-fips-sys" -version = "0.13.14" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3d619165468401dec3caa3366ebffbcb83f2f31883e5b3932f8e2dec2ddc568" +checksum = "118303cd75f63d1933a90c2ceb7e697281ac6acbdbcc490b46419f25a527ab90" dependencies = [ "bindgen", "cc", "cmake", "dunce", "fs_extra", + "pkg-config", "regex", ] [[package]] name = "aws-lc-rs" -version = "1.16.3" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec6fb3fe69024a75fa7e1bfb48aa6cf59706a101658ea01bfd33b2b248a038f" +checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e" dependencies = [ "aws-lc-fips-sys", "aws-lc-sys", @@ -234,14 +235,15 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.40.0" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7" +checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483" dependencies = [ "cc", "cmake", "dunce", "fs_extra", + "pkg-config", ] [[package]] @@ -256,6 +258,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -274,25 +282,40 @@ version = "0.72.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cexpr", "clang-sys", - "itertools 0.13.0", + "itertools 0.10.5", "log", "prettyplease", "proc-macro2", "quote", "regex", "rustc-hash", - "shlex", - "syn", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", ] [[package]] name = "bitflags" -version = "2.11.1" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" [[package]] name = "block-buffer" @@ -307,19 +330,18 @@ dependencies = [ name = "bogo" version = "0.1.0" dependencies = [ - "base64", + "base64 0.22.1", "env_logger", "nix", - "rustls", - "rustls-post-quantum", "rustls-webpki", + "shaped-rustls", ] [[package]] name = "brotli" -version = "8.0.2" +version = "8.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -328,9 +350,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "5.0.0" +version = "5.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -338,9 +360,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.2" +version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "byteorder" @@ -350,9 +372,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cast" @@ -362,14 +384,14 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.2.60" +version = "1.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", ] [[package]] @@ -389,9 +411,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" @@ -404,6 +426,17 @@ dependencies = [ "cpufeatures 0.2.17", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chacha20poly1305" version = "0.10.1" @@ -411,7 +444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" dependencies = [ "aead", - "chacha20", + "chacha20 0.9.1", "cipher", "poly1305", "zeroize", @@ -457,9 +490,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.8.1" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" dependencies = [ "glob", "libc", @@ -468,9 +501,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.1" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" dependencies = [ "clap_builder", "clap_derive", @@ -478,9 +511,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.0" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" dependencies = [ "anstream", "anstyle", @@ -490,14 +523,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.1" +version = "4.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -521,12 +554,38 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "const-oid" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "core-models" version = "0.0.5" @@ -535,7 +594,7 @@ checksum = "657f625ff361906f779745d08375ae3cc9fef87a35fba5f22874cf773010daf4" dependencies = [ "hax-lib", "pastey", - "rand 0.9.4", + "rand 0.9.5", ] [[package]] @@ -549,9 +608,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] @@ -606,18 +665,18 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "crossbeam-channel" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -625,18 +684,18 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" [[package]] name = "crunchy" @@ -707,14 +766,45 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "data-encoding" -version = "2.10.0" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "defmt" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror", +] [[package]] name = "der" @@ -745,9 +835,6 @@ name = "deranged" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "powerfmt", -] [[package]] name = "digest" @@ -772,13 +859,13 @@ dependencies = [ [[package]] name = "displaydoc" -version = "0.2.5" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -803,9 +890,9 @@ dependencies = [ [[package]] name = "either" -version = "1.15.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" [[package]] name = "elliptic-curve" @@ -827,23 +914,11 @@ dependencies = [ "zeroize", ] -[[package]] -name = "enum-as-inner" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "env_filter" -version = "1.0.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" dependencies = [ "log", "regex", @@ -851,9 +926,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.11.10" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" dependencies = [ "anstream", "anstyle", @@ -886,9 +961,9 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" [[package]] name = "find-msvc-tools" -version = "0.1.9" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" [[package]] name = "fnv" @@ -934,44 +1009,56 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "futures-channel" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", ] [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -1013,16 +1100,14 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", "rand_core 0.10.1", - "wasip2", - "wasip3", ] [[package]] @@ -1037,9 +1122,9 @@ dependencies = [ [[package]] name = "glob" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "graviola" @@ -1064,9 +1149,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.13" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" dependencies = [ "atomic-waker", "bytes", @@ -1103,9 +1188,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.17.0" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "hax-lib" @@ -1128,7 +1213,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1157,26 +1242,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] -name = "hickory-proto" -version = "0.25.2" +name = "hickory-net" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502" +checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" dependencies = [ "async-trait", "bytes", "cfg-if", "data-encoding", - "enum-as-inner", "futures-channel", "futures-io", "futures-util", "h2", + "hickory-proto", "http", "idna", "ipnet", - "once_cell", - "rand 0.9.4", - "ring", + "jni", + "rand 0.10.2", "rustls", "thiserror", "tinyvec", @@ -1184,31 +1268,56 @@ dependencies = [ "tokio-rustls", "tracing", "url", - "webpki-roots 0.26.11", + "webpki-roots", +] + +[[package]] +name = "hickory-proto" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +dependencies = [ + "data-encoding", + "idna", + "ipnet", + "jni", + "once_cell", + "prefix-trie", + "rand 0.10.2", + "ring", + "thiserror", + "tinyvec", + "tracing", + "url", ] [[package]] name = "hickory-resolver" -version = "0.25.2" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a" +checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" dependencies = [ "cfg-if", "futures-util", + "hickory-net", "hickory-proto", "ipconfig", + "ipnet", + "jni", "moka", + "ndk-context", "once_cell", "parking_lot", - "rand 0.9.4", + "rand 0.10.2", "resolv-conf", "rustls", "smallvec", + "system-configuration", "thiserror", "tokio", "tokio-rustls", "tracing", - "webpki-roots 0.26.11", + "webpki-roots", ] [[package]] @@ -1267,7 +1376,7 @@ dependencies = [ "libcrux-hkdf", "libcrux-kem", "libcrux-traits", - "rand 0.10.1", + "rand 0.10.2", "rand_chacha 0.10.0", "rand_core 0.10.1", "zeroize", @@ -1286,7 +1395,7 @@ dependencies = [ "k256", "p256", "p384", - "rand 0.8.6", + "rand 0.8.8", "rand_chacha 0.3.1", "rand_core 0.10.1", "rand_core 0.6.4", @@ -1298,9 +1407,9 @@ dependencies = [ [[package]] name = "http" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" dependencies = [ "bytes", "itoa", @@ -1308,18 +1417,18 @@ dependencies = [ [[package]] name = "hybrid-array" -version = "0.4.12" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ "typenum", ] [[package]] name = "icu_collections" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" dependencies = [ "displaydoc", "potential_utf", @@ -1331,9 +1440,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", @@ -1344,9 +1453,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -1358,16 +1467,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" [[package]] name = "icu_properties" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -1378,15 +1488,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" [[package]] name = "icu_provider" -version = "2.2.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", @@ -1397,12 +1507,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "idna" version = "1.1.0" @@ -1416,9 +1520,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" dependencies = [ "icu_normalizer", "icu_properties", @@ -1426,14 +1530,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.0" +version = "2.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" dependencies = [ "equivalent", - "hashbrown 0.17.0", - "serde", - "serde_core", + "hashbrown 0.17.1", ] [[package]] @@ -1460,9 +1562,12 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.12.0" +version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" +dependencies = [ + "serde", +] [[package]] name = "is_terminal_polyfill" @@ -1505,10 +1610,12 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.23" +version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" dependencies = [ + "defmt", + "jiff-core", "jiff-static", "log", "portable-atomic", @@ -1516,15 +1623,74 @@ dependencies = [ "serde_core", ] +[[package]] +name = "jiff-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +dependencies = [ + "defmt", +] + [[package]] name = "jiff-static" -version = "0.2.23" +version = "0.2.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" dependencies = [ "proc-macro2", "quote", - "syn", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", ] [[package]] @@ -1539,11 +1705,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.95" +version = "0.3.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" dependencies = [ - "once_cell", + "cfg-if", + "futures-util", "wasm-bindgen", ] @@ -1559,12 +1726,12 @@ dependencies = [ [[package]] name = "keccak" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e24a010dd405bd7ed803e5253182815b41bf2e6a80cc3bfc066658e03a198aa" +checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598" dependencies = [ "cfg-if", - "cpufeatures 0.3.0", + "cpufeatures 0.3.1", ] [[package]] @@ -1576,17 +1743,11 @@ dependencies = [ "spin", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "libc" -version = "0.2.185" +version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" [[package]] name = "libcrux-aead" @@ -1645,7 +1806,7 @@ checksum = "b65f73ce79337c762eb38bbac91e4c9b9e60cf318e8501b812750c640814d45e" dependencies = [ "libcrux-curve25519", "libcrux-p256", - "rand 0.9.4", + "rand 0.9.5", ] [[package]] @@ -1701,7 +1862,7 @@ dependencies = [ "libcrux-p256", "libcrux-sha3", "libcrux-traits", - "rand 0.9.4", + "rand 0.9.5", ] [[package]] @@ -1711,7 +1872,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffd6aa2dcd5be681662001b81d493f1569c6d49a32361f470b0c955465cd0338" dependencies = [ "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1726,7 +1887,7 @@ dependencies = [ "libcrux-secrets", "libcrux-sha3", "libcrux-traits", - "rand 0.9.4", + "rand 0.9.5", "tls_codec", ] @@ -1801,7 +1962,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e4fa89f3f5e34b47f928b22b1b78395a0d4ec23b1f583db635f128159d65f" dependencies = [ "libcrux-secrets", - "rand 0.9.4", + "rand 0.9.5", ] [[package]] @@ -1822,9 +1983,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "litemap" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "lock_api" @@ -1837,31 +1998,31 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "macro_rules_attribute" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520" +checksum = "b3ae8f6d608c795738406608304d30a2dfbdc8e58e44f7ba43236da5208ded3c" dependencies = [ "macro_rules_attribute-proc_macro", - "paste", + "pastey", ] [[package]] name = "macro_rules_attribute-proc_macro" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30" +checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" [[package]] name = "memchr" -version = "2.8.0" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "minimal-lexical" @@ -1871,9 +2032,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "mio" -version = "1.2.0" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" dependencies = [ "libc", "log", @@ -1883,9 +2044,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.12.15" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957228ad12042ee839f93c8f257b62b4c0ab5eaae1d4fa60de53b27c9d7c5046" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" dependencies = [ "crossbeam-channel", "crossbeam-epoch", @@ -1898,13 +2059,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + [[package]] name = "nix" version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cfg-if", "cfg_aliases", "libc", @@ -1922,9 +2089,9 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.6" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" dependencies = [ "num-integer", "num-traits", @@ -1941,33 +2108,32 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand 0.8.6", + "rand 0.8.8", "smallvec", "zeroize", ] [[package]] name = "num-conv" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "num-integer" -version = "0.1.46" +version = "0.1.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" dependencies = [ "num-traits", ] [[package]] name = "num-iter" -version = "0.1.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" dependencies = [ - "autocfg", "num-integer", "num-traits", ] @@ -2021,15 +2187,14 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openssl" -version = "0.10.78" +version = "0.10.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38c4372413cdaaf3cc79dd92d29d7d9f5ab09b51b10dded508fb90bb70b9222" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cfg-if", "foreign-types", "libc", - "once_cell", "openssl-macros", "openssl-sys", ] @@ -2042,14 +2207,14 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "openssl-sys" -version = "0.9.114" +version = "0.9.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13ce1245cd07fcc4cfdb438f7507b0c7e4f3849a69fd84d52374c66d83741bb6" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" dependencies = [ "cc", "libc", @@ -2102,25 +2267,19 @@ dependencies = [ "windows-link", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "pastey" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5a797f0e07bdf071d15742978fc3128ec6c22891c31a3a931513263904c982a" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" [[package]] name = "pem" -version = "3.0.6" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" dependencies = [ - "base64", + "base64 0.23.1", "serde_core", ] @@ -2159,9 +2318,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "plotters" @@ -2216,9 +2375,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.13.1" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "portable-atomic-util" @@ -2231,9 +2390,9 @@ dependencies = [ [[package]] name = "potential_utf" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ "zerovec", ] @@ -2253,6 +2412,17 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prefix-trie" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7" +dependencies = [ + "either", + "ipnet", + "num-traits", +] + [[package]] name = "prettyplease" version = "0.2.37" @@ -2260,7 +2430,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", - "syn", + "syn 2.0.119", ] [[package]] @@ -2291,23 +2461,23 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.45" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -2326,9 +2496,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha 0.3.1", @@ -2337,9 +2507,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.5", @@ -2347,11 +2517,12 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" dependencies = [ - "getrandom 0.4.2", + "chacha20 0.10.2", + "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -2431,9 +2602,9 @@ dependencies = [ [[package]] name = "rcgen" -version = "0.14.7" +version = "0.14.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10b99e0098aa4082912d4c649628623db6aba77335e4f4569ff5083a6448b32e" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" dependencies = [ "aws-lc-rs", "pem", @@ -2449,14 +2620,14 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.1", ] [[package]] name = "regex" -version = "1.12.3" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" dependencies = [ "aho-corasick", "memchr", @@ -2466,9 +2637,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.14" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -2477,9 +2648,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "resolv-conf" @@ -2558,35 +2729,17 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", - "base64", - "bencher", - "brotli", - "brotli-decompressor", - "env_logger", - "hashbrown 0.15.5", - "hex", "log", - "macro_rules_attribute", - "num-bigint", "once_cell", - "rcgen", - "ring", "rustls-pki-types", - "rustls-test", "rustls-webpki", - "rustversion", - "serde", - "serde_json", - "shake", "subtle", - "time", - "webpki-roots 1.0.7", - "x509-parser 0.17.0", "zeroize", - "zlib-rs", ] [[package]] @@ -2594,10 +2747,10 @@ name = "rustls-bench" version = "0.1.0" dependencies = [ "clap", - "rustls", "rustls-graviola", "rustls-post-quantum", "rustls-test", + "shaped-rustls", "tikv-jemallocator", ] @@ -2613,9 +2766,9 @@ dependencies = [ "itertools 0.14.0", "rayon", "rustc-hash", - "rustls", "rustls-fuzzing-provider", "rustls-test", + "shaped-rustls", "tikv-jemallocator", ] @@ -2623,10 +2776,9 @@ dependencies = [ name = "rustls-connect-tests" version = "0.0.1" dependencies = [ - "hickory-resolver", "regex", "ring", - "rustls", + "shaped-rustls", "tokio", ] @@ -2640,10 +2792,10 @@ dependencies = [ "log", "mio", "rcgen", - "rustls", "serde", + "shaped-rustls", "tokio", - "webpki-roots 1.0.7", + "webpki-roots", ] [[package]] @@ -2651,7 +2803,7 @@ name = "rustls-fuzzing-provider" version = "0.1.0" dependencies = [ "env_logger", - "rustls", + "shaped-rustls", ] [[package]] @@ -2669,18 +2821,18 @@ name = "rustls-openssl-tests" version = "0.0.1" dependencies = [ "asn1", - "base64", + "base64 0.22.1", "num-bigint", "once_cell", "openssl", - "rustls", + "shaped-rustls", ] [[package]] name = "rustls-pki-types" -version = "1.14.0" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ "zeroize", ] @@ -2691,8 +2843,8 @@ version = "0.2.2" dependencies = [ "criterion", "env_logger", - "rustls", - "webpki-roots 1.0.7", + "shaped-rustls", + "webpki-roots", ] [[package]] @@ -2712,10 +2864,10 @@ dependencies = [ "rand_core 0.6.4", "rcgen", "rsa", - "rustls", "sha2", + "shaped-rustls", "signature", - "webpki-roots 1.0.7", + "webpki-roots", "x25519-dalek", ] @@ -2724,24 +2876,24 @@ name = "rustls-provider-test" version = "0.1.0" dependencies = [ "hex", - "rustls", "rustls-provider-example", "serde", "serde_json", + "shaped-rustls", ] [[package]] name = "rustls-test" version = "0.1.0" dependencies = [ - "rustls", + "shaped-rustls", ] [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -2751,9 +2903,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "same-file" @@ -2792,9 +2944,9 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -2802,29 +2954,29 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] name = "serde_json" -version = "1.0.149" +version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ "itoa", "memchr", @@ -2855,12 +3007,51 @@ dependencies = [ "sponge-cursor", ] +[[package]] +name = "shaped-rustls" +version = "0.23.4600" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "bencher", + "brotli", + "brotli-decompressor", + "env_logger", + "hashbrown 0.15.5", + "hex", + "log", + "macro_rules_attribute", + "num-bigint", + "once_cell", + "rcgen", + "ring", + "rustls-pki-types", + "rustls-test", + "rustls-webpki", + "rustversion", + "serde", + "serde_json", + "shake", + "subtle", + "time", + "webpki-roots", + "x509-parser 0.17.0", + "zeroize", + "zlib-rs", +] + [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signature" version = "2.2.0" @@ -2871,6 +3062,22 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -2879,15 +3086,15 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" [[package]] name = "socket2" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", "windows-sys 0.61.2", @@ -2895,9 +3102,9 @@ dependencies = [ [[package]] name = "spin" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" [[package]] name = "spki" @@ -2935,9 +3142,20 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.117" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" dependencies = [ "proc-macro2", "quote", @@ -2952,7 +3170,28 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.1", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", ] [[package]] @@ -2963,22 +3202,22 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -3003,12 +3242,11 @@ dependencies = [ [[package]] name = "time" -version = "0.3.47" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "itoa", "num-conv", "powerfmt", "serde_core", @@ -3018,15 +3256,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] name = "time-macros" -version = "0.2.27" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" dependencies = [ "num-conv", "time-core", @@ -3034,9 +3272,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" dependencies = [ "displaydoc", "zerovec", @@ -3054,9 +3292,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" dependencies = [ "tinyvec_macros", ] @@ -3085,14 +3323,14 @@ checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "tokio" -version = "1.52.3" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -3105,13 +3343,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -3124,25 +3362,16 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls-smoke" -version = "0.0.0" -dependencies = [ - "rcgen", - "rustls", - "tokio", - "tokio-rustls", -] - [[package]] name = "tokio-util" -version = "0.7.18" +version = "0.7.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -3168,9 +3397,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.20.0" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicode-ident" @@ -3178,12 +3407,6 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "universal-hash" version = "0.5.1" @@ -3232,11 +3455,11 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.23.1" +version = "1.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" dependencies = [ - "getrandom 0.4.2", + "getrandom 0.4.3", "js-sys", "wasm-bindgen", ] @@ -3271,27 +3494,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.3+wasi-0.2.9" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.118" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" dependencies = [ "cfg-if", "once_cell", @@ -3302,9 +3516,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.118" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3312,65 +3526,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.118" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.119", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.118" +version = "0.2.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags", - "hashbrown 0.15.5", - "indexmap", - "semver", -] - [[package]] name = "web-sys" -version = "0.3.95" +version = "0.3.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" dependencies = [ "js-sys", "wasm-bindgen", @@ -3378,18 +3558,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "0.26.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" -dependencies = [ - "webpki-roots 1.0.7", -] - -[[package]] -name = "webpki-roots" -version = "1.0.7" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -3526,105 +3697,17 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "writeable" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "x25519-dalek" @@ -3675,18 +3758,19 @@ dependencies = [ [[package]] name = "yasna" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" dependencies = [ + "bit-vec", "time", ] [[package]] name = "yoke" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -3701,35 +3785,35 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.48" +version = "0.8.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.48" +version = "0.8.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "zerofrom" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] @@ -3742,7 +3826,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", "synstructure", ] @@ -3757,20 +3841,20 @@ dependencies = [ [[package]] name = "zeroize_derive" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] name = "zerotrie" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", @@ -3779,9 +3863,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ "yoke", "zerofrom", @@ -3790,23 +3874,23 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.3" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] name = "zlib-rs" -version = "0.6.3" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index a1a1ddad308..5b132b0d880 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,8 +6,6 @@ members = [ "ci-bench", # Network-based tests "connect-tests", - # tokio-rustls compatibility smoke test - "tokio-rustls-smoke", # tests and example code "examples", # Tests that require OpenSSL @@ -45,7 +43,7 @@ resolver = "2" anyhow = "1.0.73" asn1 = "0.22" async-trait = "0.1.74" -aws-lc-rs = { version = "1.14", default-features = false } +aws-lc-rs = { version = "1.18", default-features = false } base64 = "0.22" bencher = "0.1.5" brotli = { version = "8", default-features = false, features = ["std"] } @@ -60,7 +58,7 @@ ecdsa = "0.16.8" env_logger = "0.11" hashbrown = { version = "0.15", default-features = false, features = ["default-hasher", "inline-more"] } hex = "0.4" -hickory-resolver = { version = "0.25", features = ["https-aws-lc-rs", "webpki-roots"] } +hickory-resolver = { version = "0.26", features = ["https-aws-lc-rs", "webpki-roots"] } hmac = "0.12" hpke-rs = "0.6" hpke-rs-crypto = "0.6" @@ -94,7 +92,7 @@ subtle = { version = "2.5.0", default-features = false } time = { version = "0.3.6", default-features = false } tikv-jemallocator = "0.6" tokio = { version = "1.34", features = ["io-util", "macros", "net", "rt"] } -webpki = { package = "rustls-webpki", version = "0.103.5", features = ["alloc"], default-features = false } +webpki = { package = "rustls-webpki", version = "0.103.14", features = ["alloc"], default-features = false } webpki-roots = "1" x25519-dalek = "2" x509-parser = "0.17" @@ -104,8 +102,3 @@ zlib-rs = "0.6" [profile.bench] codegen-units = 1 lto = true - -# ensure all our tests are against the local copy, never -# against the latest _published_ copy. -[patch.crates-io] -rustls = { path = "rustls" } diff --git a/README.md b/README.md index 6a4449b7a00..92826daa7a1 100644 --- a/README.md +++ b/README.md @@ -6,16 +6,50 @@ Rustls is a modern TLS library written in Rust.

-# shaped-rustls ClientHello shaping branch - -This branch is based on rustls `0.23.40` and adds opt-in ClientHello shaping -support for xray/uTLS-compatible fingerprints. +# shaped-rustls + +shaped-rustls is a fork of [rustls](https://github.com/rustls/rustls) with an +opt-in API for shaping the TLS ClientHello, so that a client can send the hello +of a browser or of a uTLS profile byte for byte. It is not affiliated with or +endorsed by the rustls project: please report its bugs +[here](https://github.com/aimalygin/shaped-rustls/issues), not upstream. + +This release is rustls `0.23.46` with the shaping API on top. Everything below +the next heading is upstream's own README. + +The shaping API is dormant unless an application installs a +`ClientHelloCustomizer` on its `ClientConfig`; without one the crate sends what +upstream sends. `admin/check-clienthello-compat` compares the default +ClientHello of this checkout with the upstream tag byte for byte, normalizing +only the fields that must vary (the random, the session ID and the key share +bytes). + +Two things differ from upstream whether or not a customizer is installed: + +* an unknown extension in a TLS 1.3 certificate entry is ignored, where + upstream rejects the message. A shaped hello can offer extensions rustls does + not implement, and a peer may answer one there; Go's `crypto/tls` ignores + them as well. The BoGo test `SendUnknownExtensionOnCertificate-TLS13` is + disabled for that reason; +* the minimum Rust version is 1.85, not 1.71, because of the `shake` + dependency of the `aws_lc_rs` feature. + +## Using it + +The package is named `shaped-rustls`, and its library is still named `rustls`, +so code written for rustls compiles against it unchanged: + +```toml +[dependencies] +rustls = { package = "shaped-rustls", version = "0.23.4600" } +``` -The default rustls behavior is intended to remain compatible with upstream when -no `ClientHelloCustomizer` is configured. The shaping API is dormant unless an -application explicitly installs a customizer on `ClientConfig`. +Crates that depend on the `rustls` package itself, such as tokio-rustls, quinn +or hyper-rustls, keep using upstream rustls, and its types are not +interchangeable with this crate's. A shaped hello under one of them needs an +adapter built against this crate. -This branch adds primitives for: +## What it adds * fixed ClientHello random and session ID values; * custom and advertised cipher suites; @@ -24,12 +58,22 @@ This branch adds primitives for: * GREASE values and GREASE extension placement; * raw key shares and fixed X25519 key shares, including the classical X25519 component inside hybrid `X25519MLKEM768` key shares; -* padding and raw ClientHello capture for byte-level verification. +* padding, including BoringSSL's rule evaluated anew for each flight; +* a retried ClientHello, after a HelloRetryRequest that names a group, with + that group's key share alone, as uTLS sends it; +* raw ClientHello capture for byte-level verification. + +## Versions + +A version is `0.23.PPRR`: `PP` is the upstream rustls patch release this one +is based on and `RR` counts the fork's own releases on that base. `0.23.4600` +is the first release on rustls `0.23.46`; a fix of the fork alone would be +`0.23.4601`, and a move to rustls `0.23.47` would be `0.23.4700`. A `^0.23` +requirement therefore follows both, as it would for rustls. -The release tag for this work is `xray-rustls-0.23.40-1`. The helper script -`admin/check-clienthello-compat` compares the default ClientHello emitted by -this checkout against the upstream rustls tag and normalizes only fields that -must vary, such as random values and ephemeral key share bytes. +Security fixes of upstream rustls reach this crate only when it is rebased. +RustSec advisories are filed against `rustls`, and tools such as `cargo audit` +do not match them to `shaped-rustls`: check the upstream base named above. # Status @@ -37,10 +81,10 @@ Rustls is used in production at many organizations and projects. We aim to maint reasonable API surface stability but the API may evolve as we make changes to accommodate new features or performance improvements. -We have a [roadmap](ROADMAP.md) for our future plans. We also have [benchmarks](BENCHMARKING.md) to +We have a [roadmap](https://github.com/rustls/rustls/blob/rel-0.23/ROADMAP.md) for our future plans. We also have [benchmarks](https://github.com/rustls/rustls/blob/rel-0.23/BENCHMARKING.md) to prevent performance regressions and to let you evaluate rustls on your target hardware. -If you'd like to help out, please see [CONTRIBUTING.md](CONTRIBUTING.md). +If you'd like to help out, please see [CONTRIBUTING.md](https://github.com/rustls/rustls/blob/rel-0.23/CONTRIBUTING.md). [![Build Status](https://github.com/rustls/rustls/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/rustls/rustls/actions/workflows/build.yml?query=branch%3Amain) [![Coverage Status (codecov.io)](https://codecov.io/gh/rustls/rustls/branch/main/graph/badge.svg)](https://codecov.io/gh/rustls/rustls/) @@ -83,7 +127,7 @@ to a wider set of architectures and environments, or compliance requirements. S Specifying `default-features = false` when depending on rustls will remove the implicit dependency on aws-lc-rs. -Rustls requires Rust 1.71 or later. It has an optional dependency on zlib-rs which requires 1.75 or later. +This fork requires Rust 1.85 or later, where upstream rustls requires 1.71: the `aws_lc_rs` feature, on by default, depends on the `shake` crate, which sets that floor. [ring-target-platforms]: https://github.com/briansmith/ring/blob/2e8363b433fa3b3962c877d9ed2e9145612f3160/include/ring-core/target.h#L18-L64 [`crypto::CryptoProvider`]: https://docs.rs/rustls/latest/rustls/crypto/struct.CryptoProvider.html diff --git a/admin/check-clienthello-compat b/admin/check-clienthello-compat index 5da46eed415..e6db4dd6a5b 100755 --- a/admin/check-clienthello-compat +++ b/admin/check-clienthello-compat @@ -109,10 +109,12 @@ def repo_root(): def default_upstream_ref(root): cargo_toml = root / "rustls" / "Cargo.toml" text = cargo_toml.read_text(encoding="utf-8") - match = re.search(r'(?m)^version = "([^"]+)"$', text) + match = re.search(r'(?m)^version = "(\d+)\.(\d+)\.(\d+)"$', text) if not match: - raise ValueError(f"could not find rustls version in {cargo_toml}") - return f"v/{match.group(1)}" + raise ValueError(f"could not find the crate version in {cargo_toml}") + major, minor, patch = (int(part) for part in match.groups()) + # A shaped-rustls version is `0.23.PPRR`: upstream patch `PP`, fork release `RR`. + return f"v/{major}.{minor}.{patch // 100}" def ensure_git_ref(root, ref): @@ -135,7 +137,7 @@ def extract_ref(root, ref, destination): raise subprocess.CalledProcessError(archive.returncode, archive.args, stderr=stderr) -def write_harness(path, package_name, rustls_path): +def write_harness(path, package_name, rustls_path, rustls_package="rustls"): src = path / "src" src.mkdir(parents=True, exist_ok=True) (path / "Cargo.toml").write_text( @@ -150,7 +152,7 @@ aws_lc_rs = ["rustls/aws_lc_rs"] tls12 = ["rustls/tls12"] [dependencies] -rustls = {{ path = "{rustls_path}", default-features = false, features = ["std"] }} +rustls = {{ package = "{rustls_package}", path = "{rustls_path}", default-features = false, features = ["std"] }} """, encoding="utf-8", ) @@ -341,7 +343,12 @@ def main(): extract_ref(root, upstream_ref, upstream_root) write_harness(harness_upstream, "rustls-clienthello-compat-upstream", upstream_root / "rustls") - write_harness(harness_fork, "rustls-clienthello-compat-fork", root / "rustls") + write_harness( + harness_fork, + "rustls-clienthello-compat-fork", + root / "rustls", + rustls_package="shaped-rustls", + ) print(f"upstream_ref={upstream_ref}") print(f"tmpdir={temp_root}") diff --git a/admin/clippy b/admin/clippy index 32250254c43..b8f19a43137 100755 --- a/admin/clippy +++ b/admin/clippy @@ -17,12 +17,17 @@ function run_clippy() { } # because examples enable rustls' features, `--workspace --no-default-features` is not -# the same as `--package rustls --no-default-features` so run it separately -run_clippy --package rustls --no-default-features --all-targets +# the same as `--package shaped-rustls --no-default-features` so run it separately +run_clippy --package shaped-rustls --no-default-features --all-targets # run all workspace members (individually, because we don't want feature unification) for p in $(admin/all-workspace-members) ; do case "$p" in + rustls-bench) + # rustls-graviola is built against upstream's rustls package, whose types + # are not this crate's: the bench cannot take it. Every other feature is linted. + ALL_FEATURES="--features aws-lc-rs,fips,post-quantum,ring" + ;; *) ALL_FEATURES="--all-features" ;; diff --git a/admin/coverage b/admin/coverage index 3ede3b233a1..aa42ad3e091 100755 --- a/admin/coverage +++ b/admin/coverage @@ -7,8 +7,8 @@ cargo llvm-cov clean --workspace cargo build --locked --all-targets --all-features cargo test --locked --all-features -cargo test -p rustls --locked --no-default-features --features tls12,logging,aws_lc_rs,fips,std -cargo test -p rustls --locked --no-default-features --features tls12,logging,ring,std +cargo test -p shaped-rustls --locked --no-default-features --features tls12,logging,aws_lc_rs,fips,std +cargo test -p shaped-rustls --locked --no-default-features --features tls12,logging,ring,std # ensure both zlib and brotli are tested, irrespective of their order cargo test --locked $(admin/all-features-except zlib rustls) diff --git a/bogo/Cargo.toml b/bogo/Cargo.toml index d5c9b96b7c1..f5993379415 100644 --- a/bogo/Cargo.toml +++ b/bogo/Cargo.toml @@ -8,11 +8,9 @@ publish = false base64 = { workspace = true } env_logger = { workspace = true } nix = { version = "0.30", default-features = false, features = ["signal"] } -rustls = { path = "../rustls", features = ["aws_lc_rs", "ring", "tls12"] } -rustls-post-quantum = { path = "../rustls-post-quantum", optional = true } +rustls = { package = "shaped-rustls", path = "../rustls", features = ["aws_lc_rs", "ring", "tls12"] } webpki = { workspace = true } [features] default = [] -post-quantum = ["dep:rustls-post-quantum"] fips = ["rustls/fips"] diff --git a/bogo/config.json.in b/bogo/config.json.in index 1fa69242e88..5367dcb99fd 100644 --- a/bogo/config.json.in +++ b/bogo/config.json.in @@ -1,5 +1,6 @@ { "DisabledTests": { + "SendUnknownExtensionOnCertificate-TLS13": "shaped-rustls ignores an unknown extension in a certificate entry, as Go's crypto/tls does", "SendV2ClientHello-*": "we only support >=TLS1.2", "*SSL3*": "we only support >=TLS1.2", "*TLS1-*": "we only support >=TLS1.2", @@ -10,6 +11,17 @@ "CertificateSelection-*ClientCertificateTypes-*": "no support for CertificateRequest::certificate_types", "CertificateSelection-Client-SignatureAlgorithmECDSACurve-TLS-TLS12": "ResolvesClientCert does not receive protocol version", "CertificateSelection-Server-*": "TODO certificate selection for servers", + "CertificateSelection-Client-CertificateType-*": "TODO: no RFC7250 raw public key support", + "CertificateSelection-Client-RawPublicKey-*": "TODO: no RFC7250 raw public key support", + "ClientCertificateType-*": "TODO: no client_certificate_type extension support", + "ServerCertificateType-*": "TODO: no server_certificate_type extension support", + "CredentialSessionIDContext-*": "TODO: no session id context support, nor multiple server credentials", + "AlternateTooManyEmptyRecordsAndWarningAlerts": "TODO: we don't count interleaved empty records and warning alerts together", + "RejectEmptyCertificateAuthorities-*": "TODO: we do not reject an empty certificate_authorities extension", + "ServerPadding*": "TODO: no support for the server-side record padding draft", + "TLS13-EarlyData-TooMuchData-LargeLimit-Client-*": "TODO: no support for -on-resume-shim-initial-write", + "CertificateVerificationPassesOnResume-*": "we do not reverify certificates on resumption, so this passes without exercising anything", + "EarlyData-*-Client-Reverify-*": "we do not reverify certificates on resumption, so this passes without exercising anything", "ConflictingVersionNegotiation": "expects to negotiate TLS1.1", "SendFallbackSCSV": "fallback scsv not implemented", "ECDSAKeyUsage-*": "TODO: we don't do anything with key usages", @@ -23,6 +35,7 @@ "SendUnsolicitedOCSPOnCertificate-TLS13": "we unconditionally request a stapled OCSP response", "DuplicateCertCompressionExt*-TLS12": "RFC8879: if TLS 1.2 or earlier is negotiated, the peers MUST ignore this extension", #if defined(RING) + "*-ML-DSA-*": "no ML-DSA verification support in *ring*", "TLS-ECH-*": "*ring* has no HPKE provider for ECH", "AllExtensions-Client-Permute-ECH-HelloRetryRequest-TLS-TLS13": "requires ECH", #elif defined(AWS_LC_RS) && defined(FIPS) @@ -35,11 +48,13 @@ "TLS-ECH-Client-TLS12-RejectRetryConfigs": "we disable TLS1.2 w/ ECH", "TLS-ECH-Client-Reject-NoClientCertificate-TLS12": "we disable TLS1.2 w/ ECH", "TLS-ECH-Client-Reject-TLS12": "we disable TLS1.2 w/ ECH", + "TLS-ECH-Client-Rejected-OverrideName-TLS12": "we disable TLS1.2 w/ ECH", "TLS-ECH-Client-Reject-ResumeInnerSession-TLS12": "we disable TLS1.2 w/ ECH", "TLS-ECH-GREASE-Client-TLS12-RejectRetryConfigs": "we disable TLS1.2 w/ ECH", "TLS-ECH-Client-Reject-EarlyDataRejected-TLS12": "we disable TLS1.2 w/ ECH", "TLS-ECH-Client-Reject-NoClientCertificate-TLS12-Async": "we disable TLS1.2 w/ ECH", "TLS-ECH-Client-Reject-ResumeInnerSession-TLS13": "assumes no outer GREASE PSK, we send GREASE PSK", + "TLS-ECH-Client-RejectUnusableConfig-*": "TODO: no support for rejecting unusable ECH configs", #endif "ALPS-*": "no ALPS support yet", "NPN-*": "no NPN support, never", @@ -50,19 +65,21 @@ "CheckClientCertificateTypes": "we don't check TLS1.2 CertificateRequest.certificate_types", "*-RSA_PKCS1_SHA256_LEGACY-*": "NYI on our side https://datatracker.ietf.org/doc/draft-ietf-tls-tls13-pkcs1/01/", "NoCommonSignatureAlgorithms-TLS12-Fallback": "requires TLS_RSA_WITH_AES_128_GCM_SHA256", -#if defined(POST_QUANTUM) - "MLKEMKeyShareIncludedSecond": "we only include a share for the first configured group", +#if defined(AWS_LC_RS) "MLKEMKeyShareIncludedSecond-MLKEM1024": "we only include a share for the first configured group", - "MLKEMKeyShareIncludedThird": "we only include a share for the first configured group", + "MLKEMKeyShareIncludedSecond-X25519MLKEM768": "we only include a share for the first configured group", "MLKEMKeyShareIncludedThird-MLKEM1024": "we only include a share for the first configured group", + "MLKEMKeyShareIncludedThird-X25519MLKEM768": "we only include a share for the first configured group", + "MultiplePQGroups-MLKEM1024": "we only include a share for the first configured group", + "NotJustMLKEMKeyShare-MLKEM1024": "we only include a share for the first configured group", + "TwoMLKEMs": "we only include a share for the first configured group", #else "*MLKEM*": "not implemented", #endif -#if defined(AWS_LC_RS) - "PostQuantumNotEnabledByDefaultInClients": "it is", - "PostQuantumNotEnabledByDefaultForAServer": "it is", +#ifndef AWS_LC_RS + "PostQuantumEnabledByDefaultForAServer": "*ring* has no ML-KEM", + "PostQuantumEnabledByDefaultInClients": "*ring* has no ML-KEM", #endif - "*Kyber*": "old draft, not implemented", "ExtraClientEncryptedExtension-*": "we don't implement ALPS", "Server-JDK11*": "workarounds for oracle engineering quality", "Client-RejectJDK11DowngradeRandom": "workarounds for oracle engineering quality", @@ -77,18 +94,20 @@ "BadRSAClientKeyExchange-*": "no rsa kem", "SendClientVersion-RSA": "no rsa kem", "Basic-Server-RSA-*": "no rsa kem", + "CertificateCipherMismatch-PSS": "no rsa kem", "RSAKeyUsage-*": "no rsa kem", "*-RSA_WITH_3DES_EDE_CBC_SHA-*": "no cbc suites", "*_WITH_AES_128_CBC_*": "no cbc suites", "*_WITH_AES_256_CBC_*": "no cbc suites", "*-ECDSA_SHA1-*": "no ecdsa-sha1", + "*-Sign-ML-DSA-*": "TODO: no ML-DSA signing support", + "*-Sign-Negotiate-ML-DSA-*": "TODO: no ML-DSA signing support", + "*-SignDefault-ML-DSA-*": "TODO: no ML-DSA signing support", "*-Sign-RSA_PKCS1_SHA1-*": "no sha1", "*-SignDefault-RSA_PKCS1_SHA1-*": "no sha1", "*-VerifyDefault-RSA_PKCS1_SHA1-*": "no sha1", "VerifyPreferences-NoCommonAlgorithms": "we validate but don't actually implement -verify-prefs", "VerifyPreferences-Enforced": "we validate but don't actually implement -verify-prefs", - "*_P224_*": "no p224", - "*-P-224-*": "no p224", #ifdef RING "*-ECDSA_P521_SHA512-*": "no p521 signatures/verification", #endif @@ -97,7 +116,6 @@ "LargeMessage-Reject": "not supported as a runtime option (cert size limit is compile-time constant)", "DelegatedCredentials-*": "not implemented", "NoCommonCurves": "nothing to fall back to", - "ClientHelloPadding": "hello padding extension not implemented", "Resume-Client-CipherMismatch": "tries to vary to unimplemented CBC-mode cs", "*Auth-SHA1-Fallback*": "no sha1 support, so no meaningful need to assume client supports it", "RSA-PSS-Large": "no support for 1024-bit RSA keys", @@ -107,7 +125,7 @@ "*-RSA_WITH_AES_256_CBC_SHA-*": "no rsa kem", "OmitExtensions-ClientHello-TLS12": "we require signature algorithms ext", "EmptyExtensions-ClientHello-TLS12": "we require signature algorithms ext", - "Resume-Server-OmitPSKsOnSecondClientHello": "not required by RFC", + "Resume-Server-CipherNotPreferred": "first connection requires an unimplemented CBC-mode cs (note the TLS1.3 version of this test passes)", "FallbackSCSV*": "fallback countermeasure not yet implemented", "RequireAnyClientCertificate-TLS12": "we don't send an alert in this case", "ServerBogusVersion": "we ignore legacy_version if there's an extension", @@ -125,7 +143,11 @@ "QUICTransportParams-*": "quic mode does not work over TLS1.3 framing -- do this in the shim?", "QUICCompatibilityMode": "quic mode does not work over TLS1.3 framing -- do this in the shim?", "PAKE-*": "no PAKE draft support", + "PSK-Client-*": "TODO: no external PSK support", + "PSK-Server-*": "TODO: no external PSK support", "TrustAnchors-*": "no TrustAnchor draft support", + "TrustAnchorGroups-*": "no TrustAnchor draft support", + "ExtensionTrailingData-TrustAnchors-*": "no TrustAnchor draft support", "TLS13-Client-*TicketFlags*": "no flags extension support (on tickets or elsewhere)", "Ed25519DefaultDisable-NoAccept": "not implemented (ed25519 accepted by default)", "Ed25519DefaultDisable-NoAdvertise": "not implemented (ed25519 advertised by default)", @@ -140,9 +162,19 @@ "*-HintMismatch-*": "hints are a boringssl-specific feature", #if defined(AWS_LC_RS) && defined(FIPS) "Compliance-fips-202205-TLS-Client-ECDSA_P521_SHA512": "fips approved in aws-lc-rs", + "Compliance-fips-202205-TLS-Client-MLKEM": "fips pending in aws-lc-rs", + "Compliance-fips-202205-TLS-Client-X25519MLKEM768": "ml-kem fips pending in aws-lc-rs", "Compliance-fips-202205-TLS-Server-ECDSA_P521_SHA512": "fips approved in aws-lc-rs", + "Compliance-fips-202205-TLS-Server-MLKEM": "fips pending in aws-lc-rs", "Compliance-fips-202205-TLS-Client-Ed25519": "fips approved in aws-lc-rs", "Compliance-fips-202205-TLS-Server-Ed25519": "fips approved in aws-lc-rs", + "Compliance-fips-202205-TLS-Server-X25519MLKEM768": "ml-kem fips pending in aws-lc-rs", + "Compliance-fips-202205-TLS-Client-ML-DSA-44": "ML-DSA postdates fips-202205 policy", + "Compliance-fips-202205-TLS-Client-ML-DSA-65": "ML-DSA postdates fips-202205 policy", + "Compliance-fips-202205-TLS-Client-ML-DSA-87": "ML-DSA postdates fips-202205 policy", + "Compliance-fips-202205-TLS-Server-ML-DSA-44": "ML-DSA postdates fips-202205 policy", + "Compliance-fips-202205-TLS-Server-ML-DSA-65": "ML-DSA postdates fips-202205 policy", + "Compliance-fips-202205-TLS-Server-ML-DSA-87": "ML-DSA postdates fips-202205 policy", #endif "*-QUIC-*" :"quic mode does not work over TLS1.3 framing -- do this in the shim?", "QUIC-*": "quic mode does not work over TLS1.3 framing -- do this in the shim?", @@ -163,7 +195,19 @@ "AppDataBeforeTLS13KeyChange": ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:", "AppDataBeforeTLS13KeyChange-Empty": ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:", "EmptyCertificateList": ":NO_CERTS:", + "Client-VerifyDefault-ML-DSA-44-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-VerifyDefault-ML-DSA-65-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-VerifyDefault-ML-DSA-87-TLS12": ":WRONG_SIGNATURE_TYPE:", + "ExtensionTrailingData-CertificateAuthorities-Client-TLS-TLS13": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-CertificateAuthorities-Server-TLS-TLS13": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-ServerName-Client-TLS-TLS12": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-ServerName-Client-TLS-TLS13": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-ServerName-Server-TLS-TLS12": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-ServerName-Server-TLS-TLS13": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-StatusRequest-Client-TLS-TLS12": ":BAD_HANDSHAKE_MSG:", + "ExtensionTrailingData-StatusRequest-Client-TLS-TLS13": ":BAD_HANDSHAKE_MSG:", "SendInvalidRecordType": ":GARBAGE:", + "SendPostHandshakeChangeCipherSpec-TLS13": ":PEER_MISBEHAVIOUR:", "NoSharedCipher": ":HANDSHAKE_FAILURE:", "NoSharedCipher-TLS13": ":HANDSHAKE_FAILURE:", "InvalidECDHPoint-Client": ":PEER_MISBEHAVIOUR:", @@ -230,6 +274,27 @@ "TLS-TLS12-AES_256_GCM_SHA384-client": ":PEER_MISBEHAVIOUR:", "SkipHelloRetryRequest-TLS13": ":PEER_MISBEHAVIOUR:", "NoSupportedVersions": ":INCOMPATIBLE:", + "Client-Sign-ML-DSA-44-TLS12": ":NO_COMMON_SIGNATURE_ALGORITHMS:", + "Client-Sign-ML-DSA-65-TLS12": ":NO_COMMON_SIGNATURE_ALGORITHMS:", + "Client-Sign-ML-DSA-87-TLS12": ":NO_COMMON_SIGNATURE_ALGORITHMS:", + "Client-SignDefault-ML-DSA-44-TLS12": ":NO_COMMON_SIGNATURE_ALGORITHMS:", + "Client-SignDefault-ML-DSA-65-TLS12": ":NO_COMMON_SIGNATURE_ALGORITHMS:", + "Client-SignDefault-ML-DSA-87-TLS12": ":NO_COMMON_SIGNATURE_ALGORITHMS:", + "Client-Verify-ML-DSA-44-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-Verify-ML-DSA-65-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-Verify-ML-DSA-87-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-VerifyDefault-ML-DSA-44-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-VerifyDefault-ML-DSA-65-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Client-VerifyDefault-ML-DSA-87-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Server-Sign-ML-DSA-44-TLS12": ":INCOMPATIBLE:", + "Server-Sign-ML-DSA-65-TLS12": ":INCOMPATIBLE:", + "Server-Sign-ML-DSA-87-TLS12": ":INCOMPATIBLE:", + "Server-SignDefault-ML-DSA-44-TLS12": ":INCOMPATIBLE:", + "Server-SignDefault-ML-DSA-65-TLS12": ":INCOMPATIBLE:", + "Server-SignDefault-ML-DSA-87-TLS12": ":INCOMPATIBLE:", + "Server-VerifyDefault-ML-DSA-44-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Server-VerifyDefault-ML-DSA-65-TLS12": ":WRONG_SIGNATURE_TYPE:", + "Server-VerifyDefault-ML-DSA-87-TLS12": ":WRONG_SIGNATURE_TYPE:", "Server-Sign-RSA_PKCS1_SHA256-TLS13": ":INCOMPATIBLE:", "Server-Sign-RSA_PKCS1_SHA384-TLS13": ":INCOMPATIBLE:", "Server-Sign-RSA_PKCS1_SHA512-TLS13": ":INCOMPATIBLE:", @@ -274,6 +339,10 @@ "UnknownUnencryptedExtension-Client-TLS13": ":PEER_MISBEHAVIOUR:", "UnexpectedUnencryptedExtension-Client-TLS13": ":PEER_MISBEHAVIOUR:", "UnofferedExtension-Client-TLS13": ":PEER_MISBEHAVIOUR:", + "RejectPSSKeyType-Client-TLS12": ":WRONG_SIGNATURE_TYPE:", + "RejectPSSKeyType-Client-TLS13": ":WRONG_SIGNATURE_TYPE:", + "RejectPSSKeyType-Server-TLS12": ":WRONG_SIGNATURE_TYPE:", + "RejectPSSKeyType-Server-TLS13": ":WRONG_SIGNATURE_TYPE:", "RenegotiationInfo-Forbidden-TLS13": ":PEER_MISBEHAVIOUR:", "UnknownExtension-Client-TLS13": ":PEER_MISBEHAVIOUR:", "RequestContextInHandshake-TLS13": ":BAD_HANDSHAKE_MSG:", @@ -351,6 +420,8 @@ "GarbageCertificate-Server-TLS13": "remote error: bad certificate", "GarbageCertificate-Client-TLS12": "remote error: bad certificate", "GarbageCertificate-Client-TLS13": "remote error: bad certificate", + "MissingKeyShare-Server-TLS13": "remote error: handshake failure", + "NoSupportedCurves-TLS13": "remote error: handshake failure", "Downgrade-TLS10-Client": "tls: no cipher suite supported by both client and server", "Downgrade-TLS10-Server": "remote error: protocol version not supported", "TrailingDataWithFinished-Client-TLS13": "local error: bad record MAC", @@ -369,7 +440,13 @@ "CertificateSelection-Client-SignatureAlgorithm-MatchNone-TLS-TLS13": "", "CertificateSelection-Client-SignatureAlgorithmECDSACurve-MatchNone-TLS-TLS13": "", "CertificateSelection-Client-SignatureAlgorithmKeyPrefs-MatchNone-TLS-TLS12": "", - "CertificateSelection-Client-SignatureAlgorithmKeyPrefs-MatchNone-TLS-TLS13": "" + "CertificateSelection-Client-SignatureAlgorithmKeyPrefs-MatchNone-TLS-TLS13": "", + "Client-Sign-ML-DSA-44-TLS12": "", + "Client-Sign-ML-DSA-65-TLS12": "", + "Client-Sign-ML-DSA-87-TLS12": "", + "Client-SignDefault-ML-DSA-44-TLS12": "", + "Client-SignDefault-ML-DSA-65-TLS12": "", + "Client-SignDefault-ML-DSA-87-TLS12": "" }, "HalfRTTTickets": 0 } diff --git a/bogo/fetch-and-build b/bogo/fetch-and-build deleted file mode 100755 index 928e701199f..00000000000 --- a/bogo/fetch-and-build +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash - -set -ex - -mkdir -p bogo -pushd bogo - -git init --initial-branch main -git config core.sparsecheckout 1 -cat << EOF > .git/info/sparse-checkout -go.mod -go.sum -ssl/test/runner -util/testresult -EOF - -# fix on a tested point of rustls-testing branch -COMMIT=92b3d4e221b4b4690dc9c3f8ada7e92df843e987 -git fetch --depth=1 https://github.com/rustls/boringssl.git $COMMIT -git checkout $COMMIT -(cd ssl/test/runner && go test -c) - -popd diff --git a/bogo/runme b/bogo/runme index 795451494bb..351d4bcaef3 100755 --- a/bogo/runme +++ b/bogo/runme @@ -18,10 +18,6 @@ case ${BOGO_SHIM_PROVIDER:-aws-lc-rs} in cpp -P -DAWS_LC_RS -DFIPS config.json.in > config.json cargo run --features fips -- -print-rustls-provider ;; - post-quantum) - cpp -P -DAWS_LC_RS -DPOST_QUANTUM config.json.in > config.json - cargo run --features post-quantum -- -print-rustls-provider - ;; existing) ;; *) @@ -30,11 +26,37 @@ case ${BOGO_SHIM_PROVIDER:-aws-lc-rs} in ;; esac -if [ ! -e bogo/ssl/test/runner/runner.test ] ; then - ./fetch-and-build +if [ ! -e bogo/.git ] ; then + mkdir -p bogo + pushd bogo + + git init --initial-branch main + git config core.sparsecheckout 1 + cat << EOF > .git/info/sparse-checkout +go.mod +go.sum +ssl/test/runner +util/testresult +EOF + + popd cp -v keys/* bogo/ fi +# fix on a tested point of rustls-testing branch +COMMIT=9389a4af2c6c47a59ec39bfb51e4da2fe971d1bc +changed=$([ "$(git -C bogo rev-parse HEAD)" != "$COMMIT" ] && echo true || echo false) +if $changed ; then + pushd bogo + git fetch --depth=1 https://github.com/rustls/boringssl.git $COMMIT + git checkout $COMMIT + popd +fi + +if $changed || [ ! -e bogo/ssl/test/runner/runner.test ] ; then + (cd bogo/ssl/test/runner && go test -c) +fi + # Best effort on OS-X case $OSTYPE in darwin*) set +e ;; esac diff --git a/bogo/src/main.rs b/bogo/src/main.rs index 20cc735ba3a..656e721b0ef 100644 --- a/bogo/src/main.rs +++ b/bogo/src/main.rs @@ -20,6 +20,7 @@ )] use core::fmt::{Debug, Formatter}; +use core::sync::atomic::{AtomicUsize, Ordering}; use std::io::{self, Read, Write}; use std::sync::{Arc, Mutex}; use std::{env, net, process, thread, time}; @@ -36,7 +37,7 @@ use rustls::client::{ }; use rustls::crypto::aws_lc_rs::hpke; use rustls::crypto::hpke::{Hpke, HpkePublicKey}; -use rustls::crypto::{CryptoProvider, aws_lc_rs, ring}; +use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms, aws_lc_rs, ring}; use rustls::internal::msgs::codec::{Codec, Reader}; use rustls::internal::msgs::handshake::EchConfigPayload; use rustls::internal::msgs::persist::ServerSessionValue; @@ -52,6 +53,15 @@ use rustls::{ PeerIncompatible, PeerMisbehaved, ProtocolVersion, RootCertStore, Side, SignatureAlgorithm, SignatureScheme, SupportedProtocolVersion, client, compress, server, sign, version, }; +use webpki::aws_lc_rs::{ + ECDSA_P256_SHA256, ECDSA_P256_SHA384, ECDSA_P256_SHA512, ECDSA_P384_SHA256, ECDSA_P384_SHA384, + ECDSA_P384_SHA512, ECDSA_P521_SHA256, ECDSA_P521_SHA384, ECDSA_P521_SHA512, ED25519, + RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_2048_8192_SHA256_ABSENT_PARAMS, + RSA_PKCS1_2048_8192_SHA384, RSA_PKCS1_2048_8192_SHA384_ABSENT_PARAMS, + RSA_PKCS1_2048_8192_SHA512, RSA_PKCS1_2048_8192_SHA512_ABSENT_PARAMS, + RSA_PSS_2048_8192_SHA256_LEGACY_KEY, RSA_PSS_2048_8192_SHA384_LEGACY_KEY, + RSA_PSS_2048_8192_SHA512_LEGACY_KEY, +}; static BOGO_NACK: i32 = 89; @@ -93,6 +103,7 @@ struct Options { max_version: Option, server_ocsp_response: Vec, groups: Option>, + server_supported_group_hint: Option, export_keying_material: usize, export_keying_material_label: String, export_keying_material_context: String, @@ -117,21 +128,36 @@ struct Options { ech_config_list: Option>, expect_ech_accept: bool, expect_ech_retry_configs: Option>, + expect_no_ech_retry_configs: bool, on_resume_ech_config_list: Option>, on_resume_expect_ech_accept: bool, on_initial_expect_ech_accept: bool, enable_ech_grease: bool, + expect_ech_name_override: Option, + expect_no_ech_name_override: bool, + on_retry_expect_ech_name_override: Option, send_key_update: bool, expect_curve_id: Option, on_initial_expect_curve_id: Option, on_resume_expect_curve_id: Option, wait_for_debugger: bool, ocsp: OcspValidation, + verify_prefs: Option, } impl Options { fn new() -> Self { - let selected_provider = SelectedProvider::from_env(); + let selected_provider = match env::var("BOGO_SHIM_PROVIDER") + .ok() + .as_deref() + { + None | Some("aws-lc-rs") => SelectedProvider::AwsLcRs, + #[cfg(feature = "fips")] + Some("aws-lc-rs-fips") => SelectedProvider::AwsLcRsFips, + Some("ring") => SelectedProvider::Ring, + Some(other) => panic!("unrecognised value for BOGO_SHIM_PROVIDER: {other:?}"), + }; + Self { port: 0, shim_id: 0, @@ -163,6 +189,7 @@ impl Options { max_version: None, server_ocsp_response: vec![], groups: None, + server_supported_group_hint: None, export_keying_material: 0, export_keying_material_label: "".to_string(), export_keying_material_context: "".to_string(), @@ -187,17 +214,49 @@ impl Options { ech_config_list: None, expect_ech_accept: false, expect_ech_retry_configs: None, + expect_no_ech_retry_configs: false, on_resume_ech_config_list: None, on_resume_expect_ech_accept: false, on_initial_expect_ech_accept: false, enable_ech_grease: false, + expect_ech_name_override: None, + expect_no_ech_name_override: false, + on_retry_expect_ech_name_override: None, send_key_update: false, expect_curve_id: None, on_initial_expect_curve_id: None, on_resume_expect_curve_id: None, wait_for_debugger: false, ocsp: OcspValidation::default(), + verify_prefs: None, + } + } + + pub(crate) fn provider(&self) -> CryptoProvider { + let mut provider = self.provider.clone(); + + if let Some(groups) = &self.groups { + provider + .kx_groups + .retain(|kxg| groups.contains(&kxg.name())); + } + + if !matches!(self.selected_provider, SelectedProvider::Ring) + && matches!( + self.verify_prefs, + Some( + SignatureScheme::ML_DSA_44 + | SignatureScheme::ML_DSA_65 + | SignatureScheme::ML_DSA_87 + ) + ) + { + // ML-DSA is disabled by default, enable for preferred verification scheme + provider.signature_verification_algorithms = + aws_lc_rs::default_provider().signature_verification_algorithms; } + + provider } fn version_allowed(&self, vers: ProtocolVersion) -> bool { @@ -214,6 +273,35 @@ impl Options { self.support_tls12 && self.version_allowed(ProtocolVersion::TLSv1_2) } + fn expected_server_names(&self) -> Vec> { + let mut names = vec![]; + + let name = match ( + &self.expect_ech_name_override, + self.expect_no_ech_name_override, + ) { + (Some(override_name), _) => override_name, + (None, true) => &self.host_name, + (None, false) => return names, + }; + + names.push( + ServerName::try_from(name.as_str()) + .expect("invalid expected server name") + .to_owned(), + ); + + if let Some(on_retry) = &self.on_retry_expect_ech_name_override { + names.push( + ServerName::try_from(on_retry.as_str()) + .expect("invalid expected server name") + .to_owned(), + ); + } + + names + } + fn supported_versions(&self) -> Vec<&'static SupportedProtocolVersion> { let mut versions = vec![]; @@ -280,37 +368,21 @@ enum SelectedProvider { AwsLcRs, #[cfg_attr(not(feature = "fips"), allow(dead_code))] AwsLcRsFips, - #[cfg_attr(not(feature = "post-quantum"), allow(dead_code))] - PostQuantum, Ring, } impl SelectedProvider { - fn from_env() -> Self { - match env::var("BOGO_SHIM_PROVIDER") - .ok() - .as_deref() - { - None | Some("aws-lc-rs") => Self::AwsLcRs, - #[cfg(feature = "fips")] - Some("aws-lc-rs-fips") => Self::AwsLcRsFips, - #[cfg(feature = "post-quantum")] - Some("post-quantum") => Self::PostQuantum, - Some("ring") => Self::Ring, - Some(other) => panic!("unrecognised value for BOGO_SHIM_PROVIDER: {other:?}"), - } - } - fn provider(&self) -> CryptoProvider { match self { - Self::AwsLcRs | Self::AwsLcRsFips | Self::PostQuantum => { + Self::AwsLcRs | Self::AwsLcRsFips => { // ensure all suites and kx groups are included (even in fips builds) // as non-fips test cases require them. runner activates fips mode via -fips-202205 option // this includes rustls-post-quantum, which just returns an altered // version of `aws_lc_rs::default_provider()` CryptoProvider { - kx_groups: aws_lc_rs::DEFAULT_KX_GROUPS.to_vec(), + kx_groups: aws_lc_rs::ALL_KX_GROUPS.to_vec(), cipher_suites: aws_lc_rs::ALL_CIPHER_SUITES.to_vec(), + signature_verification_algorithms: SUPPORTED_SIG_ALGS, ..aws_lc_rs::default_provider() } } @@ -321,21 +393,84 @@ impl SelectedProvider { fn ticketer(&self) -> Arc { match self { - Self::AwsLcRs | Self::AwsLcRsFips | Self::PostQuantum => { - aws_lc_rs::Ticketer::new().unwrap() - } + Self::AwsLcRs | Self::AwsLcRsFips => aws_lc_rs::Ticketer::new().unwrap(), Self::Ring => ring::Ticketer::new().unwrap(), } } fn supports_ech(&self) -> bool { match *self { - Self::AwsLcRs | Self::AwsLcRsFips | Self::PostQuantum => true, + Self::AwsLcRs | Self::AwsLcRsFips => true, Self::Ring => false, } } } +// aws-lc-rs signature algorithms, with ML-DSA disabled +pub(crate) static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms { + all: &[ + ECDSA_P256_SHA256, + ECDSA_P256_SHA384, + ECDSA_P256_SHA512, + ECDSA_P384_SHA256, + ECDSA_P384_SHA384, + ECDSA_P384_SHA512, + ECDSA_P521_SHA256, + ECDSA_P521_SHA384, + ECDSA_P521_SHA512, + ED25519, + RSA_PSS_2048_8192_SHA256_LEGACY_KEY, + RSA_PSS_2048_8192_SHA384_LEGACY_KEY, + RSA_PSS_2048_8192_SHA512_LEGACY_KEY, + RSA_PKCS1_2048_8192_SHA256, + RSA_PKCS1_2048_8192_SHA384, + RSA_PKCS1_2048_8192_SHA512, + RSA_PKCS1_2048_8192_SHA256_ABSENT_PARAMS, + RSA_PKCS1_2048_8192_SHA384_ABSENT_PARAMS, + RSA_PKCS1_2048_8192_SHA512_ABSENT_PARAMS, + ], + mapping: &[ + // Note: for TLS1.2 the curve is not fixed by SignatureScheme. For TLS1.3 it is. + ( + SignatureScheme::ECDSA_NISTP384_SHA384, + &[ECDSA_P384_SHA384, ECDSA_P256_SHA384, ECDSA_P521_SHA384], + ), + ( + SignatureScheme::ECDSA_NISTP256_SHA256, + &[ECDSA_P256_SHA256, ECDSA_P384_SHA256, ECDSA_P521_SHA256], + ), + ( + SignatureScheme::ECDSA_NISTP521_SHA512, + &[ECDSA_P521_SHA512, ECDSA_P384_SHA512, ECDSA_P256_SHA512], + ), + (SignatureScheme::ED25519, &[ED25519]), + ( + SignatureScheme::RSA_PSS_SHA512, + &[RSA_PSS_2048_8192_SHA512_LEGACY_KEY], + ), + ( + SignatureScheme::RSA_PSS_SHA384, + &[RSA_PSS_2048_8192_SHA384_LEGACY_KEY], + ), + ( + SignatureScheme::RSA_PSS_SHA256, + &[RSA_PSS_2048_8192_SHA256_LEGACY_KEY], + ), + ( + SignatureScheme::RSA_PKCS1_SHA512, + &[RSA_PKCS1_2048_8192_SHA512], + ), + ( + SignatureScheme::RSA_PKCS1_SHA384, + &[RSA_PKCS1_2048_8192_SHA384], + ), + ( + SignatureScheme::RSA_PKCS1_SHA256, + &[RSA_PKCS1_2048_8192_SHA256], + ), + ], +}; + fn load_root_certs(filename: &str) -> Arc { let mut roots = RootCertStore::empty(); @@ -392,15 +527,14 @@ impl DummyClientAuth { trusted_cert_file: &str, mandatory: bool, root_hint_subjects: Vec, + provider: Arc, ) -> Self { Self { mandatory, root_hint_subjects, parent: WebPkiClientVerifier::builder_with_provider( load_root_certs(trusted_cert_file), - SelectedProvider::from_env() - .provider() - .into(), + provider, ) .build() .unwrap(), @@ -459,20 +593,27 @@ impl ClientCertVerifier for DummyClientAuth { struct DummyServerAuth { parent: Arc, ocsp: OcspValidation, + expect_server_names: Vec>, + server_name_index: AtomicUsize, } impl DummyServerAuth { - fn new(trusted_cert_file: &str, ocsp: OcspValidation) -> Self { + fn new( + trusted_cert_file: &str, + ocsp: OcspValidation, + expect_server_names: Vec>, + provider: Arc, + ) -> Self { Self { parent: WebPkiServerVerifier::builder_with_provider( load_root_certs(trusted_cert_file), - SelectedProvider::from_env() - .provider() - .into(), + provider, ) .build() .unwrap(), ocsp, + expect_server_names, + server_name_index: AtomicUsize::new(0), } } } @@ -482,10 +623,16 @@ impl ServerCertVerifier for DummyServerAuth { &self, _end_entity: &CertificateDer<'_>, _certs: &[CertificateDer<'_>], - _hostname: &ServerName<'_>, + hostname: &ServerName<'_>, _ocsp: &[u8], _now: UnixTime, ) -> Result { + if !self.expect_server_names.is_empty() { + let expect_server_name = &self.expect_server_names[self + .server_name_index + .fetch_add(1, Ordering::SeqCst)]; + assert_eq!(hostname, expect_server_name); + } if let OcspValidation::Reject = self.ocsp { return Err(CertificateError::InvalidOcspResponse.into()); } @@ -591,11 +738,7 @@ impl client::ResolvesClientCert for MultipleClientCredentialResolver { for sig_scheme in sig_schemes.iter().copied() { for (i, cert) in self.additional.iter().enumerate() { // if the server sends any issuer hints, respect them - if cert.must_match_issuer - && !root_hint_subjects - .iter() - .any(|dn| *dn == cert.issuer_dn.as_ref()) - { + if cert.must_match_issuer && !cert.any_issuer_matches_hints(root_hint_subjects) { continue; } @@ -647,14 +790,17 @@ impl client::ResolvesClientCert for MultipleClientCredentialResolver { #[derive(Debug)] struct ClientCert { certkey: Arc, - issuer_dn: DistinguishedName, + issuer_names: Vec, must_match_issuer: bool, } impl ClientCert { fn new(mut certkey: sign::CertifiedKey, meta: &Credential) -> Self { - let parsed_cert = webpki::EndEntityCert::try_from(certkey.cert.last().unwrap()).unwrap(); - let issuer_dn = DistinguishedName::in_sequence(parsed_cert.issuer()); + let mut issuer_names = Vec::new(); + for cert in &certkey.cert { + let parsed_cert = webpki::EndEntityCert::try_from(cert).unwrap(); + issuer_names.push(DistinguishedName::in_sequence(parsed_cert.issuer())); + } if let Some(scheme) = meta.use_signing_scheme { certkey.key = Arc::new(FixedSignatureSchemeSigningKey { @@ -665,10 +811,18 @@ impl ClientCert { Self { certkey: Arc::new(certkey), - issuer_dn, + issuer_names, must_match_issuer: meta.must_match_issuer, } } + + fn any_issuer_matches_hints(&self, hints: &[&[u8]]) -> bool { + hints.iter().any(|dn| { + self.issuer_names + .iter() + .any(|issuer| *dn == issuer.as_ref()) + }) + } } fn lookup_scheme(scheme: u16) -> SignatureScheme { @@ -683,6 +837,9 @@ fn lookup_scheme(scheme: u16) -> SignatureScheme { 0x0805 => SignatureScheme::RSA_PSS_SHA384, 0x0806 => SignatureScheme::RSA_PSS_SHA512, 0x0807 => SignatureScheme::ED25519, + 0x0904 => SignatureScheme::ML_DSA_44, + 0x0905 => SignatureScheme::ML_DSA_65, + 0x0906 => SignatureScheme::ML_DSA_87, // TODO: add support for Ed448 // 0x0808 => SignatureScheme::ED448, _ => { @@ -752,12 +909,15 @@ impl server::StoresServerSessions for ServerCacheWithResumptionDelay { } fn make_server_cfg(opts: &Options, key_log: &Arc) -> Arc { + let provider = Arc::new(opts.provider()); + let client_auth = if opts.verify_peer || opts.offer_no_client_cas || opts.require_any_client_cert { Arc::new(DummyClientAuth::new( &opts.trusted_cert_file, opts.require_any_client_cert, opts.root_hint_subjects.clone(), + provider.clone(), )) } else { WebPkiClientVerifier::no_client_auth() @@ -770,15 +930,7 @@ fn make_server_cfg(opts: &Options, key_log: &Arc) -> Arc) -> Arc, storage: Arc, } -impl ClientCacheWithoutKxHints { - fn new(delay: u32) -> Arc { +impl ClientCacheWithSpecificKxHints { + fn new(delay: u32, kx_hint: Option) -> Arc { Arc::new(Self { delay, + kx_hint, storage: Arc::new(client::ClientSessionMemoryCache::new(32)), }) } } -impl client::ClientSessionStore for ClientCacheWithoutKxHints { +impl client::ClientSessionStore for ClientCacheWithSpecificKxHints { fn set_kx_hint(&self, _: ServerName<'static>, _: NamedGroup) {} fn kx_hint(&self, _: &ServerName<'_>) -> Option { - None + self.kx_hint } fn set_tls12_session( @@ -904,7 +1058,7 @@ impl client::ClientSessionStore for ClientCacheWithoutKxHints { } } -impl Debug for ClientCacheWithoutKxHints { +impl Debug for ClientCacheWithSpecificKxHints { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { // Note: we omit self.storage here as it may contain sensitive data. f.debug_struct("ClientCacheWithoutKxHints") @@ -914,15 +1068,7 @@ impl Debug for ClientCacheWithoutKxHints { } fn make_client_cfg(opts: &Options, key_log: &Arc) -> Arc { - let mut provider = opts.provider.clone(); - - if let Some(groups) = &opts.groups { - provider - .kx_groups - .retain(|kxg| groups.contains(&kxg.name())); - } - - let provider = Arc::new(provider); + let provider = Arc::new(opts.provider()); let cfg = ClientConfig::builder_with_provider(provider.clone()); let cfg = if opts.selected_provider.supports_ech() { @@ -955,6 +1101,8 @@ fn make_client_cfg(opts: &Options, key_log: &Arc) -> Arc) -> Arc cfg.with_no_client_auth(), }; - cfg.resumption = Resumption::store(ClientCacheWithoutKxHints::new(opts.resumption_delay)) - .tls12_resumption(match opts.tickets { - true => Tls12Resumption::SessionIdOrTickets, - false => Tls12Resumption::SessionIdOnly, - }); + cfg.resumption = Resumption::store(ClientCacheWithSpecificKxHints::new( + opts.resumption_delay, + opts.server_supported_group_hint, + )) + .tls12_resumption(match opts.tickets { + true => Tls12Resumption::SessionIdOrTickets, + false => Tls12Resumption::SessionIdOnly, + }); cfg.enable_sni = opts.use_sni; cfg.max_fragment_size = opts.max_fragment; cfg.require_ems = opts.require_ems; @@ -1098,9 +1249,6 @@ fn handle_err(opts: &Options, err: Error) -> ! { Error::InvalidMessage(InvalidMessage::PreSharedKeyIsNotFinalExtension) => { quit(":PRE_SHARED_KEY_MUST_BE_LAST:") } - Error::DecryptError if opts.ech_config_list.is_some() => { - quit(":INCONSISTENT_ECH_NEGOTIATION:") - } Error::DecryptError => quit(":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:"), Error::NoApplicationProtocol => quit(":NO_APPLICATION_PROTOCOL:"), Error::PeerIncompatible( @@ -1109,6 +1257,9 @@ fn handle_err(opts: &Options, err: Error) -> ! { Error::PeerIncompatible(PeerIncompatible::ServerRejectedEncryptedClientHello( _retry_configs, )) => { + if opts.expect_no_ech_retry_configs { + assert_eq!(_retry_configs, None); + } if let Some(expected_configs) = &opts.expect_ech_retry_configs { let expected_configs = Vec::::read(&mut Reader::init(expected_configs)).unwrap(); @@ -1117,9 +1268,10 @@ fn handle_err(opts: &Options, err: Error) -> ! { quit(":ECH_REJECTED:") } Error::PeerIncompatible(_) => quit(":INCOMPATIBLE:"), - Error::PeerMisbehaved(PeerMisbehaved::MissingPskModesExtension) => { - quit(":MISSING_EXTENSION:") - } + Error::PeerMisbehaved( + PeerMisbehaved::MissingPskExtensionInSecondClientHello + | PeerMisbehaved::MissingPskModesExtension, + ) => quit(":MISSING_EXTENSION:"), Error::PeerMisbehaved(PeerMisbehaved::TooMuchEarlyDataReceived) => { quit(":TOO_MUCH_READ_EARLY_DATA:") } @@ -1151,6 +1303,9 @@ fn handle_err(opts: &Options, err: Error) -> ! { Error::PeerMisbehaved(PeerMisbehaved::TooManyEmptyFragments) => { quit(":TOO_MANY_EMPTY_FRAGMENTS:") } + Error::PeerMisbehaved(PeerMisbehaved::EchAcceptanceVariedAfterRetry) => { + quit(":INCONSISTENT_ECH_NEGOTIATION:") + } Error::PeerMisbehaved(PeerMisbehaved::IllegalHelloRetryRequestWithInvalidEch) | Error::PeerMisbehaved(PeerMisbehaved::UnsolicitedEchExtension) => { quit(":UNEXPECTED_EXTENSION:") @@ -1226,7 +1381,12 @@ const MAX_MESSAGE_SIZE: usize = 0xffff + 5; fn after_read(opts: &Options, sess: &mut Connection, conn: &mut net::TcpStream) { if let Err(err) = sess.process_new_packets() { - flush(sess, conn); /* send any alerts before exiting */ + // Send any alerts before exiting, but don't swallow `err` if we can't. + while sess.wants_write() { + if sess.write_tls(conn).is_err() { + break; + } + } orderly_close(conn); handle_err(opts, err); } @@ -1557,7 +1717,9 @@ pub fn main() { opts.credentials.last_mut().key_file = args.remove(0); } "-new-x509-credential" => { - opts.credentials.additional.push(Credential::default()); + opts.credentials + .additional + .push(Credential::default()); } "-expect-selected-credential" => { opts.credentials.expect_selected = args.remove(0).parse::().ok(); @@ -1608,68 +1770,74 @@ pub fn main() { } "-signing-prefs" => { let alg = args.remove(0).parse::().unwrap(); - opts.credentials.last_mut().use_signing_scheme = Some(alg); + opts.credentials + .last_mut() + .use_signing_scheme = Some(alg); } "-must-match-issuer" => { - opts.credentials.last_mut().must_match_issuer = true; + opts.credentials + .last_mut() + .must_match_issuer = true; } - "-use-client-ca-list" => { - match args.remove(0).as_ref() { - "" | "" => { - opts.root_hint_subjects = vec![]; - } - list => { - opts.root_hint_subjects = list.split(',') - .map(|entry| DistinguishedName::from(decode_hex(entry))) - .collect(); - } + "-use-client-ca-list" => match args.remove(0).as_ref() { + "" | "" => { + opts.root_hint_subjects = vec![]; } - } + list => { + opts.root_hint_subjects = list + .split(',') + .map(|entry| DistinguishedName::from(decode_hex(entry))) + .collect(); + } + }, "-verify-prefs" => { - lookup_scheme(args.remove(0).parse::().unwrap()); + opts.verify_prefs = Some(lookup_scheme(args.remove(0).parse::().unwrap())); } "-expect-curve-id" => { - opts.expect_curve_id = Some(NamedGroup::from(args.remove(0).parse::().unwrap())); + opts.expect_curve_id = + Some(NamedGroup::from(args.remove(0).parse::().unwrap())); } "-on-initial-expect-curve-id" => { - opts.on_initial_expect_curve_id = Some(NamedGroup::from(args.remove(0).parse::().unwrap())); + opts.on_initial_expect_curve_id = + Some(NamedGroup::from(args.remove(0).parse::().unwrap())); } "-on-resume-expect-curve-id" => { - opts.on_resume_expect_curve_id = Some(NamedGroup::from(args.remove(0).parse::().unwrap())); - } - "-max-cert-list" | - "-expect-peer-signature-algorithm" | - "-expect-peer-verify-pref" | - "-expect-advertised-alpn" | - "-expect-alpn" | - "-on-initial-expect-alpn" | - "-on-resume-expect-alpn" | - "-on-retry-expect-alpn" | - "-expect-server-name" | - "-expect-ocsp-response" | - "-expect-signed-cert-timestamps" | - "-expect-certificate-types" | - "-expect-client-ca-list" | - "-on-retry-expect-early-data-reason" | - "-on-resume-expect-early-data-reason" | - "-on-initial-expect-early-data-reason" | - "-on-initial-expect-cipher" | - "-on-resume-expect-cipher" | - "-on-retry-expect-cipher" | - "-expect-ticket-age-skew" | - "-handshaker-path" | - "-application-settings" | - "-expect-msg-callback" => { + opts.on_resume_expect_curve_id = + Some(NamedGroup::from(args.remove(0).parse::().unwrap())); + } + "-max-cert-list" + | "-expect-peer-signature-algorithm" + | "-expect-peer-verify-pref" + | "-expect-advertised-alpn" + | "-expect-alpn" + | "-on-initial-expect-alpn" + | "-on-resume-expect-alpn" + | "-on-retry-expect-alpn" + | "-expect-server-name" + | "-expect-ocsp-response" + | "-expect-signed-cert-timestamps" + | "-expect-certificate-types" + | "-expect-client-ca-list" + | "-on-retry-expect-early-data-reason" + | "-on-resume-expect-early-data-reason" + | "-on-initial-expect-early-data-reason" + | "-on-initial-expect-cipher" + | "-on-resume-expect-cipher" + | "-on-retry-expect-cipher" + | "-expect-ticket-age-skew" + | "-handshaker-path" + | "-application-settings" + | "-expect-msg-callback" => { println!("not checking {} {}; NYI", arg, args.remove(0)); } - "-expect-secure-renegotiation" | - "-expect-no-session-id" | - "-enable-ed25519" | - "-on-resume-expect-no-offer-early-data" | - "-expect-tls13-downgrade" | - "-enable-signed-cert-timestamps" | - "-expect-session-id" => { + "-expect-secure-renegotiation" + | "-expect-no-session-id" + | "-enable-ed25519" + | "-on-resume-expect-no-offer-early-data" + | "-expect-tls13-downgrade" + | "-enable-signed-cert-timestamps" + | "-expect-session-id" => { println!("not checking {arg}; NYI"); } @@ -1685,7 +1853,7 @@ pub fn main() { "-expect-session-miss" => { opts.expect_handshake_kind_resumed = Some(vec![ HandshakeKind::Full, - HandshakeKind::FullWithHelloRetryRequest + HandshakeKind::FullWithHelloRetryRequest, ]); } "-export-keying-material" => { @@ -1704,16 +1872,19 @@ pub fn main() { opts.export_traffic_secrets = true; } "-quic-transport-params" => { - opts.quic_transport_params = BASE64_STANDARD.decode(args.remove(0).as_bytes()) + opts.quic_transport_params = BASE64_STANDARD + .decode(args.remove(0).as_bytes()) .expect("invalid base64"); } "-expect-quic-transport-params" => { - opts.expect_quic_transport_params = BASE64_STANDARD.decode(args.remove(0).as_bytes()) + opts.expect_quic_transport_params = BASE64_STANDARD + .decode(args.remove(0).as_bytes()) .expect("invalid base64"); } "-ocsp-response" => { - opts.server_ocsp_response = BASE64_STANDARD.decode(args.remove(0).as_bytes()) + opts.server_ocsp_response = BASE64_STANDARD + .decode(args.remove(0).as_bytes()) .expect("invalid base64"); } "-select-alpn" => { @@ -1763,25 +1934,24 @@ pub fn main() { opts.only_write_one_byte_after_handshake_on_resume = true; } "-on-resume-early-write-after-message" => { - opts.queue_early_data_after_received_messages= match args.remove(0).parse::().unwrap() { - // estimate where these messages appear in the server's first flight. - 2 => vec![5 + 128 + 5 + 32], - 8 => vec![5 + 128 + 5 + 32, 5 + 64], - _ => { - panic!("unhandled -on-resume-early-write-after-message"); - } - }; + opts.queue_early_data_after_received_messages = + match args.remove(0).parse::().unwrap() { + // estimate where these messages appear in the server's first flight. + 2 => vec![5 + 128 + 5 + 32], + 8 => vec![5 + 128 + 5 + 32, 5 + 64], + _ => { + panic!("unhandled -on-resume-early-write-after-message"); + } + }; opts.queue_data_on_resume = true; } "-expect-ticket-supports-early-data" => { opts.expect_ticket_supports_early_data = true; } - "-expect-accept-early-data" | - "-on-resume-expect-accept-early-data" => { + "-expect-accept-early-data" | "-on-resume-expect-accept-early-data" => { opts.expect_accept_early_data = true; } - "-expect-early-data-reason" | - "-on-resume-expect-reject-early-data-reason" => { + "-expect-early-data-reason" | "-on-resume-expect-reject-early-data-reason" => { let reason = args.remove(0); match reason.as_str() { "disabled" | "protocol_version" => { @@ -1793,8 +1963,7 @@ pub fn main() { } } } - "-expect-reject-early-data" | - "-on-resume-expect-reject-early-data" => { + "-expect-reject-early-data" | "-on-resume-expect-reject-early-data" => { opts.expect_reject_early_data = true; } "-expect-version" => { @@ -1802,13 +1971,13 @@ pub fn main() { } "-curves" => { let group = NamedGroup::from(args.remove(0).parse::().unwrap()); - opts.groups.get_or_insert(Vec::new()).push(group); - - // if X25519MLKEM768 is requested, insert it from rustls_post_quantum - #[cfg(feature = "post-quantum")] - if group == rustls_post_quantum::X25519MLKEM768.name() && opts.selected_provider == SelectedProvider::PostQuantum { - opts.provider.kx_groups.insert(0, rustls_post_quantum::X25519MLKEM768); - } + opts.groups + .get_or_insert(Vec::new()) + .push(group); + } + "-server-supported-groups-hint" => { + let group = NamedGroup::from(args.remove(0).parse::().unwrap()); + opts.server_supported_group_hint = Some(group); } "-resumption-delay" => { opts.resumption_delay = args.remove(0).parse::().unwrap(); @@ -1821,7 +1990,8 @@ pub fn main() { opts.install_cert_compression_algs = CompressionAlgs::All; } "-install-one-cert-compression-alg" => { - opts.install_cert_compression_algs = CompressionAlgs::One(args.remove(0).parse::().unwrap()); + opts.install_cert_compression_algs = + CompressionAlgs::One(args.remove(0).parse::().unwrap()); } #[cfg(feature = "fips")] "-fips-202205" if opts.selected_provider == SelectedProvider::AwsLcRsFips => { @@ -1832,33 +2002,59 @@ pub fn main() { process::exit(BOGO_NACK); } "-ech-config-list" => { - opts.ech_config_list = Some(BASE64_STANDARD.decode(args.remove(0).as_bytes()) - .expect("invalid ECH config base64").into()); + opts.ech_config_list = Some( + BASE64_STANDARD + .decode(args.remove(0).as_bytes()) + .expect("invalid ECH config base64") + .into(), + ); } "-expect-ech-accept" => { opts.expect_ech_accept = true; } "-expect-ech-retry-configs" => { - opts.expect_ech_retry_configs = Some(BASE64_STANDARD.decode(args.remove(0).as_bytes()) - .expect("invalid ECH config base64").into()); + opts.expect_ech_retry_configs = Some( + BASE64_STANDARD + .decode(args.remove(0).as_bytes()) + .expect("invalid ECH config base64") + .into(), + ); } "-on-resume-ech-config-list" => { - opts.on_resume_ech_config_list = Some(BASE64_STANDARD.decode(args.remove(0).as_bytes()) - .expect("invalid on resume ECH config base64").into()); + opts.on_resume_ech_config_list = Some( + BASE64_STANDARD + .decode(args.remove(0).as_bytes()) + .expect("invalid on resume ECH config base64") + .into(), + ); } "-on-resume-expect-ech-accept" => { opts.on_resume_expect_ech_accept = true; } "-expect-no-ech-retry-configs" => { opts.expect_ech_retry_configs = None; + opts.expect_no_ech_retry_configs = true; } "-on-initial-expect-ech-accept" => { opts.on_initial_expect_ech_accept = true; } "-on-retry-expect-ech-retry-configs" => { // Note: we treat this the same as -expect-ech-retry-configs - opts.expect_ech_retry_configs = Some(BASE64_STANDARD.decode(args.remove(0).as_bytes()) - .expect("invalid retry ECH config base64").into()); + opts.expect_ech_retry_configs = Some( + BASE64_STANDARD + .decode(args.remove(0).as_bytes()) + .expect("invalid retry ECH config base64") + .into(), + ); + } + "-expect-ech-name-override" => { + opts.expect_ech_name_override = Some(args.remove(0)); + } + "-expect-no-ech-name-override" => { + opts.expect_no_ech_name_override = true; + } + "-on-retry-expect-ech-name-override" => { + opts.on_retry_expect_ech_name_override = Some(args.remove(0)); } "-enable-ech-grease" => { opts.enable_ech_grease = true; @@ -1881,82 +2077,90 @@ pub fn main() { } // defaults: - "-enable-all-curves" | - "-renegotiate-ignore" | - "-no-tls11" | - "-no-tls1" | - "-no-ssl3" | - "-handoff" | - "-ipv6" | - "-decline-alpn" | - "-permute-extensions" | - "-expect-no-session" | - "-expect-ticket-renewal" | - "-enable-ocsp-stapling" | - "-use-ocsp-callback" | - "-forbid-renegotiation-after-handshake" | - // internal openssl details: - "-async" | - "-implicit-handshake" | - "-use-old-client-cert-callback" | - "-use-early-callback" => {} + "-enable-all-curves" + | "-renegotiate-ignore" + | "-no-tls11" + | "-no-tls1" + | "-no-ssl3" + | "-handoff" + | "-ipv6" + | "-no-legacy-server-connect" + | "-decline-alpn" + | "-permute-extensions" + | "-expect-no-session" + | "-on-retry-expect-no-session" + | "-expect-ticket-renewal" + | "-enable-ocsp-stapling" + | "-use-ocsp-callback" + | "-forbid-renegotiation-after-handshake" + | "-async" + | "-implicit-handshake" + | "-use-old-client-cert-callback" + | "-use-early-callback" + | "-use-custom-verify-callback" + | "-reverify-on-resume" + | "-on-resume-expect-no-ech-name-override" => {} // Not implemented things - "-dtls" | - "-cipher" | - "-psk" | - "-renegotiate-freely" | - "-false-start" | - "-fallback-scsv" | - "-fail-early-callback" | - "-fail-cert-callback" | - "-install-ddos-callback" | - "-advertise-npn" | - "-advertise-empty-npn" | - "-verify-fail" | - "-expect-channel-id" | - "-send-channel-id" | - "-select-next-proto" | - "-select-empty-next-proto" | - "-expect-verify-result" | - "-send-alert" | - "-digest-prefs" | - "-use-exporter-between-reads" | - "-ticket-key" | - "-tls-unique" | - "-enable-server-custom-extension" | - "-enable-client-custom-extension" | - "-expect-dhe-group-size" | - "-use-ticket-callback" | - "-enable-grease" | - "-enable-channel-id" | - "-expect-early-data-info" | - "-expect-cipher-aes" | - "-retain-only-sha256-client-cert-initial" | - "-expect-draft-downgrade" | - "-allow-unknown-alpn-protos" | - "-on-initial-tls13-variant" | - "-on-resume-export-early-keying-material" | - "-on-resume-enable-early-data" | - "-export-early-keying-material" | - "-handshake-twice" | - "-on-resume-verify-fail" | - "-reverify-on-resume" | - "-no-op-extra-handshake" | - "-expect-peer-cert-file" | - "-no-rsa-pss-rsae-certs" | - "-ignore-tls13-downgrade" | - "-allow-hint-mismatch" | - "-wpa-202304" | - "-cnsa-202407" | - "-srtp-profiles" | - "-use-ticket-aead-callback" | - "-signed-cert-timestamps" | - "-on-initial-expect-peer-cert-file" | - "-resumption-across-names-enabled" | - "-expect-resumable-across-names" | - "-expect-not-resumable-across-names" | - "-use-custom-verify-callback" => { + "-dtls" + | "-cipher" + | "-psk" + | "-renegotiate-freely" + | "-false-start" + | "-fallback-scsv" + | "-fail-early-callback" + | "-fail-cert-callback" + | "-install-ddos-callback" + | "-advertise-npn" + | "-advertise-empty-npn" + | "-verify-fail" + | "-expect-channel-id" + | "-send-channel-id" + | "-select-next-proto" + | "-select-empty-next-proto" + | "-expect-verify-result" + | "-send-alert" + | "-digest-prefs" + | "-use-exporter-between-reads" + | "-ticket-key" + | "-tls-unique" + | "-enable-server-custom-extension" + | "-enable-client-custom-extension" + | "-expect-dhe-group-size" + | "-use-ticket-callback" + | "-enable-grease" + | "-enable-channel-id" + | "-expect-early-data-info" + | "-expect-cipher-aes" + | "-retain-only-sha256-client-cert-initial" + | "-expect-draft-downgrade" + | "-allow-unknown-alpn-protos" + | "-on-initial-tls13-variant" + | "-on-resume-export-early-keying-material" + | "-on-resume-enable-early-data" + | "-export-early-keying-material" + | "-handshake-twice" + | "-on-resume-verify-fail" + | "-on-retry-verify-fail" + | "-key-shares" + | "-no-key-shares" + | "-no-server-name-ack" + | "-no-op-extra-handshake" + | "-expect-peer-cert-file" + | "-no-rsa-pss-rsae-certs" + | "-ignore-tls13-downgrade" + | "-allow-hint-mismatch" + | "-wpa-202304" + | "-cnsa-202407" + | "-cnsa1-202603" + | "-cnsa2-202603" + | "-srtp-profiles" + | "-use-ticket-aead-callback" + | "-signed-cert-timestamps" + | "-on-initial-expect-peer-cert-file" + | "-resumption-across-names-enabled" + | "-expect-resumable-across-names" + | "-expect-not-resumable-across-names" => { println!("NYI option {arg:?}"); process::exit(BOGO_NACK); } diff --git a/ci-bench/Cargo.toml b/ci-bench/Cargo.toml index 63ae7d71236..446c77685a2 100644 --- a/ci-bench/Cargo.toml +++ b/ci-bench/Cargo.toml @@ -14,7 +14,7 @@ clap = { workspace = true } itertools = { workspace = true } rayon = { workspace = true } rustc-hash = { workspace = true } -rustls = { path = "../rustls", features = ["ring", "aws_lc_rs"] } +rustls = { package = "shaped-rustls", path = "../rustls", features = ["ring", "aws_lc_rs"] } rustls-test = { workspace = true } rustls-fuzzing-provider = { workspace = true } diff --git a/ci-bench/src/util.rs b/ci-bench/src/util.rs index 8ac4b34b4c2..4a014d9b508 100644 --- a/ci-bench/src/util.rs +++ b/ci-bench/src/util.rs @@ -1,3 +1,4 @@ +#[allow(clippy::double_must_use)] // https://github.com/rust-lang/rust-clippy/issues/17529 pub(crate) mod async_io { //! Async IO building blocks required for sharing code between the instruction count and //! wall-time benchmarks @@ -348,6 +349,7 @@ pub(crate) mod async_io { } } +#[allow(clippy::std_instead_of_core)] // awaits core::io::Cursor in stable (1.97) pub(crate) mod transport { //! Custom functions to interact between rustls clients and a servers. //! diff --git a/connect-tests/Cargo.toml b/connect-tests/Cargo.toml index 548c70d946d..8d854c8982b 100644 --- a/connect-tests/Cargo.toml +++ b/connect-tests/Cargo.toml @@ -7,10 +7,9 @@ description = "Rustls connectivity based integration tests." publish = false [dependencies] -rustls = { path = "../rustls", features = ["logging"] } +rustls = { package = "shaped-rustls", path = "../rustls", features = ["logging"] } [dev-dependencies] -hickory-resolver = { workspace = true } regex = { workspace = true } ring = { workspace = true } tokio = { workspace = true } diff --git a/connect-tests/tests/ech.rs b/connect-tests/tests/ech.rs deleted file mode 100644 index 9b56eac2f28..00000000000 --- a/connect-tests/tests/ech.rs +++ /dev/null @@ -1,67 +0,0 @@ -mod ech_config { - use hickory_resolver::config::ResolverConfig; - use hickory_resolver::name_server::TokioConnectionProvider; - use hickory_resolver::proto::rr::rdata::svcb::{SvcParamKey, SvcParamValue}; - use hickory_resolver::proto::rr::{RData, RecordType}; - use hickory_resolver::{Resolver, TokioResolver}; - use rustls::internal::msgs::codec::{Codec, Reader}; - use rustls::internal::msgs::handshake::EchConfigPayload; - use rustls::pki_types::EchConfigListBytes; - - #[tokio::test] - async fn cloudflare() { - test_deserialize_ech_config_list("research.cloudflare.com").await; - } - - #[tokio::test] - async fn defo_ie() { - test_deserialize_ech_config_list("defo.ie").await; - } - - #[tokio::test] - async fn tls_ech_dev() { - test_deserialize_ech_config_list("tls-ech.dev").await; - } - - /// Lookup the ECH config list for a domain and deserialize it. - async fn test_deserialize_ech_config_list(domain: &str) { - let resolver = Resolver::builder_with_config( - ResolverConfig::google_https(), - TokioConnectionProvider::default(), - ) - .build(); - let tls_encoded_list = lookup_ech(&resolver, domain).await; - let parsed_configs = Vec::::read(&mut Reader::init(&tls_encoded_list)) - .expect("failed to deserialize ECH config list"); - assert!(!parsed_configs.is_empty()); - assert!( - parsed_configs - .iter() - .all(|config| matches!(config, EchConfigPayload::V18(_))) - ); - } - - /// Use `resolver` to make an HTTPS record type query for `domain`, returning the - /// first SvcParam EchConfig value found, panicking if none are returned. - async fn lookup_ech(resolver: &TokioResolver, domain: &str) -> EchConfigListBytes<'static> { - resolver - .lookup(domain, RecordType::HTTPS) - .await - .expect("failed to lookup HTTPS record type") - .record_iter() - .find_map(|r| match r.data() { - RData::HTTPS(svcb) => svcb - .svc_params() - .iter() - .find_map(|sp| match sp { - (SvcParamKey::EchConfigList, SvcParamValue::EchConfigList(e)) => { - Some(e.clone().0) - } - _ => None, - }), - _ => None, - }) - .expect("missing expected HTTPS SvcParam EchConfig record") - .into() - } -} diff --git a/deny.toml b/deny.toml index b0559e7c6cd..1647cd8435d 100644 --- a/deny.toml +++ b/deny.toml @@ -17,4 +17,9 @@ private = { ignore = true } ignore = [ "RUSTSEC-2023-0071", # Marvin Attack on rsa, dev-dependency only "RUSTSEC-2024-0436", # Unmaintained paste via macro_rules_attributes; dev-dependency only + "RUSTSEC-2026-0173", # Unmaintained proc-macro-error2 via graviola -> libcrux; dev-dependency only + "RUSTSEC-2026-0207", # Broken libcrux-sha3, no fixed version for our MSRV via zeroize (dropped on main) + "RUSTSEC-2026-0208", # Ditto + "RUSTSEC-2026-0212", # Ditto for libcrux-secrets + "RUSTSEC-2026-0387", # Timing variability in crypto-bigint 0.5 via elliptic-curve 0.13; provider example and dev-dependencies only, no compatible fixed release ] diff --git a/examples/Cargo.toml b/examples/Cargo.toml index ce694b8fceb..41e45210474 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -13,7 +13,7 @@ hickory-resolver = { workspace = true } log = { workspace = true } mio = { workspace = true } rcgen = { workspace = true } -rustls = { path = "../rustls", features = ["logging"] } +rustls = { package = "shaped-rustls", path = "../rustls", features = ["logging"] } serde = { workspace = true } tokio = { workspace = true } webpki-roots = { workspace = true } diff --git a/examples/src/bin/ech-client.rs b/examples/src/bin/ech-client.rs index a8bf9896398..38439a2d411 100644 --- a/examples/src/bin/ech-client.rs +++ b/examples/src/bin/ech-client.rs @@ -35,11 +35,12 @@ use std::net::{TcpStream, ToSocketAddrs}; use std::sync::Arc; use clap::Parser; -use hickory_resolver::config::ResolverConfig; -use hickory_resolver::name_server::TokioConnectionProvider; +use hickory_resolver::config::{CLOUDFLARE, GOOGLE, ResolverConfig}; +use hickory_resolver::net::NetError; +use hickory_resolver::net::runtime::TokioRuntimeProvider; use hickory_resolver::proto::rr::rdata::svcb::{SvcParamKey, SvcParamValue}; use hickory_resolver::proto::rr::{RData, RecordType}; -use hickory_resolver::{ResolveError, Resolver, TokioResolver}; +use hickory_resolver::{Resolver, TokioResolver}; use log::trace; use rustls::RootCertStore; use rustls::client::{EchConfig, EchGreaseConfig, EchMode, EchStatus}; @@ -63,14 +64,14 @@ async fn main() -> Result<(), Box> { } (false, None) => { // Find raw ECH configs using DNS-over-HTTPS with Hickory DNS. - let resolver_config = if args.use_cloudflare_dns { - ResolverConfig::cloudflare_https() - } else { - ResolverConfig::google_https() - }; + let resolver_config = ResolverConfig::https(match args.use_cloudflare_dns { + true => &CLOUDFLARE, + false => &GOOGLE, + }); + lookup_ech_configs( - &Resolver::builder_with_config(resolver_config, TokioConnectionProvider::default()) - .build(), + &Resolver::builder_with_config(resolver_config, TokioRuntimeProvider::default()) + .build()?, &args.inner_hostname, args.port, ) @@ -229,7 +230,7 @@ async fn lookup_ech_configs( resolver: &TokioResolver, domain: &str, port: u16, -) -> Result>, ResolveError> { +) -> Result>, NetError> { // For non-standard ports, lookup the ECHConfig using port-prefix naming // See: https://datatracker.ietf.org/doc/html/rfc9460#section-9.1 let qname_to_lookup = match port { @@ -242,13 +243,13 @@ async fn lookup_ech_configs( .await?; let mut ech_config_lists = Vec::new(); - for r in lookup.record_iter() { - let RData::HTTPS(svcb) = r.data() else { + for r in lookup.answers() { + let RData::HTTPS(svcb) = &r.data else { continue; }; ech_config_lists.extend( - svcb.svc_params() + svcb.svc_params .iter() .find_map(|sp| match sp { (SvcParamKey::EchConfigList, SvcParamValue::EchConfigList(e)) => { diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 10807ff9d56..d517a4fcc00 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -273,33 +273,21 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rustls" -version = "0.23.40" -dependencies = [ - "log", - "once_cell", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - [[package]] name = "rustls-fuzz" version = "0.0.1" dependencies = [ "env_logger", "libfuzzer-sys", - "rustls", "rustls-fuzzing-provider", + "shaped-rustls", ] [[package]] name = "rustls-fuzzing-provider" version = "0.1.0" dependencies = [ - "rustls", + "shaped-rustls", ] [[package]] @@ -313,9 +301,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.5" +version = "0.103.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5a37813727b78798e53c2bec3f5e8fe12a6d6f8389bf9ca7802add4c9905ad8" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" dependencies = [ "ring", "rustls-pki-types", @@ -342,6 +330,18 @@ dependencies = [ "syn", ] +[[package]] +name = "shaped-rustls" +version = "0.23.4600" +dependencies = [ + "log", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + [[package]] name = "shlex" version = "1.3.0" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index b2884a8e10e..23871719d41 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -11,7 +11,7 @@ cargo-fuzz = true [dependencies] env_logger = "0.11" libfuzzer-sys = "0.4" -rustls = { path = "../rustls", default-features = false, features = ["std", "tls12", "custom-provider"] } +rustls = { package = "shaped-rustls", path = "../rustls", default-features = false, features = ["std", "tls12", "custom-provider"] } rustls-fuzzing-provider = { path = "../rustls-fuzzing-provider" } # Prevent this from interfering with workspaces diff --git a/openssl-tests/Cargo.toml b/openssl-tests/Cargo.toml index ab2b50044ba..4cdbf965d4a 100644 --- a/openssl-tests/Cargo.toml +++ b/openssl-tests/Cargo.toml @@ -11,5 +11,5 @@ asn1 = { workspace = true } base64 = { workspace = true } num-bigint = { workspace = true } once_cell = { workspace = true } -rustls = { path = "../rustls" } +rustls = { package = "shaped-rustls", path = "../rustls" } openssl = { workspace = true } diff --git a/openssl-tests/src/raw_key_openssl_interop.rs b/openssl-tests/src/raw_key_openssl_interop.rs index a6d8b50aadf..c82c26c14bb 100644 --- a/openssl-tests/src/raw_key_openssl_interop.rs +++ b/openssl-tests/src/raw_key_openssl_interop.rs @@ -150,6 +150,7 @@ mod client { } mod server { + #![allow(clippy::std_instead_of_core)] // awaits core::io::ErrorKind in stable (1.97) use std::io::{self, ErrorKind, Read, Write}; use std::net::TcpListener; use std::sync::Arc; diff --git a/provider-example/Cargo.toml b/provider-example/Cargo.toml index 3ca1a442311..831c7c3d222 100644 --- a/provider-example/Cargo.toml +++ b/provider-example/Cargo.toml @@ -17,7 +17,7 @@ hpke-rs-rust-crypto = { workspace = true } p256 = { workspace = true } pkcs8 = { workspace = true } rand_core = { workspace = true } -rustls = { path = "../rustls", default-features = false, features = ["logging", "tls12"] } +rustls = { package = "shaped-rustls", path = "../rustls", default-features = false, features = ["logging", "tls12"] } rsa = { workspace = true } sha2 = { workspace = true } signature = { workspace = true } diff --git a/rustls-bench/Cargo.toml b/rustls-bench/Cargo.toml index 89d8e725369..8e12662c77e 100644 --- a/rustls-bench/Cargo.toml +++ b/rustls-bench/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] clap = { workspace = true } -rustls = { path = "../rustls" } +rustls = { package = "shaped-rustls", path = "../rustls" } rustls-graviola = { workspace = true, optional = true } rustls-post-quantum = { path = "../rustls-post-quantum", optional = true } rustls-test = { workspace = true } diff --git a/rustls-fuzzing-provider/Cargo.toml b/rustls-fuzzing-provider/Cargo.toml index 80d6ae06523..bbe79899f5e 100644 --- a/rustls-fuzzing-provider/Cargo.toml +++ b/rustls-fuzzing-provider/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" publish = false [dependencies] -rustls = { path = "../rustls", default-features = false, features = ["logging", "std", "tls12"] } +rustls = { package = "shaped-rustls", path = "../rustls", default-features = false, features = ["logging", "std", "tls12"] } [dev-dependencies] env_logger = { workspace = true } diff --git a/rustls-post-quantum/Cargo.toml b/rustls-post-quantum/Cargo.toml index 4c17db70ba4..bfde56f035d 100644 --- a/rustls-post-quantum/Cargo.toml +++ b/rustls-post-quantum/Cargo.toml @@ -12,7 +12,7 @@ categories = ["network-programming", "cryptography"] autobenches = false [dependencies] -rustls = { version = "0.23.22", features = ["aws_lc_rs", "prefer-post-quantum"], path = "../rustls" } +rustls = { package = "shaped-rustls", version = "0.23.22", features = ["aws_lc_rs", "prefer-post-quantum"], path = "../rustls" } [dev-dependencies] criterion = { workspace = true } diff --git a/rustls-provider-test/Cargo.toml b/rustls-provider-test/Cargo.toml index 205e391df97..23c00d531b1 100644 --- a/rustls-provider-test/Cargo.toml +++ b/rustls-provider-test/Cargo.toml @@ -9,6 +9,6 @@ publish = false [dependencies] hex = "0.4" provider-example = { package = "rustls-provider-example", version = "0.0.1", path = "../provider-example" } -rustls = { version = "0.23.8", features = ["aws_lc_rs", "logging"], path = "../rustls" } +rustls = { package = "shaped-rustls", version = "0.23.8", features = ["aws_lc_rs", "logging"], path = "../rustls" } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/rustls-test/Cargo.toml b/rustls-test/Cargo.toml index 877ec34833e..6776c68f5b0 100644 --- a/rustls-test/Cargo.toml +++ b/rustls-test/Cargo.toml @@ -5,4 +5,4 @@ edition = "2021" publish = false [dependencies] -rustls = { path = "../rustls", default-features = false, features = ["std", "tls12"] } +rustls = { package = "shaped-rustls", path = "../rustls", default-features = false, features = ["std", "tls12"] } diff --git a/rustls-test/src/lib.rs b/rustls-test/src/lib.rs index e47b3502696..88fbff0bdee 100644 --- a/rustls-test/src/lib.rs +++ b/rustls-test/src/lib.rs @@ -1025,6 +1025,11 @@ impl io::Write for TestNonBlockIo { impl Drop for TestNonBlockIo { fn drop(&mut self) { + // avoid aborting on a double panic, which would hide the original failure + if std::thread::panicking() { + return; + } + // ensure the object was exhausted as expected assert!(self.reads.is_empty()); assert!(self.writes.is_empty()); @@ -1432,12 +1437,16 @@ impl RawTls { let encrypter = match (tx_keys, suite) { ( - rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv }, + rustls::ConnectionTrafficSecrets::Aes128Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv }, SupportedCipherSuite::Tls13(tls13), ) => tls13.aead_alg.encrypter(key, iv), ( - rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv }, + rustls::ConnectionTrafficSecrets::Aes128Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv }, SupportedCipherSuite::Tls12(tls12), ) => tls12 .aead_alg @@ -1448,12 +1457,16 @@ impl RawTls { let decrypter = match (rx_keys, suite) { ( - rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv }, + rustls::ConnectionTrafficSecrets::Aes128Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv }, SupportedCipherSuite::Tls13(tls13), ) => tls13.aead_alg.decrypter(key, iv), ( - rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv }, + rustls::ConnectionTrafficSecrets::Aes128Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Aes256Gcm { key, iv } + | rustls::ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv }, SupportedCipherSuite::Tls12(tls12), ) => tls12 .aead_alg @@ -1475,14 +1488,20 @@ impl RawTls { msg: &PlainMessage, peer: &mut impl DerefMut>, ) { + let data = self.encrypt(msg); + peer.read_tls(&mut io::Cursor::new(data)) + .unwrap(); + } + + /// Encrypt `msg` into a complete TLS record, including its header + pub fn encrypt(&mut self, msg: &PlainMessage) -> Vec { let data = self .encrypter .encrypt(msg.borrow_outbound(), self.enc_seq) .unwrap() .encode(); self.enc_seq += 1; - peer.read_tls(&mut io::Cursor::new(data)) - .unwrap(); + data } pub fn receive_and_decrypt( @@ -1804,15 +1823,17 @@ pub mod encoding { } } + pub fn new_versions_server_tls13() -> Self { + Self { + typ: ExtensionType::SupportedVersions, + body: ProtocolVersion::TLSv1_3 + .to_array() + .to_vec(), + } + } + pub fn new_dummy_key_share() -> Self { - const SOME_POINT_ON_P256: &[u8] = &[ - 4, 41, 39, 177, 5, 18, 186, 227, 237, 220, 254, 70, 120, 40, 18, 139, 173, 41, 3, - 38, 153, 25, 247, 8, 96, 105, 200, 196, 223, 108, 115, 40, 56, 199, 120, 121, 100, - 234, 172, 0, 229, 146, 31, 177, 73, 138, 96, 244, 96, 103, 102, 179, 217, 104, 80, - 1, 85, 141, 26, 151, 78, 115, 65, 81, 62, - ]; - - let mut share = len_u16(SOME_POINT_ON_P256.to_vec()); + let mut share = len_u16(Self::SOME_POINT_ON_P256.to_vec()); share.splice(0..0, NamedGroup::secp256r1.to_array()); Self { @@ -1821,12 +1842,29 @@ pub mod encoding { } } + pub fn new_dummy_key_share_server() -> Self { + let mut share = len_u16(Self::SOME_POINT_ON_P256.to_vec()); + share.splice(0..0, NamedGroup::secp256r1.to_array()); + + Self { + typ: ExtensionType::KeyShare, + body: share, + } + } + pub fn new_alpn(body: &[u8]) -> Self { Self { typ: ExtensionType::ALProtocolNegotiation, body: len_u16(body.to_vec()), } } + + const SOME_POINT_ON_P256: &[u8] = &[ + 4, 41, 39, 177, 5, 18, 186, 227, 237, 220, 254, 70, 120, 40, 18, 139, 173, 41, 3, 38, + 153, 25, 247, 8, 96, 105, 200, 196, 223, 108, 115, 40, 56, 199, 120, 121, 100, 234, + 172, 0, 229, 146, 31, 177, 73, 138, 96, 244, 96, 103, 102, 179, 217, 104, 80, 1, 85, + 141, 26, 151, 78, 115, 65, 81, 62, + ]; } /// Prefix with u8 length diff --git a/rustls/.clippy.toml b/rustls/.clippy.toml index 8b79eddd64c..581087081f3 100644 --- a/rustls/.clippy.toml +++ b/rustls/.clippy.toml @@ -1,5 +1,10 @@ upper-case-acronyms-aggressive = true +# Upstream's code is written for Rust 1.71. The manifest says 1.85 because of a +# dependency this fork adds; without this, Clippy would ask to rewrite upstream's +# code for the newer version. +msrv = "1.71" + disallowed-types = [ { path = "std::sync::Arc", reason = "must use Arc from sync module to support downstream forks targeting architectures without atomic ptrs" }, { path = "std::sync::Weak", reason = "must use Weak from sync module to support downstream forks targeting architectures without atomic ptrs" }, diff --git a/rustls/Cargo.toml b/rustls/Cargo.toml index 1713f4c3679..22fc58effaa 100644 --- a/rustls/Cargo.toml +++ b/rustls/Cargo.toml @@ -1,19 +1,24 @@ [package] -name = "rustls" -version = "0.23.40" +name = "shaped-rustls" +version = "0.23.4600" edition = "2021" -rust-version = "1.71" +rust-version = "1.85" license = "Apache-2.0 OR ISC OR MIT" readme = "../README.md" -description = "Rustls is a modern TLS library written in Rust." -homepage = "https://github.com/rustls/rustls" -repository = "https://github.com/rustls/rustls" +description = "A fork of rustls 0.23.46 with an opt-in API for shaping the TLS ClientHello (browser and uTLS fingerprints)." +repository = "https://github.com/aimalygin/shaped-rustls" categories = ["network-programming", "cryptography"] +keywords = ["tls", "rustls", "clienthello", "fingerprint", "utls"] autobenches = false autotests = false exclude = ["src/testdata", "tests/**"] build = "build.rs" +# The library keeps upstream's name, so that code written for rustls compiles +# against this package unchanged. +[lib] +name = "rustls" + [features] default = ["aws_lc_rs", "logging", "prefer-post-quantum", "std", "tls12"] diff --git a/rustls/src/client/builder.rs b/rustls/src/client/builder.rs index 30bf8a230e7..8b8c8f23b29 100644 --- a/rustls/src/client/builder.rs +++ b/rustls/src/client/builder.rs @@ -186,6 +186,7 @@ impl ConfigBuilder { cert_compression_cache: Arc::new(compress::CompressionCache::default()), cert_decompressors: compress::default_cert_decompressors().to_vec(), ech_mode: self.state.client_ech_mode, + send_ticket_request: None, } } } diff --git a/rustls/src/client/client_conn.rs b/rustls/src/client/client_conn.rs index 8c164ed9d3d..ee41824f178 100644 --- a/rustls/src/client/client_conn.rs +++ b/rustls/src/client/client_conn.rs @@ -293,6 +293,22 @@ pub struct ClientConfig { /// How to offer Encrypted Client Hello (ECH). The default is to not offer ECH. pub(super) ech_mode: Option, + + /// Request a specific number of TLS 1.3 session tickets via [RFC 9149]. + /// + /// Set to `None` to disable sending the extension (the default). + /// + /// [RFC 9149]: https://datatracker.ietf.org/doc/html/rfc9149 + pub send_ticket_request: Option, +} + +/// Desired session ticket counts for the RFC 9149 `ticket_request` extension. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TicketRequest { + /// Tickets desired when the server negotiates a new connection. + pub new_session_count: u8, + /// Tickets desired when the server resumes using a presented ticket. + pub resumption_count: u8, } impl ClientConfig { @@ -415,19 +431,20 @@ impl ClientConfig { } pub(super) fn needs_key_share(&self) -> bool { - self.supports_version(ProtocolVersion::TLSv1_3) + self.supports_version(ProtocolVersion::TLSv1_3, Protocol::Tcp) } /// We support a given TLS version if it's quoted in the configured /// versions *and* at least one ciphersuite for this version is /// also configured. - pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool { + pub(crate) fn supports_version(&self, v: ProtocolVersion, protocol: Protocol) -> bool { self.versions.contains(v) && self .provider .cipher_suites .iter() .any(|cs| cs.version().version == v) + && protocol.supports_version(v) } #[cfg(feature = "std")] @@ -438,12 +455,16 @@ impl ClientConfig { .any(|cs| cs.usable_for_protocol(proto)) } - pub(super) fn find_cipher_suite(&self, suite: CipherSuite) -> Option { + pub(super) fn find_cipher_suite( + &self, + suite: CipherSuite, + protocol: Protocol, + ) -> Option { self.provider .cipher_suites .iter() .copied() - .find(|&scs| scs.suite() == suite) + .find(|&scs| scs.suite() == suite && scs.usable_for_protocol(protocol)) } pub(super) fn find_kx_group( diff --git a/rustls/src/client/client_hello.rs b/rustls/src/client/client_hello.rs index ccbcf231360..5b8b9fab08d 100644 --- a/rustls/src/client/client_hello.rs +++ b/rustls/src/client/client_hello.rs @@ -332,17 +332,17 @@ where K: Ord, { if values.is_empty() { - return Err(Error::General( - format!("ClientHello {what} cannot be empty").into(), - )); + return Err(Error::General(format!( + "ClientHello {what} cannot be empty" + ))); } let mut seen = BTreeSet::new(); for value in values { if !seen.insert(key(*value)) { - return Err(Error::General( - format!("ClientHello {what} contains a duplicate value").into(), - )); + return Err(Error::General(format!( + "ClientHello {what} contains a duplicate value" + ))); } } @@ -351,9 +351,9 @@ where fn reject_empty(values: &[T], what: &str) -> Result<(), Error> { if values.is_empty() { - return Err(Error::General( - format!("ClientHello {what} cannot be empty").into(), - )); + return Err(Error::General(format!( + "ClientHello {what} cannot be empty" + ))); } Ok(()) diff --git a/rustls/src/client/common.rs b/rustls/src/client/common.rs index 9afa0c3410f..1bf0d8c7758 100644 --- a/rustls/src/client/common.rs +++ b/rustls/src/client/common.rs @@ -6,7 +6,7 @@ use crate::log::{debug, trace}; use crate::msgs::enums::ExtensionType; use crate::msgs::handshake::{CertificateChain, DistinguishedName, ProtocolName, ServerExtensions}; use crate::sync::Arc; -use crate::{SignatureScheme, compress, sign}; +use crate::{CipherSuite, SignatureScheme, compress, sign}; #[derive(Debug)] pub(super) struct ServerCertDetails<'a> { @@ -39,6 +39,7 @@ pub(super) struct ClientHelloDetails { pub(super) sent_extensions: Vec, pub(super) extension_order_seed: u16, pub(super) offered_cert_compression: bool, + pub(super) offered_cipher_suites: Vec, } impl ClientHelloDetails { @@ -48,6 +49,7 @@ impl ClientHelloDetails { sent_extensions: Vec::new(), extension_order_seed, offered_cert_compression: false, + offered_cipher_suites: Vec::new(), } } diff --git a/rustls/src/client/ech.rs b/rustls/src/client/ech.rs index 5675e71d092..88949d3e08a 100644 --- a/rustls/src/client/ech.rs +++ b/rustls/src/client/ech.rs @@ -326,6 +326,9 @@ pub(crate) struct EchState { enable_sni: bool, // The extensions sent in the inner hello. sent_extensions: Vec, + // Whether a hello retry request accepted our ECH offer, if we received one. RFC 9849 + // section 6.1.4 makes that decision final. + accepted_by_hello_retry_request: Option, } impl EchState { @@ -370,6 +373,7 @@ impl EchState { early_data_key_schedule: None, enable_sni, sent_extensions: Vec::new(), + accepted_by_hello_retry_request: None, }) } @@ -452,7 +456,17 @@ impl EchState { server_hello: &ServerHelloPayload, server_hello_encoded: &Payload<'_>, hash: &'static dyn Hash, + server_name: &mut ServerName<'static>, + common: &mut CommonState, ) -> Result, Error> { + // After a rejecting hello retry request the handshake continues with the outer hello + // without consulting the server hello, see RFC 9849 section 6.1.6. + if self.accepted_by_hello_retry_request == Some(false) { + trace!("ECH rejected by server in hello retry request"); + *server_name = ServerName::DnsName(self.outer_name); + return Ok(None); + } + // Start the inner transcript hash now that we know the hash algorithm to use. let inner_transcript = self .inner_hello_transcript @@ -486,15 +500,28 @@ impl EchState { sent_extensions: self.sent_extensions, })) } + // An accepting hello retry request requires an "illegal_parameter" alert here + // -- + false if self.accepted_by_hello_retry_request == Some(true) => Err(common + .send_fatal_alert( + AlertDescription::IllegalParameter, + PeerMisbehaved::EchAcceptanceVariedAfterRetry, + )), false => { trace!("ECH rejected by server"); + + // "If the server rejects ECH, the client proceeds with the handshake, authenticating + // for ECHConfig.contents.public_name" + // -- + *server_name = ServerName::DnsName(self.outer_name); + Ok(None) } } } pub(crate) fn confirm_hrr_acceptance( - &self, + &mut self, hrr: &HelloRetryRequest, cs: &Tls13CipherSuite, common: &mut CommonState, @@ -502,7 +529,10 @@ impl EchState { // The client checks for the "encrypted_client_hello" extension. let ech_conf = match &hrr.encrypted_client_hello { // If none is found, the server has implicitly rejected ECH. - None => return Ok(false), + None => { + self.accepted_by_hello_retry_request = Some(false); + return Ok(false); + } // Otherwise, if it has a length other than 8, the client aborts the // handshake with a "decode_error" alert. Some(ech_conf) if ech_conf.bytes().len() != 8 => { @@ -530,16 +560,18 @@ impl EchState { confirmation_transcript.current_hash(), ); - match ConstantTimeEq::ct_eq(derived.as_ref(), ech_conf.bytes()).into() { + let accepted = match ConstantTimeEq::ct_eq(derived.as_ref(), ech_conf.bytes()).into() { true => { trace!("ECH accepted by server in hello retry request"); - Ok(true) + true } false => { trace!("ECH rejected by server in hello retry request"); - Ok(false) + false } - } + }; + self.accepted_by_hello_retry_request = Some(accepted); + Ok(accepted) } /// Update the ECH context inner hello transcript based on a received hello retry request message. @@ -937,6 +969,253 @@ mod tests { } } + #[macro_rules_attribute::apply(test_for_each_provider)] + mod hello_retry_request { + use super::*; + use crate::common_state::Side; + use crate::crypto::SharedSecret; + use crate::msgs::base::PayloadU16; + use crate::msgs::handshake::{HelloRetryRequestExtensions, SupportedProtocolVersions}; + use crate::tls13::key_schedule::KeySchedulePreHandshake; + + #[test] + fn ech_rejection_in_server_hello_after_acceptance_in_hello_retry_request() { + let suite = tls13_suite(); + let hash = suite.common.hash_provider; + let mut state = ech_state(); + + // the server accepts our offer in its hello retry request... + state + .ech_hello(outer_hello(), None, &None) + .unwrap(); + let hrr = accepting_hello_retry_request(&state, suite); + assert!( + state + .confirm_hrr_acceptance(&hrr, suite, &mut CommonState::new(Side::Client)) + .unwrap() + ); + state.transcript_hrr_update(hash, &hrr_message(&hrr)); + state + .ech_hello(outer_hello(), Some(&hrr), &None) + .unwrap(); + + // ...but its server hello does not confirm that acceptance + let server_hello = server_hello(suite); + let mut server_name = inner_name(); + assert_eq!( + state + .confirm_acceptance( + &mut handshake_key_schedule(suite), + &server_hello, + &encode(&server_hello), + hash, + &mut server_name, + &mut CommonState::new(Side::Client), + ) + .err(), + Some(PeerMisbehaved::EchAcceptanceVariedAfterRetry.into()) + ); + } + + #[test] + fn ech_acceptance_in_server_hello_after_rejection_in_hello_retry_request() { + let suite = tls13_suite(); + let hash = suite.common.hash_provider; + let mut key_schedule = handshake_key_schedule(suite); + + // without a hello retry request, a confirming server hello accepts ECH + let mut state = ech_state(); + state + .ech_hello(outer_hello(), None, &None) + .unwrap(); + let server_hello = confirming_server_hello(&state, &mut key_schedule, suite); + let mut server_name = inner_name(); + assert!( + state + .confirm_acceptance( + &mut key_schedule, + &server_hello, + &encode(&server_hello), + hash, + &mut server_name, + &mut CommonState::new(Side::Client), + ) + .unwrap() + .is_some() + ); + assert_eq!(server_name, inner_name()); + + // but after a rejecting hello retry request, a confirming server hello cannot revive it + let mut state = ech_state(); + state + .ech_hello(outer_hello(), None, &None) + .unwrap(); + let hrr = hello_retry_request(suite, None); + assert!( + !state + .confirm_hrr_acceptance(&hrr, suite, &mut CommonState::new(Side::Client)) + .unwrap() + ); + state.transcript_hrr_update(hash, &hrr_message(&hrr)); + let server_hello = confirming_server_hello(&state, &mut key_schedule, suite); + let mut server_name = inner_name(); + assert!( + state + .confirm_acceptance( + &mut key_schedule, + &server_hello, + &encode(&server_hello), + hash, + &mut server_name, + &mut CommonState::new(Side::Client), + ) + .unwrap() + .is_none() + ); + assert_eq!(server_name, ServerName::from(public_name())); + } + + fn tls13_suite() -> &'static Tls13CipherSuite { + provider::cipher_suite::TLS13_AES_128_GCM_SHA256 + .tls13() + .unwrap() + } + + fn ech_state() -> EchState { + let config = EchConfig { + config: EchConfigPayload::V18(EchConfigContents { + key_config: HpkeKeyConfig { + config_id: 0, + kem_id: MockHpke::SUITE.kem, + public_key: PayloadU16::new(vec![0; 32]), + symmetric_cipher_suites: vec![MockHpke::SUITE.sym], + }, + maximum_name_length: 255, + public_name: public_name(), + extensions: vec![], + }), + suite: &MockHpke, + }; + + EchState::new(&config, inner_name(), false, &FixedRandom, true).unwrap() + } + + fn inner_name() -> ServerName<'static> { + ServerName::try_from("inner.example.com").unwrap() + } + + fn public_name() -> DnsName<'static> { + DnsName::try_from("public.example.com").unwrap() + } + + fn outer_hello() -> ClientHelloPayload { + ClientHelloPayload { + client_version: ProtocolVersion::TLSv1_2, + random: Random([0u8; 32]), + session_id: SessionId::empty(), + cipher_suites: vec![tls13_suite().common.suite], + compression_methods: vec![Compression::Null], + extensions: Box::new(ClientExtensions { + server_name: Some(ServerNamePayload::from(&public_name())), + supported_versions: Some(SupportedProtocolVersions::from_flags(false, true)), + ..Default::default() + }), + } + } + + fn hello_retry_request( + suite: &'static Tls13CipherSuite, + encrypted_client_hello: Option>, + ) -> HelloRetryRequest { + HelloRetryRequest { + legacy_version: ProtocolVersion::TLSv1_2, + session_id: SessionId::empty(), + cipher_suite: suite.common.suite, + extensions: HelloRetryRequestExtensions { + cookie: Some(PayloadU16::new(vec![1, 2, 3, 4])), + supported_versions: Some(ProtocolVersion::TLSv1_3), + encrypted_client_hello, + ..HelloRetryRequestExtensions::default() + }, + } + } + + /// A hello retry request accepting the offer in `state`, see RFC 9849 section 7.2.1. + fn accepting_hello_retry_request( + state: &EchState, + suite: &'static Tls13CipherSuite, + ) -> HelloRetryRequest { + let mut hrr = hello_retry_request(suite, Some(Payload::new(vec![0u8; 8]))); + let mut transcript = state + .inner_hello_transcript + .clone() + .start_hash(suite.common.hash_provider); + transcript.rollup_for_hrr(); + transcript.add_message(&EchState::hello_retry_request_conf(&hrr)); + let confirmation = server_ech_hrr_confirmation_secret( + suite.hkdf_provider, + &state.inner_hello_random.0, + transcript.current_hash(), + ); + hrr.encrypted_client_hello = Some(Payload::new(confirmation.to_vec())); + hrr + } + + fn hrr_message(hrr: &HelloRetryRequest) -> Message<'static> { + Message { + version: ProtocolVersion::TLSv1_2, + payload: MessagePayload::handshake(HandshakeMessagePayload( + HandshakePayload::HelloRetryRequest(hrr.clone()), + )), + } + } + + fn server_hello(suite: &'static Tls13CipherSuite) -> ServerHelloPayload { + ServerHelloPayload { + legacy_version: ProtocolVersion::TLSv1_2, + random: Random([0x55u8; 32]), + session_id: SessionId::empty(), + cipher_suite: suite.common.suite, + compression_method: Compression::Null, + extensions: Box::new(ServerExtensions::default()), + } + } + + /// A server hello accepting the offer in `state`, see RFC 9849 section 7.2. + fn confirming_server_hello( + state: &EchState, + key_schedule: &mut KeyScheduleHandshakeStart, + suite: &'static Tls13CipherSuite, + ) -> ServerHelloPayload { + let mut server_hello = server_hello(suite); + let mut transcript = state + .inner_hello_transcript + .clone() + .start_hash(suite.common.hash_provider); + transcript.add_message(&EchState::server_hello_conf( + &server_hello, + &encode(&server_hello), + )); + let confirmation = key_schedule.server_ech_confirmation_secret( + &state.inner_hello_random.0, + transcript.current_hash(), + ); + server_hello.random.0[24..].copy_from_slice(&confirmation); + server_hello + } + + fn encode(server_hello: &ServerHelloPayload) -> Payload<'static> { + Payload::new( + HandshakeMessagePayload(HandshakePayload::ServerHello(server_hello.clone())) + .get_encoding(), + ) + } + + fn handshake_key_schedule(suite: &'static Tls13CipherSuite) -> KeyScheduleHandshakeStart { + KeySchedulePreHandshake::new(suite).into_handshake(SharedSecret::from(&[0u8; 32][..])) + } + } + fn inner_hello_encoding_for_name(name: DnsName<'static>, enable_sni: bool) -> Vec { let config = EchConfig { config: EchConfigPayload::V18(EchConfigContents { @@ -1065,9 +1344,9 @@ mod tests { struct MockHpkeSealer; impl HpkeSealer for MockHpkeSealer { - #[cfg_attr(coverage_nightly, coverage(off))] - fn seal(&mut self, _aad: &[u8], _plaintext: &[u8]) -> Result, Error> { - todo!() + fn seal(&mut self, _aad: &[u8], plaintext: &[u8]) -> Result, Error> { + // ciphertext length as if sealed with the AEAD named in `MockHpke::SUITE` + Ok(vec![0xff; plaintext.len() + 16]) } } diff --git a/rustls/src/client/handy.rs b/rustls/src/client/handy.rs index 3ad3073bbd7..30011679daf 100644 --- a/rustls/src/client/handy.rs +++ b/rustls/src/client/handy.rs @@ -75,10 +75,19 @@ mod cache { } impl ClientSessionMemoryCache { - /// Make a new ClientSessionMemoryCache. `size` is the - /// maximum number of stored sessions. + /// Make a new `ClientSessionMemoryCache`. + /// + /// `size` determines the maximum number of servers to remember: + /// `size` divided by `MAX_TLS13_TICKETS_PER_SERVER` (8), rounded + /// up. Each server keeps up to 8 TLS 1.3 tickets. When the maximum + /// is reached, the server that was added first is evicted. + /// + /// For example, `new(100)` remembers up to 13 servers. Any `size` + /// from 1 to 8 remembers one server, and a `size` of 0 remembers + /// none. #[cfg(feature = "std")] pub fn new(size: usize) -> Self { + // Round up so that any non-zero size holds at least one server. let max_servers = size.saturating_add(MAX_TLS13_TICKETS_PER_SERVER - 1) / MAX_TLS13_TICKETS_PER_SERVER; Self { @@ -86,10 +95,19 @@ mod cache { } } - /// Make a new ClientSessionMemoryCache. `size` is the - /// maximum number of stored sessions. + /// Make a new `ClientSessionMemoryCache`. + /// + /// `size` determines the maximum number of servers to remember: + /// `size` divided by `MAX_TLS13_TICKETS_PER_SERVER` (8), rounded + /// up. Each server keeps up to 8 TLS 1.3 tickets. When the maximum + /// is reached, the server that was added first is evicted. + /// + /// For example, `new(100)` remembers up to 13 servers. Any `size` + /// from 1 to 8 remembers one server, and a `size` of 0 remembers + /// none. #[cfg(not(feature = "std"))] pub fn new(size: usize) -> Self { + // Round up so that any non-zero size holds at least one server. let max_servers = size.saturating_add(MAX_TLS13_TICKETS_PER_SERVER - 1) / MAX_TLS13_TICKETS_PER_SERVER; Self { @@ -247,10 +265,14 @@ impl client::ResolvesClientCert for AlwaysResolvesClientRawPublicKeys { #[cfg(test)] #[macro_rules_attribute::apply(test_for_each_provider)] mod tests { + use core::time::Duration; use std::prelude::v1::*; + use std::{format, vec}; use pki_types::{ServerName, UnixTime}; + #[cfg(feature = "std")] + use super::ClientSessionMemoryCache; use super::NoClientSessionStorage; use super::provider::cipher_suite; use crate::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; @@ -327,6 +349,121 @@ mod tests { assert!(c.take_tls13_ticket(&name).is_none()); } + #[test] + fn debug_of_session_types() { + let server_cert_verifier: Arc = Arc::new(DummyServerCertVerifier); + let resolves_client_cert: Arc = Arc::new(DummyResolvesClientCert); + + #[cfg(feature = "tls12")] + { + use crate::msgs::persist::Tls12ClientSessionValue; + let SupportedCipherSuite::Tls12(tls12_suite) = + cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + else { + unreachable!() + }; + + let tls12 = Tls12ClientSessionValue::new( + tls12_suite, + SessionId::empty(), + Arc::new(PayloadU16::new(vec![5])), + &[0xa5; 48], + CertificateChain::default(), + &server_cert_verifier, + &resolves_client_cert, + UnixTime::since_unix_epoch(Duration::from_secs(1)), + 2, + true, + ); + let debug = format!("{tls12:?}"); + assert!( + debug.contains("ClientSessionCommon { ticket: 05, epoch: 1, lifetime_secs: 2,") + ); + assert!(!debug.contains("a5a5"), "{debug}"); + } + + let SupportedCipherSuite::Tls13(tls13_suite) = cipher_suite::TLS13_AES_256_GCM_SHA384 + else { + unreachable!(); + }; + let tls13 = Tls13ClientSessionValue::new( + tls13_suite, + Arc::new(PayloadU16::new(vec![5])), + &[0xa5; 32], + CertificateChain::default(), + &server_cert_verifier, + &resolves_client_cert, + UnixTime::since_unix_epoch(Duration::from_secs(1)), + 2, + 3, + 0, + ); + let debug = format!("{tls13:?}"); + assert!(debug.contains("ClientSessionCommon { ticket: 05, epoch: 1, lifetime_secs: 2,")); + assert!(!debug.contains("a5a5"), "{debug}"); + } + + /// For each `size` from 1 to 8, the cache keeps one server's key + /// exchange hint and TLS 1.3 ticket. + #[cfg(feature = "std")] + #[test] + fn test_clientsessionmemorycache_small_sizes_retain_server() { + for size in 1..=8 { + let c = ClientSessionMemoryCache::new(size); + let name = ServerName::try_from("example.com").unwrap(); + + c.set_kx_hint(name.clone(), NamedGroup::X25519); + assert_eq!(c.kx_hint(&name), Some(NamedGroup::X25519), "size {size}"); + + c.insert_tls13_ticket(name.clone(), tls13_session(UnixTime::now())); + assert!(c.take_tls13_ticket(&name).is_some(), "size {size}"); + } + } + + /// A cache of size 9 remembers two servers: after three servers are + /// added, the first is evicted and the other two remain. + #[cfg(feature = "std")] + #[test] + fn test_clientsessionmemorycache_evicts_oldest_server() { + let c = ClientSessionMemoryCache::new(9); + let first = ServerName::try_from("first.example.com").unwrap(); + let second = ServerName::try_from("second.example.com").unwrap(); + let third = ServerName::try_from("third.example.com").unwrap(); + + c.set_kx_hint(first.clone(), NamedGroup::X25519); + c.set_kx_hint(second.clone(), NamedGroup::X25519); + c.set_kx_hint(third.clone(), NamedGroup::X25519); + + assert_eq!(c.kx_hint(&first), None); + assert_eq!(c.kx_hint(&second), Some(NamedGroup::X25519)); + assert_eq!(c.kx_hint(&third), Some(NamedGroup::X25519)); + } + + /// Test helper: builds a placeholder TLS 1.3 ticket. Its contents are + /// empty or dummy values; the tests only check whether the cache + /// keeps it. + #[cfg(feature = "std")] + fn tls13_session(now: UnixTime) -> Tls13ClientSessionValue { + let SupportedCipherSuite::Tls13(tls13_suite) = cipher_suite::TLS13_AES_256_GCM_SHA384 + else { + unreachable!(); + }; + let server_cert_verifier: Arc = Arc::new(DummyServerCertVerifier); + let resolves_client_cert: Arc = Arc::new(DummyResolvesClientCert); + Tls13ClientSessionValue::new( + tls13_suite, + Arc::new(PayloadU16::empty()), + &[], + CertificateChain::default(), + &server_cert_verifier, + &resolves_client_cert, + now, + 0, + 0, + 0, + ) + } + #[derive(Debug)] struct DummyServerCertVerifier; diff --git a/rustls/src/client/hs.rs b/rustls/src/client/hs.rs index daa20695c81..a5c6dee7dab 100644 --- a/rustls/src/client/hs.rs +++ b/rustls/src/client/hs.rs @@ -37,9 +37,10 @@ use crate::msgs::codec::{Codec, Reader}; use crate::msgs::enums::{Compression, ExtensionType, NamedGroup}; use crate::msgs::handshake::{ CertificateStatusRequest, ClientExtensions, ClientExtensionsInput, ClientHelloPayload, - ClientSessionTicket, EncryptedClientHello, HandshakeMessagePayload, HandshakePayload, - HelloRetryRequest, KeyShareEntry, ProtocolName, PskKeyExchangeModes, Random, ServerNamePayload, - SessionId, SupportedEcPointFormats, SupportedProtocolVersions, TransportParameters, + ClientSessionTicket, ClientTicketRequest, EncryptedClientHello, HandshakeMessagePayload, + HandshakePayload, HelloRetryRequest, KeyShareEntry, ProtocolName, PskKeyExchangeModes, Random, + ServerNamePayload, SessionId, SupportedEcPointFormats, SupportedProtocolVersions, + TransportParameters, }; use crate::msgs::message::{Message, MessagePayload}; use crate::msgs::persist; @@ -63,7 +64,6 @@ struct ExpectServerHello { // // If this is `None` then we do not support early data. early_data_key_schedule: Option, - offered_cipher_suites: Vec, offered_key_share: Option, suite: Option, ech_state: Option, @@ -122,7 +122,9 @@ impl ClientHelloInput { let session_id = match session_id { Some(session_id) => session_id, None if cx.common.is_quic() => SessionId::empty(), - None if !config.supports_version(ProtocolVersion::TLSv1_3) => SessionId::empty(), + None if !config.supports_version(ProtocolVersion::TLSv1_3, cx.common.protocol) => { + SessionId::empty() + } None => SessionId::random(config.provider.secure_random)?, }; @@ -143,10 +145,12 @@ impl ClientHelloInput { .copied() .filter(|version| match version.version { ProtocolVersion::TLSv1_2 => { - !forbids_tls12 && config.supports_version(ProtocolVersion::TLSv1_2) + !forbids_tls12 + && config + .supports_version(ProtocolVersion::TLSv1_2, cx.common.protocol) } ProtocolVersion::TLSv1_3 => { - config.supports_version(ProtocolVersion::TLSv1_3) + config.supports_version(ProtocolVersion::TLSv1_3, cx.common.protocol) } _ => false, }) @@ -256,29 +260,31 @@ impl ClientHelloInput { fn default_supported_versions( config: &ClientConfig, + protocol: Protocol, forbids_tls12: bool, ) -> SupportedProtocolVersions { SupportedProtocolVersions::from_flags( - config.supports_version(ProtocolVersion::TLSv1_2) && !forbids_tls12, - config.supports_version(ProtocolVersion::TLSv1_3), + config.supports_version(ProtocolVersion::TLSv1_2, protocol) && !forbids_tls12, + config.supports_version(ProtocolVersion::TLSv1_3, protocol), ) } fn planned_supported_versions( plan: Option<&ClientHelloPlan>, config: &ClientConfig, + protocol: Protocol, forbids_tls12: bool, ) -> Result { let Some(versions) = plan.and_then(|plan| plan.supported_versions.as_ref()) else { - return Ok(default_supported_versions(config, forbids_tls12)); + return Ok(default_supported_versions(config, protocol, forbids_tls12)); }; for version in versions.as_slice() { let supported = match *version { ProtocolVersion::TLSv1_2 => { - !forbids_tls12 && config.supports_version(ProtocolVersion::TLSv1_2) + !forbids_tls12 && config.supports_version(ProtocolVersion::TLSv1_2, protocol) } - ProtocolVersion::TLSv1_3 => config.supports_version(ProtocolVersion::TLSv1_3), + ProtocolVersion::TLSv1_3 => config.supports_version(ProtocolVersion::TLSv1_3, protocol), _ => false, }; @@ -480,6 +486,7 @@ fn apply_extension_plan( hello.offered_cert_compression = false; } ExtensionType::SessionTicket => exts.session_ticket = None, + ExtensionType::TicketRequest => exts.ticket_request = None, ExtensionType::PreSharedKey => { if exts.preshared_key_offer.is_some() { return Err(Error::General( @@ -805,9 +812,9 @@ const PADDING_EXTENSION_HEADER_LEN: usize = 4; fn insert_at(items: &mut Vec, position: usize, value: T, what: &str) -> Result<(), Error> { if position > items.len() { - return Err(Error::General( - format!("ClientHello GREASE position is out of range for {what}").into(), - )); + return Err(Error::General(format!( + "ClientHello GREASE position is out of range for {what}" + ))); } items.insert(position, value); @@ -978,8 +985,12 @@ fn emit_client_hello_for_retry( // builder semantics. let forbids_tls12 = cx.common.is_quic() || ech_state.is_some(); - let supported_versions = - planned_supported_versions(input.plan.as_ref(), config, forbids_tls12)?; + let supported_versions = planned_supported_versions( + input.plan.as_ref(), + config, + cx.common.protocol, + forbids_tls12, + )?; // should be unreachable thanks to config builder assert!(supported_versions.any(|_| true)); @@ -1027,6 +1038,17 @@ fn emit_client_hello_for_retry( ..Default::default() }); + if !config + .crypto_provider() + .cipher_suites + .iter() + .any(|cs| cs.tls13().is_some()) + { + if let Some(schemes) = &mut exts.signature_schemes { + schemes.retain(|scheme| scheme.algorithm().is_some()); + } + } + match extra_exts.transport_parameters.clone() { Some(TransportParameters::Quic(v)) => exts.transport_parameters = Some(v), Some(TransportParameters::QuicDraft(v)) => exts.transport_parameters_draft = Some(v), @@ -1083,6 +1105,13 @@ fn emit_client_hello_for_retry( psk: false, psk_dhe: true, }); + + if let Some(ticket_req) = &config.send_ticket_request { + exts.ticket_request = Some(ClientTicketRequest { + new_session_count: ticket_req.new_session_count, + resumption_count: ticket_req.resumption_count, + }); + } } input.hello.offered_cert_compression = match input.plan.as_ref().and_then(|plan| { @@ -1310,17 +1339,15 @@ fn emit_client_hello_for_retry( } // If we haven't offered ECH, and have no ECH state, then consider whether to use GREASE // ECH. - (EchStatus::NotOffered, None) => { - if !has_exact_ech { - if let Some(grease_ext) = ech_grease_ext { - // Add the GREASE ECH extension. - let grease_ext = grease_ext?; - chp_payload.encrypted_client_hello = Some(grease_ext.clone()); - cx.data.ech_status = EchStatus::Grease; - // Store the GREASE ECH extension in case we need to carry it forward in a - // subsequent hello. - input.prev_ech_ext = Some(grease_ext); - } + (EchStatus::NotOffered, None) if !has_exact_ech => { + if let Some(grease_ext) = ech_grease_ext { + // Add the GREASE ECH extension. + let grease_ext = grease_ext?; + chp_payload.encrypted_client_hello = Some(grease_ext.clone()); + cx.data.ech_status = EchStatus::Grease; + // Store the GREASE ECH extension in case we need to carry it forward in a + // subsequent hello. + input.prev_ech_ext = Some(grease_ext); } } _ => {} @@ -1332,7 +1359,7 @@ fn emit_client_hello_for_retry( input.hello.sent_extensions = chp_payload .extensions .collect_used_with_raw(); - let offered_cipher_suites = chp_payload.cipher_suites.clone(); + input.hello.offered_cipher_suites = chp_payload.cipher_suites.clone(); let mut chp = HandshakeMessagePayload(HandshakePayload::ClientHello(chp_payload)); @@ -1433,7 +1460,6 @@ fn emit_client_hello_for_retry( input, transcript_buffer, early_data_key_schedule, - offered_cipher_suites, offered_key_share: key_share, suite, ech_state, @@ -1583,7 +1609,7 @@ fn prepare_resumption<'a>( let resuming = match resuming { Some(resuming) if !resuming.ticket().is_empty() => resuming, _ => { - if config.supports_version(ProtocolVersion::TLSv1_2) + if config.supports_version(ProtocolVersion::TLSv1_2, cx.common.protocol) && config.resumption.tls12_resumption == Tls12Resumption::SessionIdOrTickets { // If we don't have a ticket, request one. @@ -1595,7 +1621,7 @@ fn prepare_resumption<'a>( let Some(tls13) = resuming.map(|csv| csv.tls13()) else { // TLS 1.2; send the ticket if we have support this protocol version - if config.supports_version(ProtocolVersion::TLSv1_2) + if config.supports_version(ProtocolVersion::TLSv1_2, cx.common.protocol) && config.resumption.tls12_resumption == Tls12Resumption::SessionIdOrTickets { exts.session_ticket = Some(ClientSessionTicket::Offer(Payload::new(resuming.ticket()))); @@ -1603,7 +1629,7 @@ fn prepare_resumption<'a>( return None; // TLS 1.2, so nothing to return here }; - if !config.supports_version(ProtocolVersion::TLSv1_3) { + if !config.supports_version(ProtocolVersion::TLSv1_3, cx.common.protocol) { return None; } @@ -1709,7 +1735,7 @@ impl State for ExpectServerHello { use crate::ProtocolVersion::{TLSv1_2, TLSv1_3}; let config = &self.input.config; - let tls13_supported = config.supports_version(TLSv1_3); + let tls13_supported = config.supports_version(TLSv1_3, cx.common.protocol); let server_version = if server_hello.legacy_version == TLSv1_2 { server_hello @@ -1721,7 +1747,7 @@ impl State for ExpectServerHello { let version = match server_version { TLSv1_3 if tls13_supported => TLSv1_3, - TLSv1_2 if config.supports_version(TLSv1_2) => { + TLSv1_2 if config.supports_version(TLSv1_2, cx.common.protocol) => { if cx.data.early_data.is_enabled() && cx.common.early_traffic { // The client must fail with a dedicated error code if the server // responds with TLS 1.2 when offering 0-RTT. @@ -1797,26 +1823,18 @@ impl State for ExpectServerHello { } } - if !self + let Some(Some(suite)) = self + .input + .hello .offered_cipher_suites .contains(&server_hello.cipher_suite) - { - return Err({ - cx.common.send_fatal_alert( - AlertDescription::HandshakeFailure, - PeerMisbehaved::SelectedUnofferedCipherSuite, - ) - }); - } - - let suite = config - .find_cipher_suite(server_hello.cipher_suite) - .ok_or_else(|| { - cx.common.send_fatal_alert( - AlertDescription::HandshakeFailure, - PeerMisbehaved::SelectedUnofferedCipherSuite, - ) - })?; + .then(|| config.find_cipher_suite(server_hello.cipher_suite, cx.common.protocol)) + else { + return Err(cx.common.send_fatal_alert( + AlertDescription::HandshakeFailure, + PeerMisbehaved::SelectedUnofferedCipherSuite, + )); + }; if version != suite.version().version { return Err({ @@ -1982,6 +2000,8 @@ impl ExpectServerHelloOrHelloRetryRequest { // Or asks us to use a ciphersuite we didn't offer. if !self .next + .input + .hello .offered_cipher_suites .contains(&hrr.cipher_suite) { @@ -1993,7 +2013,7 @@ impl ExpectServerHelloOrHelloRetryRequest { }); } - let Some(cs) = config.find_cipher_suite(hrr.cipher_suite) else { + let Some(cs) = config.find_cipher_suite(hrr.cipher_suite, cx.common.protocol) else { return Err({ cx.common.send_fatal_alert( AlertDescription::IllegalParameter, @@ -2017,20 +2037,18 @@ impl ExpectServerHelloOrHelloRetryRequest { cx.common.handshake_kind = Some(HandshakeKind::FullWithHelloRetryRequest); // If we offered ECH, we need to confirm that the server accepted it. - match (self.next.ech_state.as_ref(), cs.tls13()) { - // If the server did not confirm, then note the new ECH status but - // continue the handshake. We will abort with an ECH required error - // at the end. - (Some(ech_state), Some(tls13_cs)) - if !ech_state.confirm_hrr_acceptance(hrr, tls13_cs, cx.common)? => - { - cx.data.ech_status = EchStatus::Rejected - } - (Some(_), None) => { + if let Some(ech_state) = self.next.ech_state.as_mut() { + let Some(tls13_cs) = cs.tls13() else { unreachable!("ECH state should only be set when TLS 1.3 was negotiated") + }; + + if !ech_state.confirm_hrr_acceptance(hrr, tls13_cs, cx.common)? { + // If the server did not confirm, then note the new ECH status but + // continue the handshake. We will abort with an ECH required error + // at the end. + cx.data.ech_status = EchStatus::Rejected; } - _ => {} - }; + } // This is the draft19 change where the transcript became a tree let transcript = self diff --git a/rustls/src/client/test.rs b/rustls/src/client/test.rs index 15462241f00..c42b3b36ae3 100644 --- a/rustls/src/client/test.rs +++ b/rustls/src/client/test.rs @@ -3,7 +3,7 @@ use alloc::boxed::Box; use alloc::vec; use alloc::vec::Vec; use core::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc as StdArc, Mutex}; +use std::sync::Mutex; use pki_types::{CertificateDer, ServerName}; @@ -45,6 +45,7 @@ mod tests { use crate::crypto::tls13::OkmBlock; use crate::enums::CertificateType; use crate::msgs::base::PayloadU8; + use crate::msgs::ccs::ChangeCipherSpecPayload; use crate::msgs::enums::ECCurveType; use crate::msgs::handshake::{ CertificateChain, EcParameters, HelloRetryRequestExtensions, KeyShareEntry, @@ -123,7 +124,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_random(fixed_random))), })); @@ -141,7 +142,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_session_id( ClientHelloSessionId::try_from(session_id.clone()).unwrap(), ))), @@ -154,15 +155,15 @@ mod tests { #[test] fn client_hello_customizer_captures_raw_client_hello() { - let captured = StdArc::new(Mutex::new(Vec::new())); + let captured = Arc::new(Mutex::new(Vec::new())); let mut config = ClientConfig::builder_with_provider(super::provider::default_provider().into()) .with_protocol_versions(&[&version::TLS13]) .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { - plan: Mutex::new(Some(ClientHelloPlan::new().with_capture(StdArc::new( + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { + plan: Mutex::new(Some(ClientHelloPlan::new().with_capture(Arc::new( RecordingClientHelloCapture { bytes: captured.clone(), }, @@ -176,8 +177,8 @@ mod tests { #[test] fn client_hello_finalizer_patches_captured_and_emitted_session_id() { - let captured = StdArc::new(Mutex::new(Vec::new())); - let finalizer_called = StdArc::new(AtomicBool::new(false)); + let captured = Arc::new(Mutex::new(Vec::new())); + let finalizer_called = Arc::new(AtomicBool::new(false)); let replacement_session_id = [0x5au8; 32]; let mut config = ClientConfig::builder_with_provider(super::provider::default_provider().into()) @@ -185,15 +186,15 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_session_id(ClientHelloSessionId::try_from(vec![0; 32]).unwrap()) - .with_finalizer(StdArc::new(PatchingClientHelloFinalizer { + .with_finalizer(Arc::new(PatchingClientHelloFinalizer { replacement_session_id, called: finalizer_called.clone(), })) - .with_capture(StdArc::new(RecordingClientHelloCapture { + .with_capture(Arc::new(RecordingClientHelloCapture { bytes: captured.clone(), })), )), @@ -209,18 +210,18 @@ mod tests { #[test] fn client_hello_finalizer_error_fails_before_emitting_client_hello() { - let finalizer_called = StdArc::new(AtomicBool::new(false)); + let finalizer_called = Arc::new(AtomicBool::new(false)); let mut config = ClientConfig::builder_with_provider(super::provider::default_provider().into()) .with_protocol_versions(&[&version::TLS13]) .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_session_id(ClientHelloSessionId::try_from(vec![0; 32]).unwrap()) - .with_finalizer(StdArc::new(FailingClientHelloFinalizer { + .with_finalizer(Arc::new(FailingClientHelloFinalizer { called: finalizer_called.clone(), })), )), @@ -238,18 +239,18 @@ mod tests { #[test] fn client_hello_finalizer_rejects_non_session_id_changes() { - let finalizer_called = StdArc::new(AtomicBool::new(false)); + let finalizer_called = Arc::new(AtomicBool::new(false)); let mut config = ClientConfig::builder_with_provider(super::provider::default_provider().into()) .with_protocol_versions(&[&version::TLS13]) .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_session_id(ClientHelloSessionId::try_from(vec![0; 32]).unwrap()) - .with_finalizer(StdArc::new(MutatingClientHelloFinalizer { + .with_finalizer(Arc::new(MutatingClientHelloFinalizer { mutation: ClientHelloFinalizerMutation::NonSessionByte, called: finalizer_called.clone(), })), @@ -268,18 +269,18 @@ mod tests { #[test] fn client_hello_finalizer_rejects_length_changes() { - let finalizer_called = StdArc::new(AtomicBool::new(false)); + let finalizer_called = Arc::new(AtomicBool::new(false)); let mut config = ClientConfig::builder_with_provider(super::provider::default_provider().into()) .with_protocol_versions(&[&version::TLS13]) .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_session_id(ClientHelloSessionId::try_from(vec![0; 32]).unwrap()) - .with_finalizer(StdArc::new(MutatingClientHelloFinalizer { + .with_finalizer(Arc::new(MutatingClientHelloFinalizer { mutation: ClientHelloFinalizerMutation::Length, called: finalizer_called.clone(), })), @@ -299,7 +300,7 @@ mod tests { #[cfg(feature = "aws_lc_rs")] #[test] fn client_hello_finalizer_session_id_completes_tls13_handshake() { - let finalizer_called = StdArc::new(AtomicBool::new(false)); + let finalizer_called = Arc::new(AtomicBool::new(false)); let replacement_session_id = [0x5au8; 32]; let provider = super::provider::default_provider(); let mut client_config = ClientConfig::builder_with_provider(provider.clone().into()) @@ -307,11 +308,11 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - client_config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + client_config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_session_id(ClientHelloSessionId::try_from(vec![0; 32]).unwrap()) - .with_finalizer(StdArc::new(PatchingClientHelloFinalizer { + .with_finalizer(Arc::new(PatchingClientHelloFinalizer { replacement_session_id, called: finalizer_called.clone(), })), @@ -345,7 +346,7 @@ mod tests { assert!(!baseline.extensions.is_empty()); let mut config = tls13_x25519_config_with_alpn(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(None), })); @@ -364,7 +365,7 @@ mod tests { assert!(!baseline.extensions.is_empty()); let mut config = tls13_x25519_config_with_alpn(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new())), })); @@ -394,7 +395,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_extension_order(order))), })); @@ -429,7 +432,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_cipher_suites(cipher_suites), )), @@ -456,7 +459,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_cipher_suites(cipher_suites), )), @@ -483,7 +486,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_advertised_cipher_suites(cipher_suites), )), @@ -514,7 +517,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_advertised_cipher_suites(cipher_suites), )), @@ -563,7 +566,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_advertised_cipher_suites(cipher_suites), )), @@ -612,7 +615,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_supported_versions(versions), )), @@ -639,7 +642,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_supported_versions(versions), )), @@ -670,7 +673,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_supported_groups(groups))), })); @@ -694,7 +697,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_supported_groups(groups))), })); @@ -728,7 +731,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_advertised_supported_versions(versions) @@ -770,7 +773,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_signature_algorithms(signature_algorithms), )), @@ -799,7 +802,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_signature_algorithms(signature_algorithms), )), @@ -827,7 +830,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_signature_algorithms(signature_algorithms), )), @@ -859,7 +862,7 @@ mod tests { .with_root_certificates(roots()) .with_no_client_auth(); config.cert_decompressors = vec![&ZLIB_DECOMPRESSOR, &BROTLI_DECOMPRESSOR]; - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_certificate_compression_algorithms(algorithms), )), @@ -890,7 +893,7 @@ mod tests { .with_root_certificates(roots()) .with_no_client_auth(); config.cert_decompressors.clear(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_certificate_compression_algorithms(algorithms), )), @@ -914,7 +917,7 @@ mod tests { .with_root_certificates(roots()) .with_no_client_auth(); config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_alpn_protocols(alpn))), })); @@ -954,7 +957,7 @@ mod tests { .with_root_certificates(roots()) .with_no_client_auth(); config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_extensions(extensions))), })); @@ -1004,7 +1007,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_extensions(extensions))), })); @@ -1053,7 +1056,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_forced_extensions(forced) @@ -1106,7 +1111,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_grease(grease))), })); @@ -1160,7 +1165,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_extension_order(order) @@ -1214,7 +1221,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_extension_order(order) @@ -1253,7 +1262,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_grease(grease))), })); @@ -1287,7 +1296,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_supported_versions(versions) @@ -1324,7 +1333,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_exact_extensions(exact_extensions), )), @@ -1376,7 +1385,7 @@ mod tests { .with_root_certificates(roots()) .with_no_client_auth(); config.cert_decompressors = vec![&BROTLI_DECOMPRESSOR]; - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_alpn_protocols(alpn) @@ -1416,6 +1425,8 @@ mod tests { .assert_matches_encoded(&encoded); } + // The FIPS provider offers no X25519 key share. + #[cfg(not(feature = "fips"))] #[test] fn client_hello_oracle_can_place_forced_and_grease_extensions_before_padding() { static BROTLI_DECOMPRESSOR: TestCertDecompressor = @@ -1513,7 +1524,7 @@ mod tests { .with_root_certificates(roots()) .with_no_client_auth(); config.cert_decompressors = vec![&BROTLI_DECOMPRESSOR]; - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_advertised_cipher_suites(advertised_cipher_suites) @@ -1625,7 +1636,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_cipher_suites(cipher_suites) @@ -1715,7 +1728,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_grease(grease))), })); @@ -1738,7 +1751,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_grease(grease))), })); @@ -1787,7 +1800,7 @@ mod tests { #[test] fn client_hello_customizer_keeps_the_planned_order_when_nothing_is_elided() { let mut config = tls13_x25519_client_config(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(planned_order_with_grease())), })); @@ -1829,7 +1842,7 @@ mod tests { ]) .unwrap(); let mut config = tls13_x25519_client_config(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_extension_order(order))), })); @@ -1863,7 +1876,7 @@ mod tests { .with_extension(ClientHelloGreaseExtension::new(0x0a0a, 10, vec![]).unwrap()) .unwrap(); let mut config = tls13_x25519_client_config(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_extension_order(order) @@ -1945,7 +1958,7 @@ mod tests { fn ip_literal_client_hello(plan: ClientHelloPlan) -> Result, Error> { let mut config = tls13_x25519_client_config(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(plan)), })); @@ -1979,7 +1992,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_grease(grease))), })); @@ -2008,7 +2021,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_key_share_plan(key_shares))), })); @@ -2028,7 +2041,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_key_share_plan(key_shares))), })); @@ -2050,7 +2063,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new().with_raw_key_shares(raw_key_shares), )), @@ -2080,7 +2093,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_raw_key_shares(raw_key_shares) @@ -2119,7 +2132,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_padding(padding))), })); @@ -2156,7 +2169,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_padding(padding))), })); @@ -2196,7 +2209,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_raw_extensions(raw_extensions) @@ -2250,7 +2265,9 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + // The expected extension list has no compress_certificate. + config.cert_decompressors.clear(); + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_exact_extensions(exact_extensions) @@ -2286,9 +2303,11 @@ mod tests { #[test] fn client_extensions_custom_order_rejects_missing_emitted_extension() { - let mut extensions = ClientExtensions::default(); - extensions.extended_master_secret_request = Some(()); - extensions.ec_point_formats = Some(SupportedEcPointFormats::default()); + let mut extensions = ClientExtensions { + extended_master_secret_request: Some(()), + ec_point_formats: Some(SupportedEcPointFormats::default()), + ..Default::default() + }; assert!( extensions @@ -2299,8 +2318,10 @@ mod tests { #[test] fn client_extensions_custom_order_rejects_extra_non_emitted_extension() { - let mut extensions = ClientExtensions::default(); - extensions.extended_master_secret_request = Some(()); + let mut extensions = ClientExtensions { + extended_master_secret_request: Some(()), + ..Default::default() + }; assert!( extensions @@ -2314,8 +2335,10 @@ mod tests { #[test] fn client_extensions_custom_order_rejects_duplicate_extension() { - let mut extensions = ClientExtensions::default(); - extensions.extended_master_secret_request = Some(()); + let mut extensions = ClientExtensions { + extended_master_secret_request: Some(()), + ..Default::default() + }; assert!( extensions @@ -2329,9 +2352,11 @@ mod tests { #[test] fn client_extensions_custom_order_rejects_forced_final_extension() { - let mut extensions = ClientExtensions::default(); - extensions.extended_master_secret_request = Some(()); - extensions.encrypted_client_hello = Some(EncryptedClientHello::Inner); + let mut extensions = ClientExtensions { + extended_master_secret_request: Some(()), + encrypted_client_hello: Some(EncryptedClientHello::Inner), + ..Default::default() + }; assert!( extensions @@ -2345,9 +2370,11 @@ mod tests { #[test] fn client_extensions_custom_order_rejects_contiguous_extension_and_appends_it_once() { - let mut extensions = ClientExtensions::default(); - extensions.extended_master_secret_request = Some(()); - extensions.ec_point_formats = Some(SupportedEcPointFormats::default()); + let mut extensions = ClientExtensions { + extended_master_secret_request: Some(()), + ec_point_formats: Some(SupportedEcPointFormats::default()), + ..Default::default() + }; extensions .contiguous_extensions .push(ExtensionType::ECPointFormats); @@ -2384,15 +2411,15 @@ mod tests { let expected_public = hex::decode("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a") .unwrap(); - let observed_public = StdArc::new(Mutex::new(None)); + let observed_public = Arc::new(Mutex::new(None)); let mut config = ClientConfig::builder_with_provider(aws_lc_x25519_provider().into()) .with_protocol_versions(&[&version::TLS13]) .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_fixed_x25519( - crate::client::FixedX25519KeyShare::new(private_key).with_observer(StdArc::new( + crate::client::FixedX25519KeyShare::new(private_key).with_observer(Arc::new( RecordingX25519KeyShare { public_key: observed_public.clone(), }, @@ -2421,7 +2448,8 @@ mod tests { ); } - #[cfg(feature = "aws_lc_rs")] + // The FIPS provider offers no X25519 key share. + #[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] #[test] fn fixed_x25519_can_be_mixed_with_provider_backed_p256() { let private_key = @@ -2442,7 +2470,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_key_share_plan(key_shares) @@ -2481,7 +2509,7 @@ mod tests { let expected_public = hex::decode("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a") .unwrap(); - let observed_public = StdArc::new(Mutex::new(None)); + let observed_public = Arc::new(Mutex::new(None)); let key_shares = ClientHelloKeySharePlan::try_from(vec![NamedGroup::X25519MLKEM768]).unwrap(); let provider = CryptoProvider { @@ -2493,13 +2521,13 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_key_share_plan(key_shares) .with_fixed_x25519( crate::client::FixedX25519KeyShare::new(private_key).with_observer( - StdArc::new(RecordingX25519KeyShare { + Arc::new(RecordingX25519KeyShare { public_key: observed_public.clone(), }), ), @@ -2542,7 +2570,7 @@ mod tests { let expected_public = hex::decode("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a") .unwrap(); - let observed_public = StdArc::new(Mutex::new(None)); + let observed_public = Arc::new(Mutex::new(None)); let draft_group = NamedGroup::Unknown(0x6399); let key_shares = ClientHelloKeySharePlan::try_from(vec![draft_group]).unwrap(); let provider = CryptoProvider { @@ -2554,13 +2582,13 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_key_share_plan(key_shares) .with_fixed_x25519( crate::client::FixedX25519KeyShare::new(private_key).with_observer( - StdArc::new(RecordingX25519KeyShare { + Arc::new(RecordingX25519KeyShare { public_key: observed_public.clone(), }), ), @@ -2606,16 +2634,16 @@ mod tests { let expected_public = hex::decode("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a") .unwrap(); - let observed_public = StdArc::new(Mutex::new(None)); + let observed_public = Arc::new(Mutex::new(None)); let provider = aws_lc_x25519_provider(); let mut client_config = ClientConfig::builder_with_provider(provider.clone().into()) .with_protocol_versions(&[&version::TLS13]) .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - client_config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + client_config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(ClientHelloPlan::new().with_fixed_x25519( - crate::client::FixedX25519KeyShare::new(private_key).with_observer(StdArc::new( + crate::client::FixedX25519KeyShare::new(private_key).with_observer(Arc::new( RecordingX25519KeyShare { public_key: observed_public.clone(), }, @@ -2660,7 +2688,7 @@ mod tests { let expected_public = hex::decode("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a") .unwrap(); - let observed_public = StdArc::new(Mutex::new(None)); + let observed_public = Arc::new(Mutex::new(None)); let draft_group = NamedGroup::Unknown(0x6399); let key_shares = ClientHelloKeySharePlan::try_from(vec![draft_group]).unwrap(); let provider = CryptoProvider { @@ -2672,13 +2700,13 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - client_config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + client_config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_key_share_plan(key_shares) .with_fixed_x25519( crate::client::FixedX25519KeyShare::new(private_key).with_observer( - StdArc::new(RecordingX25519KeyShare { + Arc::new(RecordingX25519KeyShare { public_key: observed_public.clone(), }), ), @@ -2720,7 +2748,7 @@ mod tests { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some( ClientHelloPlan::new() .with_fixed_x25519(crate::client::FixedX25519KeyShare::new([1u8; 32])), @@ -3093,6 +3121,63 @@ mod tests { conn.process_new_packets().map(|_| ()) } + #[test] + fn test_client_rejects_protected_change_cipher_spec() { + let fake_server_crypto = Arc::new(FakeServerCrypto::new()); + let mut config = ClientConfig::builder_with_provider(x25519_provider().into()) + .with_protocol_versions(&[&version::TLS13]) + .unwrap() + .with_root_certificates(roots()) + .with_no_client_auth(); + config.key_log = fake_server_crypto.clone(); + let mut conn = + ClientConnection::new(config.into(), ServerName::try_from("localhost").unwrap()) + .unwrap(); + let mut sent = Vec::new(); + conn.write_tls(&mut sent).unwrap(); + + let sh = Message { + version: ProtocolVersion::TLSv1_3, + payload: MessagePayload::handshake(HandshakeMessagePayload( + HandshakePayload::ServerHello(ServerHelloPayload { + random: Random([0; 32]), + compression_method: Compression::Null, + cipher_suite: CipherSuite::TLS13_AES_128_GCM_SHA256, + legacy_version: ProtocolVersion::TLSv1_3, + session_id: SessionId::empty(), + extensions: Box::new(ServerExtensions { + key_share: Some(KeyShareEntry { + group: NamedGroup::X25519, + payload: PayloadU16::new(vec![0xaa; 32]), + }), + ..ServerExtensions::default() + }), + }), + )), + }; + conn.read_tls(&mut sh.into_wire_bytes().as_slice()) + .unwrap(); + conn.process_new_packets().unwrap(); + + // A change_cipher_spec protected under the handshake keys is not a + // compatibility-mode CCS, and must not be dropped like one. + let ccs = Message { + version: ProtocolVersion::TLSv1_3, + payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload), + }; + + let mut encrypter = fake_server_crypto.server_handshake_encrypter(); + let enc_ccs = encrypter + .encrypt(PlainMessage::from(ccs).borrow_outbound(), 0) + .unwrap(); + conn.read_tls(&mut enc_ccs.encode().as_slice()) + .unwrap(); + assert_eq!( + conn.process_new_packets().unwrap_err(), + PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into() + ); + } + fn client_config_for_rpk(key_log: Arc) -> ClientConfig { let mut config = ClientConfig::builder_with_provider(x25519_provider().into()) .with_protocol_versions(&[&version::TLS13]) @@ -3423,7 +3508,7 @@ fn retry_test_config(plan: ClientHelloPlan) -> ClientConfig { .unwrap() .with_root_certificates(roots()) .with_no_client_auth(); - config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + config.client_hello_customizer = Some(Arc::new(StaticClientHelloCustomizer { plan: Mutex::new(Some(plan.with_key_share_plan( ClientHelloKeySharePlan::try_from(vec![NamedGroup::X25519]).unwrap(), ))), @@ -3720,7 +3805,7 @@ impl ClientHelloCustomizer for StaticClientHelloCustomizer { #[derive(Debug)] struct RecordingClientHelloCapture { - bytes: StdArc>>, + bytes: Arc>>, } impl crate::client::CapturesClientHello for RecordingClientHelloCapture { @@ -3733,7 +3818,7 @@ impl crate::client::CapturesClientHello for RecordingClientHelloCapture { #[derive(Debug)] struct PatchingClientHelloFinalizer { replacement_session_id: [u8; 32], - called: StdArc, + called: Arc, } impl FinalizesClientHello for PatchingClientHelloFinalizer { @@ -3749,7 +3834,7 @@ impl FinalizesClientHello for PatchingClientHelloFinalizer { #[derive(Debug)] struct FailingClientHelloFinalizer { - called: StdArc, + called: Arc, } impl FinalizesClientHello for FailingClientHelloFinalizer { @@ -3763,7 +3848,7 @@ impl FinalizesClientHello for FailingClientHelloFinalizer { #[derive(Debug)] struct MutatingClientHelloFinalizer { mutation: ClientHelloFinalizerMutation, - called: StdArc, + called: Arc, } #[derive(Debug)] @@ -3787,7 +3872,7 @@ impl FinalizesClientHello for MutatingClientHelloFinalizer { #[cfg(feature = "aws_lc_rs")] #[derive(Debug)] struct RecordingX25519KeyShare { - public_key: StdArc>>, + public_key: Arc>>, } #[cfg(feature = "aws_lc_rs")] diff --git a/rustls/src/client/tls12.rs b/rustls/src/client/tls12.rs index 88bb846ecb1..d1a493ea679 100644 --- a/rustls/src/client/tls12.rs +++ b/rustls/src/client/tls12.rs @@ -92,7 +92,6 @@ mod server_hello { let ClientHelloInput { config, server_name, - plan: _, .. } = self.input; @@ -401,7 +400,7 @@ impl State for ExpectCertificateStatus<'_> { trace!( "Server stapled OCSP response is {:?}", - &server_cert_ocsp_response + server_cert_ocsp_response ); let server_cert = ServerCertDetails::new(self.server_cert_chain, server_cert_ocsp_response); @@ -757,6 +756,15 @@ impl State for ExpectCertificateRequest<'_> { // We ignore certreq.certtypes as a result, since the information it contains // is entirely duplicated in certreq.sigschemes. + // Filter out signature schemes that don't have an associated `SignatureAlgorithm`; + // we use this to select only signature schemes that are allowed on 1.2. + let signature_schemes = certreq + .sigschemes + .iter() + .copied() + .filter(|scheme| scheme.algorithm().is_some()) + .collect::>(); + const NO_CONTEXT: Option> = None; // TLS 1.2 doesn't use a context. let no_compression = None; // or compression let client_auth = ClientAuthDetails::resolve( @@ -764,7 +772,7 @@ impl State for ExpectCertificateRequest<'_> { .client_auth_cert_resolver .as_ref(), Some(&certreq.canames), - &certreq.sigschemes, + &signature_schemes, NO_CONTEXT, no_compression, ); @@ -890,22 +898,30 @@ impl State for ExpectServerDone<'_> { // Build up the contents of the signed message. // It's ClientHello.random || ServerHello.random || ServerKeyExchange.params let sig_verified = { + // Check the signature is compatible with the ciphersuite. + let sig = &st.server_kx.kx_sig; + let Some(sig_alg) = sig.scheme.algorithm() else { + return Err(cx.common.send_fatal_alert( + AlertDescription::IllegalParameter, + PeerMisbehaved::SignedKxWithWrongAlgorithm, + )); + }; + let mut message = Vec::new(); message.extend_from_slice(&st.randoms.client); message.extend_from_slice(&st.randoms.server); message.extend_from_slice(&st.server_kx.kx_params); - // Check the signature is compatible with the ciphersuite. - let sig = &st.server_kx.kx_sig; - if !SupportedCipherSuite::from(suite) - .usable_for_signature_algorithm(sig.scheme.algorithm()) - { + if !SupportedCipherSuite::from(suite).usable_for_signature_algorithm(sig_alg) { warn!( "peer signed kx with wrong algorithm (got {:?} expect {:?})", sig.scheme.algorithm(), suite.sign ); - return Err(PeerMisbehaved::SignedKxWithWrongAlgorithm.into()); + return Err(cx.common.send_fatal_alert( + AlertDescription::IllegalParameter, + PeerMisbehaved::SignedKxWithWrongAlgorithm, + )); } st.config diff --git a/rustls/src/client/tls13.rs b/rustls/src/client/tls13.rs index 46b65b06419..145acbe75eb 100644 --- a/rustls/src/client/tls13.rs +++ b/rustls/src/client/tls13.rs @@ -96,7 +96,7 @@ pub(super) fn handle_server_hello( resuming, mut sent_tls13_fake_ccs, mut hello, - server_name, + mut server_name, .. } = input; @@ -196,6 +196,8 @@ pub(super) fn handle_server_hello( server_hello, server_hello_encoded, suite.common.hash_provider, + &mut server_name, + cx.common, )? { // The server accepted our ECH offer, so complete the inner transcript with the // server hello message, and switch the relevant state to the copies for the @@ -214,12 +216,6 @@ pub(super) fn handle_server_hello( }; } - // Remember what KX group the server liked for next time. - config - .resumption - .store - .set_kx_hint(server_name.clone(), their_key_share.group); - // If we change keying when a subsequent handshake message is being joined, // the two halves will have different record layer protections. Disallow this. cx.common.check_aligned_handshake()?; @@ -244,6 +240,7 @@ pub(super) fn handle_server_hello( suite, transcript, key_schedule, + kx_group: their_key_share.group, hello, })) } @@ -369,21 +366,20 @@ pub(super) fn initial_key_shares( return planned_key_shares(config, kx_state, plan, key_share_plan.as_slice()); } - let planned_group = match plan.and_then(|plan| plan.supported_groups.as_ref()) { - Some(groups) => { - let mut selected = None; - for group_name in groups.as_slice() { - let Some(group) = config.find_kx_group(*group_name, ProtocolVersion::TLSv1_3) - else { - return Err(Error::General( + // A plan's first supported group is the one whose key share goes out. + let planned_group = match plan + .and_then(|plan| plan.supported_groups.as_ref()) + .and_then(|groups| groups.as_slice().first()) + { + Some(group_name) => Some( + config + .find_kx_group(*group_name, ProtocolVersion::TLSv1_3) + .ok_or_else(|| { + Error::General( "ClientHello supported group is not supported by this config".into(), - )); - }; - selected = Some(group); - break; - } - selected - } + ) + })?, + ), None => None, }; @@ -748,6 +744,7 @@ struct ExpectEncryptedExtensions { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, hello: ClientHelloDetails, } @@ -859,6 +856,7 @@ impl State for ExpectEncryptedExtensions { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: None, cert_verified, sig_verified, @@ -881,6 +879,7 @@ impl State for ExpectEncryptedExtensions { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, ech_retry_configs, }) } else { @@ -891,6 +890,7 @@ impl State for ExpectEncryptedExtensions { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, ech_retry_configs, }) }) @@ -910,6 +910,7 @@ struct ExpectCertificateOrCompressedCertificateOrCertReq { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, ech_retry_configs: Option>, } @@ -933,6 +934,7 @@ impl State for ExpectCertificateOrCompressedCertificateOrC suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: None, message_already_in_transcript: false, ech_retry_configs: self.ech_retry_configs, @@ -948,6 +950,7 @@ impl State for ExpectCertificateOrCompressedCertificateOrC suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: None, ech_retry_configs: self.ech_retry_configs, }) @@ -962,6 +965,7 @@ impl State for ExpectCertificateOrCompressedCertificateOrC suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, offered_cert_compression: true, ech_retry_configs: self.ech_retry_configs, }) @@ -990,6 +994,7 @@ struct ExpectCertificateOrCompressedCertificate { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, client_auth: Option, ech_retry_configs: Option>, } @@ -1014,6 +1019,7 @@ impl State for ExpectCertificateOrCompressedCertificate { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: self.client_auth, message_already_in_transcript: false, ech_retry_configs: self.ech_retry_configs, @@ -1029,6 +1035,7 @@ impl State for ExpectCertificateOrCompressedCertificate { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: self.client_auth, ech_retry_configs: self.ech_retry_configs, }) @@ -1056,6 +1063,7 @@ struct ExpectCertificateOrCertReq { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, ech_retry_configs: Option>, } @@ -1079,6 +1087,7 @@ impl State for ExpectCertificateOrCertReq { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: None, message_already_in_transcript: false, ech_retry_configs: self.ech_retry_configs, @@ -1094,6 +1103,7 @@ impl State for ExpectCertificateOrCertReq { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, offered_cert_compression: false, ech_retry_configs: self.ech_retry_configs, }) @@ -1124,6 +1134,7 @@ struct ExpectCertificateRequest { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, offered_cert_compression: bool, ech_retry_configs: Option>, } @@ -1207,6 +1218,7 @@ impl State for ExpectCertificateRequest { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: Some(client_auth), ech_retry_configs: self.ech_retry_configs, }) @@ -1218,6 +1230,7 @@ impl State for ExpectCertificateRequest { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: Some(client_auth), message_already_in_transcript: false, ech_retry_configs: self.ech_retry_configs, @@ -1237,6 +1250,7 @@ struct ExpectCompressedCertificate { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, client_auth: Option, ech_retry_configs: Option>, } @@ -1321,6 +1335,7 @@ impl State for ExpectCompressedCertificate { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: self.client_auth, message_already_in_transcript: true, ech_retry_configs: self.ech_retry_configs, @@ -1340,6 +1355,7 @@ struct ExpectCertificate { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, client_auth: Option, message_already_in_transcript: bool, ech_retry_configs: Option>, @@ -1386,6 +1402,7 @@ impl State for ExpectCertificate { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, server_cert, client_auth: self.client_auth, ech_retry_configs: self.ech_retry_configs, @@ -1405,6 +1422,7 @@ struct ExpectCertificateVerify<'a> { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, server_cert: ServerCertDetails<'a>, client_auth: Option, ech_retry_configs: Option>, @@ -1476,6 +1494,7 @@ impl State for ExpectCertificateVerify<'_> { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, client_auth: self.client_auth, cert_verified, sig_verified, @@ -1491,6 +1510,7 @@ impl State for ExpectCertificateVerify<'_> { suite: self.suite, transcript: self.transcript, key_schedule: self.key_schedule, + kx_group: self.kx_group, server_cert: self.server_cert.into_owned(), client_auth: self.client_auth, ech_retry_configs: self.ech_retry_configs, @@ -1583,6 +1603,7 @@ struct ExpectFinished { suite: &'static Tls13CipherSuite, transcript: HandshakeHash, key_schedule: KeyScheduleHandshake, + kx_group: NamedGroup, client_auth: Option, cert_verified: verify::ServerCertVerified, sig_verified: verify::HandshakeSignatureValid, @@ -1683,6 +1704,12 @@ impl State for ExpectFinished { emit_finished_tls13(&mut flight, &verify_data); flight.finish(cx.common); + // Remember what KX group the server liked for next time. + st.config + .resumption + .store + .set_kx_hint(st.server_name.clone(), st.kx_group); + /* We're now sure this server supports TLS1.3. But if we run out of TLS1.3 tickets * when connecting to it again, we definitely don't want to attempt a TLS1.2 resumption. */ st.config @@ -1694,16 +1721,19 @@ impl State for ExpectFinished { cx.common.check_aligned_handshake()?; let (key_schedule, resumption) = key_schedule_pre_finished.into_traffic(cx.common, st.transcript.current_hash()); - cx.common - .start_traffic(&mut cx.sendable_plaintext); // Now that we've reached the end of the normal handshake we must enforce ECH acceptance by // sending an alert and returning an error (potentially with retry configs) if the server - // did not accept our ECH offer. + // did not accept our ECH offer. This must happen before the connection is made available + // for application data, since the server has only been authenticated for the ECH config's + // `public_name`. if cx.data.ech_status == EchStatus::Rejected { return Err(ech::fatal_alert_required(st.ech_retry_configs, cx.common)); } + cx.common + .start_traffic(&mut cx.sendable_plaintext); + let st = ExpectTraffic { config: st.config.clone(), session_storage: st.config.resumption.store.clone(), diff --git a/rustls/src/common_state.rs b/rustls/src/common_state.rs index 77ba0bbf57e..9a6e6b55f6a 100644 --- a/rustls/src/common_state.rs +++ b/rustls/src/common_state.rs @@ -233,6 +233,33 @@ impl CommonState { } } + /// Ask for a TLS 1.3 key update before encrypting `payload`, if one of its records would + /// take the last sequence number allowed by the current keys. + /// + /// The key update then takes that sequence number instead. + pub(crate) fn request_key_update_for(&mut self, payload: OutboundChunks<'_>) { + let records = self + .message_fragmenter + .fragment_payload( + ContentType::ApplicationData, + ProtocolVersion::TLSv1_2, + payload, + ) + .len(); + + if records > 0 + && self.negotiated_version == Some(ProtocolVersion::TLSv1_3) + && self.record_layer.write_seq() > 0 + && self + .record_layer + .pre_encrypt_action(records as u64) + != PreEncryptAction::Nothing + { + // driven by caller, as we don't have the `State` here + self.refresh_traffic_keys_pending = true; + } + } + pub(crate) fn write_plaintext( &mut self, payload: OutboundChunks<'_>, @@ -317,7 +344,17 @@ impl CommonState { } /// Like send_msg_encrypt, but operate on an appdata directly. - fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize { + /// + /// If `stop_for_key_update` is true, this stops before a TLS 1.3 record that would take + /// the last sequence number allowed by the current keys, so that the caller can first send + /// a `key_update` request with that sequence number. In that case, the return value is the + /// number of bytes sent so far. + fn send_appdata_encrypt( + &mut self, + payload: OutboundChunks<'_>, + limit: Limit, + stop_for_key_update: bool, + ) -> usize { // Here, the limit on sendable_tls applies to encrypted data, // but we're respecting it for plaintext data -- so we'll // be out by whatever the cipher+record overhead is. That's a @@ -337,7 +374,30 @@ impl CommonState { ProtocolVersion::TLSv1_2, payload.split_at(len).0, ); + + // Check the record limit for the last fragment before encrypting any of them, so + // that a write crossing the limit is not sent in part. + if let Some(last) = (iter.len() as u64).checked_sub(1) { + if !self.check_pre_encrypt_action(last) { + return len; + } + } + + let mut sent = 0; for m in iter { + // The key update takes the last sequence number allowed by the current keys, + // unless they have not been used yet (as updating them would not help then). + if stop_for_key_update + && self.negotiated_version == Some(ProtocolVersion::TLSv1_3) + && self.record_layer.write_seq() > 0 + && self.record_layer.pre_encrypt_action(1) != PreEncryptAction::Nothing + { + // driven by caller, as we don't have the `State` here + self.refresh_traffic_keys_pending = true; + return sent; + } + + sent += m.payload.len(); self.send_single_fragment(m); } @@ -352,42 +412,53 @@ impl CommonState { return; } + if !self.check_pre_encrypt_action(0) { + return; + } + + let em = self.record_layer.encrypt_outgoing(m); + self.queue_tls_message(em); + } + + /// Take the remedial action needed before encrypting the record `add` records after the next. + /// + /// Returns `false` if that record must not be encrypted. + fn check_pre_encrypt_action(&mut self, add: u64) -> bool { match self .record_layer - .next_pre_encrypt_action() + .pre_encrypt_action(add) { - PreEncryptAction::Nothing => {} + PreEncryptAction::Nothing => true, // Close connection once we start to run out of // sequence space. - PreEncryptAction::RefreshOrClose => { - match self.negotiated_version { - Some(ProtocolVersion::TLSv1_3) => { - // driven by caller, as we don't have the `State` here - self.refresh_traffic_keys_pending = true; - } - _ => { - error!( - "traffic keys exhausted, closing connection to prevent security failure" - ); - self.send_close_notify(); - return; - } + PreEncryptAction::RefreshOrClose => match self.negotiated_version { + Some(ProtocolVersion::TLSv1_3) => { + // driven by caller, as we don't have the `State` here + self.refresh_traffic_keys_pending = true; + true } - } + _ => { + error!( + "traffic keys exhausted, closing connection to prevent security failure" + ); + self.send_close_notify(); + false + } + }, // Refuse to wrap counter at all costs. This // is basically untestable unfortunately. - PreEncryptAction::Refuse => { - return; - } - }; - - let em = self.record_layer.encrypt_outgoing(m); - self.queue_tls_message(em); + PreEncryptAction::Refuse => false, + } } - fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize { + fn send_plain_non_buffering( + &mut self, + payload: OutboundChunks<'_>, + limit: Limit, + stop_for_key_update: bool, + ) -> usize { debug_assert!(self.may_send_application_data); debug_assert!(self.record_layer.is_encrypting()); @@ -396,7 +467,7 @@ impl CommonState { return 0; } - self.send_appdata_encrypt(payload, limit) + self.send_appdata_encrypt(payload, limit, stop_for_key_update) } /// Mark the connection as ready to send application data. @@ -428,7 +499,7 @@ impl CommonState { } while let Some(buf) = sendable_plaintext.pop() { - self.send_plain_non_buffering(buf.as_slice().into(), Limit::No); + self.send_plain_non_buffering(buf.as_slice().into(), Limit::No, false); } } @@ -732,8 +803,8 @@ impl CommonState { /// Send plaintext application data, fragmenting and /// encrypting it as it goes out. /// - /// If internal buffers are too small, this function will not accept - /// all the data. + /// If internal buffers are too small, or if the traffic keys must be + /// updated first, this function will not accept all the data. pub(crate) fn buffer_plaintext( &mut self, payload: OutboundChunks<'_>, @@ -752,7 +823,7 @@ impl CommonState { return 0; } - self.send_appdata_encrypt(data.into(), Limit::Yes) + self.send_appdata_encrypt(data.into(), Limit::Yes, false) } /// Encrypt and send some plaintext `data`. `limit` controls @@ -776,7 +847,7 @@ impl CommonState { return len; } - self.send_plain_non_buffering(payload, limit) + self.send_plain_non_buffering(payload, limit, true) } } @@ -910,6 +981,15 @@ pub(crate) enum Protocol { Quic, } +impl Protocol { + pub(crate) fn supports_version(&self, version: ProtocolVersion) -> bool { + match self { + Self::Quic => version == ProtocolVersion::TLSv1_3, + Self::Tcp => true, + } + } +} + enum Limit { #[cfg(feature = "std")] Yes, diff --git a/rustls/src/compress.rs b/rustls/src/compress.rs index 14df129032e..89ed1858467 100644 --- a/rustls/src/compress.rs +++ b/rustls/src/compress.rs @@ -126,7 +126,7 @@ pub struct CompressionFailed; #[cfg(feature = "zlib")] mod feat_zlib_rs { use zlib_rs::{ - DeflateConfig, InflateConfig, ReturnCode, compress_bound, compress_slice, decompress_slice, + DeflateConfig, Inflate, InflateFlush, ReturnCode, Status, compress_bound, compress_slice, }; use super::*; @@ -139,10 +139,17 @@ mod feat_zlib_rs { impl CertDecompressor for ZlibRsDecompressor { fn decompress(&self, input: &[u8], output: &mut [u8]) -> Result<(), DecompressionFailed> { - let output_len = output.len(); - match decompress_slice(output, input, InflateConfig::default()) { - (output_filled, ReturnCode::Ok) if output_filled.len() == output_len => Ok(()), - (_, _) => Err(DecompressionFailed), + // `Inflate` rather than `decompress_slice()`, because the latter does not + // report how much of `input` the stream used: see `total_in()` below. + let mut state = Inflate::new(true, ZLIB_WINDOW_BITS); + match state.decompress(input, output, InflateFlush::Finish) { + Ok(Status::StreamEnd) + if state.total_in() == input.len() as u64 + && state.total_out() == output.len() as u64 => + { + Ok(()) + } + _ => Err(DecompressionFailed), } } @@ -182,15 +189,21 @@ mod feat_zlib_rs { CertificateCompressionAlgorithm::Zlib } } + + /// Largest LZ77 window, matching `InflateConfig::default()`. + const ZLIB_WINDOW_BITS: u8 = 15; } #[cfg(feature = "zlib")] pub use feat_zlib_rs::{ZLIB_COMPRESSOR, ZLIB_DECOMPRESSOR}; +#[allow(clippy::std_instead_of_core)] // awaits core::io::Cursor (1.97) in crate MSRV #[cfg(feature = "brotli")] mod feat_brotli { use std::io::{Cursor, Write}; + use brotli_decompressor::{BrotliDecompressStream, BrotliResult, BrotliState, StandardAlloc}; + use super::*; /// A certificate decompressor for the brotli algorithm using the `brotli` crate. @@ -201,17 +214,27 @@ mod feat_brotli { impl CertDecompressor for BrotliDecompressor { fn decompress(&self, input: &[u8], output: &mut [u8]) -> Result<(), DecompressionFailed> { - let mut in_cursor = Cursor::new(input); - let mut out_cursor = Cursor::new(output); - - brotli::BrotliDecompress(&mut in_cursor, &mut out_cursor) - .map_err(|_| DecompressionFailed)?; - - if out_cursor.position() as usize != out_cursor.into_inner().len() { - return Err(DecompressionFailed); + let mut state = BrotliState::new_strict( + StandardAlloc::default(), + StandardAlloc::default(), + StandardAlloc::default(), + ); + let (mut available_in, mut input_offset) = (input.len(), 0); + let (mut available_out, mut output_offset, mut total_out) = (output.len(), 0, 0); + + match BrotliDecompressStream( + &mut available_in, + &mut input_offset, + input, + &mut available_out, + &mut output_offset, + output, + &mut total_out, + &mut state, + ) { + BrotliResult::ResultSuccess if available_out == 0 && available_in == 0 => Ok(()), + _ => Err(DecompressionFailed), } - - Ok(()) } fn algorithm(&self) -> CertificateCompressionAlgorithm { @@ -374,7 +397,7 @@ impl CompressionCache { compressed: CompressedCertificatePayload { alg: algorithm, uncompressed_len, - compressed: PayloadU24(Payload::new(compressed)), + compressed: PayloadU24::from(Payload::new(compressed)), }, }); @@ -407,7 +430,7 @@ impl CompressionCache { compressed: CompressedCertificatePayload { alg: algorithm, uncompressed_len, - compressed: PayloadU24(Payload::new(compressed)), + compressed: PayloadU24::from(Payload::new(compressed)), }, })) } @@ -463,12 +486,23 @@ mod tests { test_compressor(BROTLI_COMPRESSOR, BROTLI_DECOMPRESSOR); } + #[test] + #[cfg(feature = "brotli")] + fn test_brotli_rejects_large_window() { + let large_window_empty = [0x11, 0xd0]; + brotli::BrotliDecompress(&mut &large_window_empty[..], &mut Vec::new()).unwrap(); + BROTLI_DECOMPRESSOR + .decompress(&large_window_empty, &mut []) + .unwrap_err(); + } + fn test_compressor(comp: &dyn CertCompressor, decomp: &dyn CertDecompressor) { assert_eq!(comp.algorithm(), decomp.algorithm()); for sz in [16, 64, 512, 2048, 8192, 16384] { test_trivial_pairwise(comp, decomp, sz); } test_decompress_wrong_len(comp, decomp); + test_decompress_trailing_data(comp, decomp); test_decompress_garbage(decomp); } @@ -518,6 +552,19 @@ mod tests { .unwrap_err(); } + fn test_decompress_trailing_data(comp: &dyn CertCompressor, decomp: &dyn CertDecompressor) { + let original = vec![0u8; 2048]; + let mut compressed = comp + .compress(original.clone(), CompressionLevel::Interactive) + .unwrap(); + compressed.extend_from_slice(b"trailing data"); + + let mut recovered = vec![0xffu8; original.len()]; + decomp + .decompress(&compressed, &mut recovered) + .unwrap_err(); + } + fn test_decompress_garbage(decomp: &dyn CertDecompressor) { let junk = [0u8; 1024]; let mut recovered = vec![0u8; 512]; diff --git a/rustls/src/conn.rs b/rustls/src/conn.rs index 344eb22bcbc..9bcaf09d9b5 100644 --- a/rustls/src/conn.rs +++ b/rustls/src/conn.rs @@ -262,7 +262,7 @@ mod connection { /// You may learn the number of bytes available at any time by inspecting /// the return of [`Connection::process_new_packets`]. #[cfg(read_buf)] - fn read_buf(&mut self, mut cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> { + fn read_buf(&mut self, mut cursor: core::io::BorrowedCursor<'_, u8>) -> io::Result<()> { let before = cursor.written(); self.received_plaintext .read_buf(cursor.reborrow())?; @@ -327,6 +327,10 @@ https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof" /// TLS handshake completes, and sends it as soon /// as it can. See [`ConnectionCommon::set_buffer_limit`] to control /// the size of this buffer. + /// + /// If the connection previously encountered a fatal error (for example, while + /// processing received data in [`Connection::process_new_packets`]), this returns + /// that error, even if `buf` is empty. fn write(&mut self, buf: &[u8]) -> io::Result { self.sink.write(buf) } @@ -335,6 +339,8 @@ https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof" self.sink.write_vectored(bufs) } + /// This does not do any I/O, but returns the fatal error the connection previously + /// encountered, if any. fn flush(&mut self) -> io::Result<()> { self.sink.flush() } @@ -351,17 +357,40 @@ https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof" fn flush(&mut self) -> io::Result<()>; } + impl ConnectionCommon { + /// Return the fatal error this connection previously encountered, if any. + fn check_error(&self) -> io::Result<()> { + match &self.core.state { + Ok(_) => Ok(()), + Err(err) => Err(io::Error::new(io::ErrorKind::InvalidData, err.clone())), + } + } + + /// Send or buffer as much of `payload` as possible. + /// + /// This updates the TLS 1.3 traffic keys as needed between records. + fn send_plaintext(&mut self, payload: OutboundChunks<'_>) -> usize { + let mut len = 0; + loop { + len += self + .core + .common_state + .buffer_plaintext(payload.split_at(len).1, &mut self.sendable_plaintext); + if !self.core.maybe_refresh_traffic_keys() || len == payload.len() { + return len; + } + } + } + } + impl PlaintextSink for ConnectionCommon { fn write(&mut self, buf: &[u8]) -> io::Result { - let len = self - .core - .common_state - .buffer_plaintext(buf.into(), &mut self.sendable_plaintext); - self.core.maybe_refresh_traffic_keys(); - Ok(len) + self.check_error()?; + Ok(self.send_plaintext(buf.into())) } fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result { + self.check_error()?; let payload_owner: Vec<&[u8]>; let payload = match bufs.len() { 0 => return Ok(0), @@ -375,16 +404,11 @@ https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof" OutboundChunks::new(&payload_owner) } }; - let len = self - .core - .common_state - .buffer_plaintext(payload, &mut self.sendable_plaintext); - self.core.maybe_refresh_traffic_keys(); - Ok(len) + Ok(self.send_plaintext(payload)) } fn flush(&mut self) -> io::Result<()> { - Ok(()) + self.check_error() } } } @@ -962,13 +986,16 @@ impl ConnectionCore { buffer: &'b mut [u8], buffer_progress: &mut BufferProgress, ) -> Option> { - self.hs_deframer + let message = self + .hs_deframer .iter(buffer) .next() .map(|(message, discard)| { buffer_progress.add_discard(discard); message - }) + }); + self.common_state.aligned_handshake = self.hs_deframer.is_aligned(); + message } fn process_more_input<'b>( @@ -1132,6 +1159,9 @@ impl ConnectionCore { self.common_state .send_fatal_alert(AlertDescription::BadRecordMac, error) } + Error::PeerMisbehaved(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec) => self + .common_state + .send_fatal_alert(AlertDescription::UnexpectedMessage, error), error => error, } @@ -1253,14 +1283,14 @@ impl ConnectionCore { } /// Trigger a `refresh_traffic_keys` if required by `CommonState`. - fn maybe_refresh_traffic_keys(&mut self) { - if mem::take( + /// + /// Returns whether the traffic keys were updated. + fn maybe_refresh_traffic_keys(&mut self) -> bool { + mem::take( &mut self .common_state .refresh_traffic_keys_pending, - ) { - let _ = self.refresh_traffic_keys(); - } + ) && self.refresh_traffic_keys().is_ok() } fn refresh_traffic_keys(&mut self) -> Result<(), Error> { diff --git a/rustls/src/conn/unbuffered.rs b/rustls/src/conn/unbuffered.rs index 77927b5587f..53bf442794b 100644 --- a/rustls/src/conn/unbuffered.rs +++ b/rustls/src/conn/unbuffered.rs @@ -447,6 +447,10 @@ impl WriteTraffic<'_, Data> { application_data: &[u8], outgoing_tls: &mut [u8], ) -> Result { + self.conn + .core + .common_state + .request_key_update_for(application_data.into()); self.conn .core .maybe_refresh_traffic_keys(); diff --git a/rustls/src/crypto/aws_lc_rs/hpke.rs b/rustls/src/crypto/aws_lc_rs/hpke.rs index 2e5c3a5ece6..dcea100a3d5 100644 --- a/rustls/src/crypto/aws_lc_rs/hpke.rs +++ b/rustls/src/crypto/aws_lc_rs/hpke.rs @@ -2,9 +2,7 @@ use alloc::boxed::Box; use alloc::vec::Vec; use core::fmt::{self, Debug, Formatter}; -use aws_lc_rs::aead::{ - self, Aad, BoundKey, NONCE_LEN, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, -}; +use aws_lc_rs::aead::{self, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey}; use aws_lc_rs::agreement; use aws_lc_rs::cipher::{AES_128_KEY_LEN, AES_256_KEY_LEN}; use aws_lc_rs::digest::{SHA256_OUTPUT_LEN, SHA384_OUTPUT_LEN, SHA512_OUTPUT_LEN}; @@ -441,11 +439,16 @@ impl HpkeSealer for Sealer HpkeOpener for Opener KeySchedule { /// See [RFC 9180 §5.2 "Encryption and Decryption"][0]. /// /// [0]: https://www.rfc-editor.org/rfc/rfc9180.html#section-5.2 - fn compute_nonce(&self) -> [u8; NONCE_LEN] { + fn compute_nonce(&self) -> Nonce { // def Context.ComputeNonce(seq): // seq_bytes = I2OSP(seq, Nn) // return xor(self.base_nonce, seq_bytes) @@ -755,7 +765,7 @@ impl KeySchedule { *n ^= b; } - nonce + Nonce::assume_unique_for_key(nonce) } /// See [RFC 9180 §5.2 "Encryption and Decryption"][0]. @@ -782,14 +792,6 @@ impl KeySchedule { } } -impl NonceSequence for &mut KeySchedule { - fn advance(&mut self) -> Result { - let nonce = self.compute_nonce(); - self.increment_seq_num()?; - Nonce::try_assume_unique_for_key(&nonce) - } -} - /// See [RFC 9180 §4 "Cryptographic Dependencies"][0]. /// /// [0]: https://www.rfc-editor.org/rfc/rfc9180.html#section-4 @@ -1031,6 +1033,29 @@ mod tests { assert_eq!(suite.fips(), *expected); } } + + #[test] + fn failed_open_does_not_consume_sequence() { + for suite in ALL_SUPPORTED_SUITES { + let (pk, sk) = suite.generate_key_pair().unwrap(); + let (enc, mut sealer) = suite + .setup_sealer(b"example", &pk) + .unwrap(); + let ct0 = sealer + .seal(b"aad", b"message 0") + .unwrap(); + let ct1 = sealer + .seal(b"aad", b"message 1") + .unwrap(); + + let mut opener = suite + .setup_opener(&enc, b"example", &sk) + .unwrap(); + assert!(opener.open(b"wrong aad", &ct0).is_err()); + assert_eq!(opener.open(b"aad", &ct0).unwrap(), b"message 0"); + assert_eq!(opener.open(b"aad", &ct1).unwrap(), b"message 1"); + } + } } #[cfg(test)] diff --git a/rustls/src/crypto/aws_lc_rs/mod.rs b/rustls/src/crypto/aws_lc_rs/mod.rs index e6fc1696ff4..3fdc2e3d76e 100644 --- a/rustls/src/crypto/aws_lc_rs/mod.rs +++ b/rustls/src/crypto/aws_lc_rs/mod.rs @@ -7,6 +7,7 @@ use alloc::vec::Vec; pub(crate) use aws_lc_rs as ring_like; use pki_types::PrivateKeyDer; use webpki::aws_lc_rs as webpki_algs; +use zeroize::Zeroizing; use crate::crypto::{CryptoProvider, KeyProvider, SecureRandom, SupportedKxGroup}; use crate::enums::SignatureScheme; @@ -87,7 +88,7 @@ impl KeyProvider for AwsLcRs { &self, key_der: PrivateKeyDer<'static>, ) -> Result, Error> { - sign::any_supported_type(&key_der) + sign::any_supported_type(&Zeroizing::new(key_der)) } fn fips(&self) -> bool { @@ -177,6 +178,9 @@ static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms webpki_algs::RSA_PKCS1_2048_8192_SHA256_ABSENT_PARAMS, webpki_algs::RSA_PKCS1_2048_8192_SHA384_ABSENT_PARAMS, webpki_algs::RSA_PKCS1_2048_8192_SHA512_ABSENT_PARAMS, + webpki_algs::ML_DSA_44, + webpki_algs::ML_DSA_65, + webpki_algs::ML_DSA_87, ], mapping: &[ // Note: for TLS1.2 the curve is not fixed by SignatureScheme. For TLS1.3 it is. @@ -229,6 +233,9 @@ static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms SignatureScheme::RSA_PKCS1_SHA256, &[webpki_algs::RSA_PKCS1_2048_8192_SHA256], ), + (SignatureScheme::ML_DSA_44, &[webpki_algs::ML_DSA_44]), + (SignatureScheme::ML_DSA_65, &[webpki_algs::ML_DSA_65]), + (SignatureScheme::ML_DSA_87, &[webpki_algs::ML_DSA_87]), ], }; diff --git a/rustls/src/crypto/aws_lc_rs/sign.rs b/rustls/src/crypto/aws_lc_rs/sign.rs index 0c874abf922..eec8952b6a0 100644 --- a/rustls/src/crypto/aws_lc_rs/sign.rs +++ b/rustls/src/crypto/aws_lc_rs/sign.rs @@ -4,9 +4,12 @@ use alloc::boxed::Box; use alloc::string::ToString; use alloc::vec::Vec; use alloc::{format, vec}; +use aws_lc_rs::signature::{PqdsaKeyPair, PqdsaSigningAlgorithm}; use core::fmt::{self, Debug, Formatter}; -use pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer, SubjectPublicKeyInfoDer, alg_id}; +use pki_types::{ + AlgorithmIdentifier, PrivateKeyDer, PrivatePkcs8KeyDer, SubjectPublicKeyInfoDer, alg_id, +}; use super::ring_like::rand::SystemRandom; use super::ring_like::signature::{self, EcdsaKeyPair, Ed25519KeyPair, KeyPair, RsaKeyPair}; @@ -30,6 +33,10 @@ pub fn any_supported_type(der: &PrivateKeyDer<'_>) -> Result if let Ok(eddsa) = any_eddsa_type(pkcs8) { return Ok(eddsa); } + + if let Ok(pqdsa) = PqdsaSigningKey::from_pkcs8(pkcs8) { + return Ok(Arc::new(pqdsa)); + } } Err(Error::General( @@ -271,7 +278,9 @@ impl SigningKey for EcdsaSigningKey { } fn algorithm(&self) -> SignatureAlgorithm { - self.scheme.algorithm() + self.scheme + .algorithm() + .unwrap_or(SignatureAlgorithm::Unknown(0)) } } @@ -310,6 +319,134 @@ impl Debug for EcdsaSigner { } } +pub(crate) struct PqdsaSigningKey { + kind: PqdsaKeyKind, + inner: Arc, +} + +impl PqdsaSigningKey { + pub(crate) fn from_pkcs8(pkcs8: &PrivatePkcs8KeyDer<'_>) -> Result { + for kind in PqdsaKeyKind::iter() { + let Ok(key_pair) = PqdsaKeyPair::from_pkcs8(kind.to_alg(), pkcs8.secret_pkcs8_der()) + else { + continue; + }; + + return Ok(Self { + kind, + inner: Arc::new(key_pair), + }); + } + + Err(Error::General( + "failed to parse private key as ML-DSA".into(), + )) + } +} + +impl SigningKey for PqdsaSigningKey { + fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option> { + if !offered.contains(&self.kind.scheme()) { + return None; + } + + Some(Box::new(PqdsaSigner { + key: self.inner.clone(), + kind: self.kind, + })) + } + + fn public_key(&self) -> Option> { + Some(public_key_to_spki( + &self.kind.alg_id(), + self.inner.public_key(), + )) + } + + fn algorithm(&self) -> SignatureAlgorithm { + SignatureAlgorithm::Unknown(0) + } +} + +impl Debug for PqdsaSigningKey { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("PqdsaSigningKey") + .field("scheme", &self.kind.scheme()) + .finish_non_exhaustive() + } +} + +struct PqdsaSigner { + key: Arc, + kind: PqdsaKeyKind, +} + +impl Signer for PqdsaSigner { + fn sign(&self, message: &[u8]) -> Result, Error> { + let expected_sig_len = self.key.algorithm().signature_len(); + let mut sig = vec![0; expected_sig_len]; + let actual_sig_len = self + .key + .sign(message, &mut sig) + .map_err(|_| Error::General("signing failed".into()))?; + + if actual_sig_len != expected_sig_len { + return Err(Error::General("unexpected signature length".into())); + } + + Ok(sig) + } + + fn scheme(&self) -> SignatureScheme { + self.kind.scheme() + } +} + +impl Debug for PqdsaSigner { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("PqdsaSigner") + .field("scheme", &self.kind.scheme()) + .finish_non_exhaustive() + } +} + +#[derive(Clone, Copy)] +enum PqdsaKeyKind { + MlDsa44, + MlDsa65, + MlDsa87, +} + +impl PqdsaKeyKind { + fn iter() -> impl Iterator { + [Self::MlDsa44, Self::MlDsa65, Self::MlDsa87].into_iter() + } + + fn to_alg(self) -> &'static PqdsaSigningAlgorithm { + match self { + Self::MlDsa44 => &signature::ML_DSA_44_SIGNING, + Self::MlDsa65 => &signature::ML_DSA_65_SIGNING, + Self::MlDsa87 => &signature::ML_DSA_87_SIGNING, + } + } + + fn scheme(&self) -> SignatureScheme { + match self { + Self::MlDsa44 => SignatureScheme::ML_DSA_44, + Self::MlDsa65 => SignatureScheme::ML_DSA_65, + Self::MlDsa87 => SignatureScheme::ML_DSA_87, + } + } + + fn alg_id(&self) -> AlgorithmIdentifier { + match self { + Self::MlDsa44 => alg_id::ML_DSA_44, + Self::MlDsa65 => alg_id::ML_DSA_65, + Self::MlDsa87 => alg_id::ML_DSA_87, + } + } +} + /// A SigningKey that uses exactly one TLS-level SignatureScheme /// and one ring-level signature::SigningAlgorithm. /// @@ -359,7 +496,9 @@ impl SigningKey for Ed25519SigningKey { } fn algorithm(&self) -> SignatureAlgorithm { - self.scheme.algorithm() + self.scheme + .algorithm() + .unwrap_or(SignatureAlgorithm::Unknown(0)) } } @@ -401,6 +540,7 @@ mod tests { use pki_types::{PrivatePkcs1KeyDer, PrivateSec1KeyDer}; use super::*; + use crate::pki_types::PrivateKeyDer; #[test] fn can_load_ecdsa_nistp256_pkcs8() { diff --git a/rustls/src/crypto/aws_lc_rs/ticketer.rs b/rustls/src/crypto/aws_lc_rs/ticketer.rs index 44c7c21b473..d24147d5f55 100644 --- a/rustls/src/crypto/aws_lc_rs/ticketer.rs +++ b/rustls/src/crypto/aws_lc_rs/ticketer.rs @@ -185,7 +185,7 @@ impl ProducesTickets for Rfc5077Ticketer { .algorithm() .digest_algorithm() .output_len(); - let (enc_state, mac) = try_split_at(ciphertext, ciphertext.len() - tag_len)?; + let (enc_state, mac) = try_split_at(ciphertext, ciphertext.len().checked_sub(tag_len)?)?; // Reconstitute the HMAC data to verify the tag. let mut hmac_data = @@ -378,6 +378,20 @@ mod tests { assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3"); } + #[test] + fn refuses_decrypt_truncated_ciphertext() { + let t = make_ticket_generator().unwrap(); + let cipher = t.encrypt(b"hello world").unwrap(); + assert_eq!(t.decrypt(&cipher), Some(b"hello world".to_vec())); + + // a truncation is rejected at any length; lengths that leave fewer + // bytes than the trailing tag after the key_name and iv prefix + // exercise the final split. + for len in 0..cipher.len() { + assert_eq!(t.decrypt(&cipher[..len]), None); + } + } + #[test] fn rfc5077ticketer_is_debug_and_producestickets() { use alloc::format; diff --git a/rustls/src/crypto/aws_lc_rs/x25519.rs b/rustls/src/crypto/aws_lc_rs/x25519.rs index 66d5a0de761..1e1ba9db2d7 100644 --- a/rustls/src/crypto/aws_lc_rs/x25519.rs +++ b/rustls/src/crypto/aws_lc_rs/x25519.rs @@ -36,7 +36,7 @@ impl ActiveKeyExchange for FixedX25519 { } let peer_key = agreement::UnparsedPublicKey::new(&agreement::X25519, peer_pub_key); - agreement::agree(&self.private_key, &peer_key, (), |secret| { + agreement::agree(&self.private_key, peer_key, (), |secret| { Ok(SharedSecret::from(secret)) }) .map_err(|_| PeerMisbehaved::InvalidKeyShare.into()) diff --git a/rustls/src/crypto/ring/mod.rs b/rustls/src/crypto/ring/mod.rs index 3ce99b15297..50f75dabcb5 100644 --- a/rustls/src/crypto/ring/mod.rs +++ b/rustls/src/crypto/ring/mod.rs @@ -1,6 +1,7 @@ use pki_types::PrivateKeyDer; pub(crate) use ring as ring_like; use webpki::ring as webpki_algs; +use zeroize::Zeroizing; use crate::Error; use crate::crypto::{CryptoProvider, KeyProvider, SecureRandom, SupportedKxGroup}; @@ -57,7 +58,7 @@ impl KeyProvider for Ring { &self, key_der: PrivateKeyDer<'static>, ) -> Result, Error> { - sign::any_supported_type(&key_der) + sign::any_supported_type(&Zeroizing::new(key_der)) } } diff --git a/rustls/src/crypto/ring/sign.rs b/rustls/src/crypto/ring/sign.rs index ad318270a99..028c8bb9f0c 100644 --- a/rustls/src/crypto/ring/sign.rs +++ b/rustls/src/crypto/ring/sign.rs @@ -304,7 +304,9 @@ impl SigningKey for EcdsaSigningKey { } fn algorithm(&self) -> SignatureAlgorithm { - self.scheme.algorithm() + self.scheme + .algorithm() + .unwrap_or(SignatureAlgorithm::Unknown(0)) } } @@ -392,7 +394,9 @@ impl SigningKey for Ed25519SigningKey { } fn algorithm(&self) -> SignatureAlgorithm { - self.scheme.algorithm() + self.scheme + .algorithm() + .unwrap_or(SignatureAlgorithm::Unknown(0)) } } diff --git a/rustls/src/enums.rs b/rustls/src/enums.rs index 4b450aafc84..817c933e5bb 100644 --- a/rustls/src/enums.rs +++ b/rustls/src/enums.rs @@ -522,7 +522,7 @@ enum_builder! { } impl SignatureScheme { - pub(crate) fn algorithm(&self) -> SignatureAlgorithm { + pub(crate) fn algorithm(&self) -> Option { match *self { Self::RSA_PKCS1_SHA1 | Self::RSA_PKCS1_SHA256 @@ -530,14 +530,14 @@ impl SignatureScheme { | Self::RSA_PKCS1_SHA512 | Self::RSA_PSS_SHA256 | Self::RSA_PSS_SHA384 - | Self::RSA_PSS_SHA512 => SignatureAlgorithm::RSA, + | Self::RSA_PSS_SHA512 => Some(SignatureAlgorithm::RSA), Self::ECDSA_SHA1_Legacy | Self::ECDSA_NISTP256_SHA256 | Self::ECDSA_NISTP384_SHA384 - | Self::ECDSA_NISTP521_SHA512 => SignatureAlgorithm::ECDSA, - Self::ED25519 => SignatureAlgorithm::ED25519, - Self::ED448 => SignatureAlgorithm::ED448, - _ => SignatureAlgorithm::Unknown(0), + | Self::ECDSA_NISTP521_SHA512 => Some(SignatureAlgorithm::ECDSA), + Self::ED25519 => Some(SignatureAlgorithm::ED25519), + Self::ED448 => Some(SignatureAlgorithm::ED448), + _ => None, } } diff --git a/rustls/src/error.rs b/rustls/src/error.rs index 3aaf3bb3c17..dbd043fb9cb 100644 --- a/rustls/src/error.rs +++ b/rustls/src/error.rs @@ -237,6 +237,7 @@ impl From for AlertDescription { pub enum PeerMisbehaved { AttemptedDowngradeToTls12WhenTls13IsSupported, BadCertChainExtensions, + CipherSuiteDifferedOnRetry, DisallowedEncryptedExtension, DuplicateClientHelloExtensions, DuplicateEncryptedExtensions, @@ -247,6 +248,7 @@ pub enum PeerMisbehaved { EarlyDataAttemptedInSecondClientHello, EarlyDataExtensionWithoutResumption, EarlyDataOfferedWithVariedCipherSuite, + EchAcceptanceVariedAfterRetry, HandshakeHashVariedAfterRetry, IllegalHelloRetryRequestWithEmptyCookie, IllegalHelloRetryRequestWithNoChanges, @@ -267,6 +269,7 @@ pub enum PeerMisbehaved { MessageInterleavedWithHandshakeMessage, MissingBinderInPskExtension, MissingKeyShare, + MissingPskExtensionInSecondClientHello, MissingPskModesExtension, MissingQuicTransportParameters, OfferedDuplicateCertificateCompressions, diff --git a/rustls/src/key_log_file.rs b/rustls/src/key_log_file.rs index 45f29da552c..2d337c793ef 100644 --- a/rustls/src/key_log_file.rs +++ b/rustls/src/key_log_file.rs @@ -5,6 +5,8 @@ use std::ffi::OsString; use std::fs::{File, OpenOptions}; use std::io; use std::io::Write; +#[cfg(unix)] +use std::os::unix::fs::OpenOptionsExt; use std::sync::Mutex; use crate::KeyLog; @@ -25,12 +27,15 @@ impl KeyLogFileInner { }; }; + let mut options = OpenOptions::new(); + options.append(true).create(true); + // Key material is extremely sensitive. On Unix, create with owner-only + // access so a default umask does not leave the file world-readable. + #[cfg(unix)] + options.mode(0o600); + #[cfg_attr(not(feature = "logging"), allow(unused_variables))] - let file = match OpenOptions::new() - .append(true) - .create(true) - .open(path) - { + let file = match options.open(path) { Ok(f) => Some(f), Err(e) => { warn!("unable to create key log file {path:?}: {e}"); @@ -49,7 +54,7 @@ impl KeyLogFileInner { return Ok(()); }; - self.buf.truncate(0); + self.buf.clear(); write!(self.buf, "{label} ")?; for b in client_random.iter() { write!(self.buf, "{b:02x}")?; @@ -117,8 +122,12 @@ impl Debug for KeyLogFile { } } -#[cfg(all(test, target_os = "linux"))] +#[cfg(all(test, unix))] mod tests { + use std::os::unix::fs::PermissionsExt; + use std::time::{SystemTime, UNIX_EPOCH}; + use std::{env, format, fs, process}; + use super::*; fn init() { @@ -149,6 +158,7 @@ mod tests { ); } + #[cfg(target_os = "linux")] #[test] fn test_env_var_cannot_be_written() { init(); @@ -159,4 +169,32 @@ mod tests { .is_err() ); } + + #[test] + fn test_created_file_has_owner_only_permissions() { + let path = env::temp_dir().join(format!( + "rustls-keylog-perm-{}-{}", + process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let _ = fs::remove_file(&path); + + let inner = KeyLogFileInner::new(Some(path.clone().into())); + assert!(inner.file.is_some(), "key log file should open"); + + let mode = fs::metadata(&path) + .expect("metadata") + .permissions() + .mode() + & 0o777; + let _ = fs::remove_file(&path); + + assert_eq!( + mode, 0o600, + "SSLKEYLOGFILE must be created with mode 0o600, got {mode:#o}" + ); + } } diff --git a/rustls/src/lib.rs b/rustls/src/lib.rs index 807a4a2ddde..9072740afad 100644 --- a/rustls/src/lib.rs +++ b/rustls/src/lib.rs @@ -24,7 +24,7 @@ //! Specifying `default-features = false` when depending on rustls will remove the implicit //! dependency on aws-lc-rs. //! -//! Rustls requires Rust 1.71 or later. It has an optional dependency on zlib-rs which requires 1.75 or later. +//! This fork requires Rust 1.85 or later, where upstream rustls requires 1.71: the `aws_lc_rs` feature, on by default, depends on the `shake` crate, which sets that floor. //! //! [ring-target-platforms]: https://github.com/briansmith/ring/blob/2e8363b433fa3b3962c877d9ed2e9145612f3160/include/ring-core/target.h#L18-L64 //! [`crypto::CryptoProvider`]: crate::crypto::CryptoProvider @@ -596,7 +596,7 @@ pub mod client { pub use builder::WantsClientCert; pub use client_conn::{ ClientConfig, ClientConnectionData, ClientSessionStore, EarlyDataError, ResolvesClientCert, - Resumption, Tls12Resumption, UnbufferedClientConnection, + Resumption, TicketRequest, Tls12Resumption, UnbufferedClientConnection, }; #[cfg(feature = "std")] pub use client_conn::{ClientConnection, WriteEarlyData}; diff --git a/rustls/src/limited_cache.rs b/rustls/src/limited_cache.rs index 6ae8bf94d2e..0cd5df7eca0 100644 --- a/rustls/src/limited_cache.rs +++ b/rustls/src/limited_cache.rs @@ -17,6 +17,10 @@ pub(crate) struct LimitedCache { // first item is the oldest key oldest: VecDeque, + + /// Maximum number of entries to retain. Compared after insert so + /// a capacity of 1 still keeps the item that was just added. + max: usize, } impl LimitedCache @@ -38,8 +42,7 @@ where } }; - // ensure next insertion does not require a realloc - if inserted_new_item && self.oldest.capacity() == self.oldest.len() { + if inserted_new_item && self.oldest.len() > self.max { if let Some(oldest_key) = self.oldest.pop_front() { self.map.remove(&oldest_key); } @@ -64,6 +67,7 @@ where Self { map: HashMap::with_capacity(capacity_order_of_magnitude), oldest: VecDeque::with_capacity(capacity_order_of_magnitude), + max: capacity_order_of_magnitude, } } @@ -83,8 +87,7 @@ where } }; - // ensure next insertion does not require a realloc - if inserted_new_item && self.oldest.capacity() == self.oldest.len() { + if inserted_new_item && self.oldest.len() > self.max { if let Some(oldest_key) = self.oldest.pop_front() { self.map.remove(&oldest_key); } @@ -138,9 +141,23 @@ mod tests { t.insert("def".into(), 2); t.insert("ghi".into(), 3); - assert_eq!(t.get("abc"), None); + assert_eq!(t.get("abc"), Some(&1)); assert_eq!(t.get("def"), Some(&2)); assert_eq!(t.get("ghi"), Some(&3)); + + t.insert("jkl".into(), 4); + assert_eq!(t.get("abc"), None); + assert_eq!(t.get("jkl"), Some(&4)); + } + + #[test] + fn test_capacity_one_retains_the_item() { + let mut t = Test::new(1); + t.insert("abc".into(), 1); + assert_eq!(t.get("abc"), Some(&1)); + t.insert("def".into(), 2); + assert_eq!(t.get("abc"), None); + assert_eq!(t.get("def"), Some(&2)); } #[test] @@ -155,7 +172,7 @@ mod tests { t.insert("jkl".into(), 4); assert_eq!(t.get("abc"), None); - assert_eq!(t.get("def"), None); + assert_eq!(t.get("def"), Some(&2)); assert_eq!(t.get("ghi"), Some(&3)); assert_eq!(t.get("jkl"), Some(&4)); } @@ -172,10 +189,14 @@ mod tests { t.insert("ghi".into(), 3); t.insert("jkl".into(), 4); - assert_eq!(t.get("abc"), None); + assert_eq!(t.get("abc"), Some(&1)); assert_eq!(t.get("def"), None); assert_eq!(t.get("ghi"), Some(&3)); assert_eq!(t.get("jkl"), Some(&4)); + + t.insert("mno".into(), 5); + assert_eq!(t.get("abc"), None); + assert_eq!(t.get("mno"), Some(&5)); } #[test] @@ -193,7 +214,7 @@ mod tests { assert_eq!(t.get("abc"), None); assert_eq!(t.get("def"), None); - assert_eq!(t.get("ghi"), None); + assert_eq!(t.get("ghi"), Some(&3)); assert_eq!(t.get("jkl"), Some(&4)); assert_eq!(t.get("mno"), Some(&5)); } @@ -215,26 +236,25 @@ mod tests { t.get_or_insert_default_and_edit("abc".into(), |v| *v += 1); t.get_or_insert_default_and_edit("def".into(), |v| *v += 2); + t.get_or_insert_default_and_edit("ghi".into(), |v| *v += 3); + assert_eq!(t.get("abc"), Some(&1)); // evicts "abc" - t.get_or_insert_default_and_edit("ghi".into(), |v| *v += 3); + t.get_or_insert_default_and_edit("jkl".into(), |v| *v += 4); assert_eq!(t.get("abc"), None); // evicts "def" - t.get_or_insert_default_and_edit("jkl".into(), |v| *v += 4); + t.get_or_insert_default_and_edit("abc".into(), |v| *v += 5); assert_eq!(t.get("def"), None); // evicts "ghi" - t.get_or_insert_default_and_edit("abc".into(), |v| *v += 5); - assert_eq!(t.get("ghi"), None); - - // evicts "jkl" t.get_or_insert_default_and_edit("def".into(), |v| *v += 6); + assert_eq!(t.get("ghi"), None); assert_eq!(t.get("abc"), Some(&5)); assert_eq!(t.get("def"), Some(&6)); assert_eq!(t.get("ghi"), None); - assert_eq!(t.get("jkl"), None); + assert_eq!(t.get("jkl"), Some(&4)); } #[test] diff --git a/rustls/src/msgs/base.rs b/rustls/src/msgs/base.rs index 4204714d891..1559b6e0ab2 100644 --- a/rustls/src/msgs/base.rs +++ b/rustls/src/msgs/base.rs @@ -82,29 +82,49 @@ impl fmt::Debug for Payload<'_> { /// An arbitrary, unknown-content, u24-length-prefixed payload #[derive(Clone, Eq, PartialEq)] -pub(crate) struct PayloadU24<'a>(pub(crate) Payload<'a>); - -impl PayloadU24<'_> { - pub(crate) fn into_owned(self) -> PayloadU24<'static> { - PayloadU24(self.0.into_owned()) +pub(crate) struct PayloadU24<'a, C: Cardinality = MaybeEmpty>( + pub(crate) Payload<'a>, + PhantomData, +); + +impl PayloadU24<'_, C> { + pub(crate) fn into_owned(self) -> PayloadU24<'static, C> { + PayloadU24(self.0.into_owned(), PhantomData) } } -impl<'a> Codec<'a> for PayloadU24<'a> { +impl<'a, C: Cardinality> Codec<'a> for PayloadU24<'a, C> { fn encode(&self, bytes: &mut Vec) { let inner = self.0.bytes(); + debug_assert!(inner.len() >= C::MIN); codec::u24(inner.len() as u32).encode(bytes); bytes.extend_from_slice(inner); } fn read(r: &mut Reader<'a>) -> Result { let len = codec::u24::read(r)?.0 as usize; + if len < C::MIN { + return Err(InvalidMessage::IllegalEmptyList("PayloadU24")); + } let mut sub = r.sub(len)?; - Ok(Self(Payload::read(&mut sub))) + Ok(Self(Payload::read(&mut sub), PhantomData)) + } +} + +impl<'a, C: Cardinality> From> for PayloadU24<'a, C> { + fn from(value: Payload<'a>) -> Self { + debug_assert!(value.bytes().len() >= C::MIN); + Self(value, PhantomData) + } +} + +impl AsRef<[u8]> for PayloadU24<'_, C> { + fn as_ref(&self) -> &[u8] { + self.0.bytes() } } -impl fmt::Debug for PayloadU24<'_> { +impl fmt::Debug for PayloadU24<'_, C> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } diff --git a/rustls/src/msgs/deframer/handshake.rs b/rustls/src/msgs/deframer/handshake.rs index 0d91f0eac82..98498219654 100644 --- a/rustls/src/msgs/deframer/handshake.rs +++ b/rustls/src/msgs/deframer/handshake.rs @@ -91,12 +91,12 @@ impl HandshakeDeframer { !self.spans.is_empty() } - /// We are "aligned" if there is no partial fragment of a handshake - /// message. + /// We are "aligned" if there are no pending handshake messages, complete or partial. pub(crate) fn is_aligned(&self) -> bool { - self.spans - .iter() - .all(|span| span.is_complete()) + // If we have any handshake spans, either: + // - it is a full pending handshake message, or + // - it is not, which means it's a partial fragment + !self.is_active() } /// Iterate over the complete messages. diff --git a/rustls/src/msgs/enums.rs b/rustls/src/msgs/enums.rs index fb10bbea13b..264dc1324ff 100644 --- a/rustls/src/msgs/enums.rs +++ b/rustls/src/msgs/enums.rs @@ -140,6 +140,7 @@ enum_builder! { SignatureAlgorithmsCert => 0x0032, KeyShare => 0x0033, TransportParameters => 0x0039, + TicketRequest => 0x003a, NextProtocolNegotiation => 0x3374, ChannelId => 0x754f, RenegotiationInfo => 0xff01, diff --git a/rustls/src/msgs/handshake.rs b/rustls/src/msgs/handshake.rs index dce0ec31a97..905358d45e3 100644 --- a/rustls/src/msgs/handshake.rs +++ b/rustls/src/msgs/handshake.rs @@ -914,6 +914,47 @@ impl TransportParameters<'_> { } } +/// RFC 9149: ClientTicketRequest extension payload. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct ClientTicketRequest { + /// Tickets desired when the server negotiates a new connection. + pub new_session_count: u8, + /// Tickets desired when the server resumes using a presented ticket. + pub resumption_count: u8, +} + +impl Codec<'_> for ClientTicketRequest { + fn encode(&self, bytes: &mut Vec) { + self.new_session_count.encode(bytes); + self.resumption_count.encode(bytes); + } + + fn read(r: &mut Reader<'_>) -> Result { + Ok(Self { + new_session_count: u8::read(r)?, + resumption_count: u8::read(r)?, + }) + } +} + +/// RFC 9149: ServerTicketRequestHint extension payload. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct ServerTicketRequestHint { + pub(crate) expected_count: u8, +} + +impl Codec<'_> for ServerTicketRequestHint { + fn encode(&self, bytes: &mut Vec) { + self.expected_count.encode(bytes); + } + + fn read(r: &mut Reader<'_>) -> Result { + Ok(Self { + expected_count: u8::read(r)?, + }) + } +} + extension_struct! { /// A representation of extensions present in a `ClientHello` message /// @@ -1007,6 +1048,10 @@ extension_struct! { ExtensionType::TransportParameters => pub(crate) transport_parameters: Option>, + /// Ticket request (RFC9149) + ExtensionType::TicketRequest => + pub(crate) ticket_request: Option, + /// Secure renegotiation (RFC5746) ExtensionType::RenegotiationInfo => pub(crate) renegotiation_info: Option, @@ -1048,19 +1093,18 @@ fn insert_positioned_grease( grease: &[(usize, ExtensionType, Payload<'static>)], ) { let real_order = core::mem::take(order); - let real_order_len = real_order.len(); - - for position in 0..=real_order_len { - for (_, extension, _) in grease + let grease_at = |position: usize| { + grease .iter() - .filter(|(grease_position, _, _)| *grease_position == position) - { - order.push(*extension); - } - if position < real_order_len { - order.push(real_order[position]); - } + .filter(move |(grease_position, _, _)| *grease_position == position) + .map(|(_, extension, _)| *extension) + }; + + for (position, extension) in real_order.iter().enumerate() { + order.extend(grease_at(position)); + order.push(*extension); } + order.extend(grease_at(real_order.len())); } impl ClientExtensions<'_> { @@ -1087,6 +1131,7 @@ impl ClientExtensions<'_> { certificate_authority_names, key_shares, transport_parameters, + ticket_request, renegotiation_info, transport_parameters_draft, encrypted_client_hello, @@ -1120,6 +1165,7 @@ impl ClientExtensions<'_> { certificate_authority_names, key_shares, transport_parameters: transport_parameters.map(|x| x.into_owned()), + ticket_request, renegotiation_info, transport_parameters_draft: transport_parameters_draft.map(|x| x.into_owned()), encrypted_client_hello, @@ -1447,6 +1493,10 @@ extension_struct! { ExtensionType::EarlyData => pub(crate) early_data_ack: Option<()>, + /// Ticket request hint (RFC9149) + ExtensionType::TicketRequest => + pub(crate) ticket_request: Option, + /// Encrypted inner client hello response (draft-ietf-tls-esni) ExtensionType::EncryptedClientHello => pub(crate) encrypted_client_hello_ack: Option, @@ -1473,6 +1523,7 @@ impl ServerExtensions<'_> { transport_parameters, transport_parameters_draft, early_data_ack, + ticket_request, encrypted_client_hello_ack, unknown_extensions, } = self; @@ -1492,6 +1543,7 @@ impl ServerExtensions<'_> { transport_parameters: transport_parameters.map(|x| x.into_owned()), transport_parameters_draft: transport_parameters_draft.map(|x| x.into_owned()), early_data_ack, + ticket_request, encrypted_client_hello_ack, unknown_extensions, } @@ -2681,7 +2733,8 @@ impl Codec<'_> for NewSessionTicketPayloadTls13 { /// Only supports OCSP #[derive(Clone, Debug)] pub(crate) struct CertificateStatus<'a> { - pub(crate) ocsp_response: PayloadU24<'a>, + /// `opaque OCSPResponse<1..2^24-1>;` + pub(crate) ocsp_response: PayloadU24<'a, NonEmpty>, } impl<'a> Codec<'a> for CertificateStatus<'a> { @@ -2705,7 +2758,7 @@ impl<'a> Codec<'a> for CertificateStatus<'a> { impl<'a> CertificateStatus<'a> { pub(crate) fn new(ocsp: &'a [u8]) -> Self { CertificateStatus { - ocsp_response: PayloadU24(Payload::Borrowed(ocsp)), + ocsp_response: PayloadU24::from(Payload::Borrowed(ocsp)), } } @@ -2758,7 +2811,7 @@ impl CompressedCertificatePayload<'_> { CompressedCertificatePayload { alg: self.alg, uncompressed_len: self.uncompressed_len, - compressed: PayloadU24(Payload::Borrowed(self.compressed.0.bytes())), + compressed: PayloadU24::from(Payload::Borrowed(self.compressed.0.bytes())), } } } @@ -2992,7 +3045,9 @@ impl<'a> HandshakeMessagePayload<'a> { pub(crate) fn encoding_for_binder_signing(&self) -> Vec { let mut ret = self.get_encoding(); - let ret_len = ret.len() - self.total_binder_length(); + let ret_len = ret + .len() + .saturating_sub(self.total_binder_length()); ret.truncate(ret_len); ret } diff --git a/rustls/src/msgs/handshake_test.rs b/rustls/src/msgs/handshake_test.rs index 8756c8b28ff..b8cdcd1d887 100644 --- a/rustls/src/msgs/handshake_test.rs +++ b/rustls/src/msgs/handshake_test.rs @@ -137,7 +137,7 @@ fn refuses_server_ext_with_unparsed_bytes() { #[test] fn refuses_certificate_ext_with_unparsed_bytes() { let bytes = [ - 0x00u8, 0x09, 0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x00u8, 0x0a, 0x00, 0x05, 0x00, 0x06, 0x01, 0x00, 0x00, 0x01, 0xcc, 0x01, ]; assert_eq!( CertificateExtensions::read_bytes(&bytes).unwrap_err(), @@ -836,6 +836,7 @@ fn sample_server_hello_payload() -> ServerHelloPayload { key_share: Some(KeyShareEntry::new(NamedGroup::X25519, &[1, 2, 3][..])), preshared_key: Some(3), early_data_ack: Some(()), + ticket_request: None, encrypted_client_hello_ack: Some(ServerEncryptedClientHello { retry_configs: vec![], }), @@ -964,7 +965,7 @@ fn sample_certificate_payload_tls13() -> CertificatePayloadTls13<'static> { cert: CertificateDer::from(vec![3, 4, 5]), extensions: CertificateExtensions { status: Some(CertificateStatus { - ocsp_response: PayloadU24(Payload::new(vec![1, 2, 3])), + ocsp_response: PayloadU24::from(Payload::new(vec![1, 2, 3])), }), }, }], @@ -975,7 +976,7 @@ fn sample_compressed_certificate() -> CompressedCertificatePayload<'static> { CompressedCertificatePayload { alg: CertificateCompressionAlgorithm::Brotli, uncompressed_len: 123, - compressed: PayloadU24(Payload::new(vec![1, 2, 3])), + compressed: PayloadU24::from(Payload::new(vec![1, 2, 3])), } } @@ -1051,6 +1052,6 @@ fn sample_encrypted_extensions() -> Box> { fn sample_certificate_status() -> CertificateStatus<'static> { CertificateStatus { - ocsp_response: PayloadU24(Payload::new(vec![1, 2, 3])), + ocsp_response: PayloadU24::from(Payload::new(vec![1, 2, 3])), } } diff --git a/rustls/src/msgs/message/inbound.rs b/rustls/src/msgs/message/inbound.rs index f8b2181c22d..5168a5f1de7 100644 --- a/rustls/src/msgs/message/inbound.rs +++ b/rustls/src/msgs/message/inbound.rs @@ -56,7 +56,8 @@ impl<'a> InboundOpaqueMessage<'a> { /// For TLS1.3 (only), checks the length msg.payload is valid and removes the padding. /// /// Returns an error if the message (pre-unpadding) is too long, or the padding is invalid, - /// or the message (post-unpadding) is too long. + /// or the inner content type is `change_cipher_spec`, or the message (post-unpadding) is + /// too long. pub fn into_tls13_unpadded_message(mut self) -> Result, Error> { let payload = &mut self.payload; @@ -69,6 +70,14 @@ impl<'a> InboundOpaqueMessage<'a> { return Err(PeerMisbehaved::IllegalTlsInnerPlaintext.into()); } + // > An implementation which receives any other change_cipher_spec value or + // > which receives a protected change_cipher_spec record MUST abort the + // > handshake with an "unexpected_message" alert. + // + if self.typ == ContentType::ChangeCipherSpec { + return Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()); + } + if payload.len() > MAX_FRAGMENT_LEN { return Err(Error::PeerSentOversizedRecord); } diff --git a/rustls/src/msgs/message_test.rs b/rustls/src/msgs/message_test.rs index 965a3572e00..0f5a08b66e1 100644 --- a/rustls/src/msgs/message_test.rs +++ b/rustls/src/msgs/message_test.rs @@ -6,8 +6,9 @@ use std::{format, fs, println, vec}; use super::base::Payload; use super::codec::Reader; use super::enums::AlertLevel; -use super::message::{Message, OutboundOpaqueMessage, PlainMessage}; -use crate::enums::{AlertDescription, HandshakeType}; +use super::message::{InboundOpaqueMessage, Message, OutboundOpaqueMessage, PlainMessage}; +use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion}; +use crate::error::{Error, PeerMisbehaved}; use crate::msgs::base::{MaybeEmpty, NonEmpty, PayloadU8, PayloadU16, PayloadU24}; #[test] @@ -110,7 +111,10 @@ fn debug_payload() { ); assert_eq!( "01020304", - format!("{:?}", PayloadU24(Payload::new(vec![1, 2, 3, 4]))) + format!( + "{:?}", + PayloadU24::<'static, NonEmpty>::from(Payload::new(vec![1, 2, 3, 4])) + ) ); } @@ -122,3 +126,18 @@ fn into_wire_format() { &[0x16, 0x3, 0x4, 0x0, 0x5, 0x18, 0x0, 0x0, 0x1, 0x1] ); } + +#[test] +fn tls13_unpadded_message_rejects_protected_change_cipher_spec() { + let mut payload = [0x01u8, ContentType::ChangeCipherSpec.into(), 0x00]; + let msg = InboundOpaqueMessage::new( + ContentType::ApplicationData, + ProtocolVersion::TLSv1_2, + &mut payload, + ); + assert_eq!( + msg.into_tls13_unpadded_message() + .unwrap_err(), + Error::PeerMisbehaved(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec) + ); +} diff --git a/rustls/src/msgs/persist.rs b/rustls/src/msgs/persist.rs index 8231c8ff61c..79370ed3639 100644 --- a/rustls/src/msgs/persist.rs +++ b/rustls/src/msgs/persist.rs @@ -1,5 +1,5 @@ use alloc::vec::Vec; -use core::cmp; +use core::{cmp, fmt}; use pki_types::{DnsName, UnixTime}; use zeroize::Zeroizing; @@ -45,7 +45,10 @@ impl Retrieved<&Tls13ClientSessionValue> { .retrieved_at .as_secs() .saturating_sub(self.value.common.epoch); - let age_millis = age_secs as u32 * 1000; + // nb. tickets have an upper age limit of ~7 days, well short of the 49 days here + let age_millis = u32::try_from(age_secs) + .unwrap_or(u32::MAX) + .saturating_mul(1000); age_millis.wrapping_add(self.value.age_add) } } @@ -69,7 +72,6 @@ impl core::ops::Deref for Retrieved { } } -#[derive(Debug)] pub struct Tls13ClientSessionValue { suite: &'static Tls13CipherSuite, age_add: u32, @@ -145,6 +147,26 @@ impl core::ops::Deref for Tls13ClientSessionValue { } } +impl fmt::Debug for Tls13ClientSessionValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + suite, + age_add, + max_early_data_size, + common, + quic_params, + } = self; + + f.debug_struct("Tls13ClientSessionValue") + .field("suite", suite) + .field("age_add", age_add) + .field("max_early_data_size", max_early_data_size) + .field("common", common) + .field("quic_params", quic_params) + .finish() + } +} + #[derive(Debug, Clone)] pub struct Tls12ClientSessionValue { #[cfg(feature = "tls12")] @@ -216,7 +238,7 @@ impl core::ops::Deref for Tls12ClientSessionValue { } } -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct ClientSessionCommon { ticket: Arc, secret: Zeroizing, @@ -287,6 +309,28 @@ impl ClientSessionCommon { } } +impl fmt::Debug for ClientSessionCommon { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + ticket, + secret: _, + epoch, + lifetime_secs, + server_cert_chain, + server_cert_verifier, + client_creds, + } = self; + f.debug_struct("ClientSessionCommon") + .field("ticket", ticket) + .field("epoch", epoch) + .field("lifetime_secs", lifetime_secs) + .field("server_cert_chain", server_cert_chain) + .field("server_cert_verifier", server_cert_verifier) + .field("client_creds", client_creds) + .finish_non_exhaustive() + } +} + static MAX_TICKET_LIFETIME: u32 = 7 * 24 * 60 * 60; /// This is the maximum allowed skew between server and client clocks, over @@ -296,7 +340,6 @@ static MAX_TICKET_LIFETIME: u32 = 7 * 24 * 60 * 60; static MAX_FRESHNESS_SKEW_MS: u32 = 60 * 1000; // --- Server types --- -#[derive(Debug)] pub struct ServerSessionValue { pub(crate) sni: Option>, pub(crate) version: ProtocolVersion, @@ -311,6 +354,36 @@ pub struct ServerSessionValue { freshness: Option, } +impl fmt::Debug for ServerSessionValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + sni, + version, + cipher_suite, + master_secret: _, + extended_ms, + client_cert_chain, + alpn, + application_data, + creation_time_sec, + age_obfuscation_offset, + freshness, + } = self; + f.debug_struct("ServerSessionValue") + .field("sni", sni) + .field("version", version) + .field("cipher_suite", cipher_suite) + .field("extended_ms", extended_ms) + .field("client_cert_chain", client_cert_chain) + .field("alpn", alpn) + .field("application_data", application_data) + .field("creation_time_sec", creation_time_sec) + .field("age_obfuscation_offset", age_obfuscation_offset) + .field("freshness", freshness) + .finish_non_exhaustive() + } +} + impl Codec<'_> for ServerSessionValue { fn encode(&self, bytes: &mut Vec) { if let Some(sni) = &self.sni { @@ -453,19 +526,22 @@ mod tests { #[cfg(feature = "std")] // for UnixTime::now #[test] fn serversessionvalue_is_debug() { - use std::{println, vec}; + use std::{format, println, vec}; let ssv = ServerSessionValue::new( None, ProtocolVersion::TLSv1_3, CipherSuite::TLS13_AES_128_GCM_SHA256, - &[1, 2, 3], + &[0xa5; 48], None, None, vec![4, 5, 6], UnixTime::now(), 0x12345678, ); - println!("{ssv:?}"); + let debug = format!("{ssv:?}"); + println!("{debug}"); + assert!(debug.contains("application_data: 040506")); + assert!(!debug.contains("a5a5"), "{debug}"); } #[test] diff --git a/rustls/src/quic.rs b/rustls/src/quic.rs index d1b732663aa..099e6eabd7f 100644 --- a/rustls/src/quic.rs +++ b/rustls/src/quic.rs @@ -183,7 +183,7 @@ mod connection { params: Vec, alpn_protocols: Vec>, ) -> Result { - if !config.supports_version(ProtocolVersion::TLSv1_3) { + if !config.supports_version(ProtocolVersion::TLSv1_3, Protocol::Quic) { return Err(Error::General( "TLS 1.3 support is required for QUIC".into(), )); @@ -268,7 +268,7 @@ mod connection { quic_version: Version, params: Vec, ) -> Result { - if !config.supports_version(ProtocolVersion::TLSv1_3) { + if !config.supports_version(ProtocolVersion::TLSv1_3, Protocol::Quic) { return Err(Error::General( "TLS 1.3 support is required for QUIC".into(), )); diff --git a/rustls/src/record_layer.rs b/rustls/src/record_layer.rs index 8c2ea6b9b68..0106dafb9fa 100644 --- a/rustls/src/record_layer.rs +++ b/rustls/src/record_layer.rs @@ -198,8 +198,8 @@ impl RecordLayer { /// "the next message processed by `encrypt_outgoing`" pub(crate) fn pre_encrypt_action(&self, add: u64) -> PreEncryptAction { match self.write_seq.saturating_add(add) { - v if v == self.write_seq_max => PreEncryptAction::RefreshOrClose, SEQ_HARD_LIMIT.. => PreEncryptAction::Refuse, + v if v >= self.write_seq_max => PreEncryptAction::RefreshOrClose, _ => PreEncryptAction::Nothing, } } @@ -273,6 +273,28 @@ const SEQ_HARD_LIMIT: u64 = 0xffff_ffff_ffff_fffeu64; mod tests { use super::*; + #[test] + fn pre_encrypt_action_checks_limits() { + let action = |write_seq_max, write_seq, add| { + let mut record_layer = RecordLayer::new(); + record_layer.write_seq_max = write_seq_max; + record_layer.write_seq = write_seq; + record_layer.pre_encrypt_action(add) + }; + + assert_eq!(action(10, 8, 1), PreEncryptAction::Nothing); + assert_eq!(action(10, 8, 2), PreEncryptAction::RefreshOrClose); + assert_eq!(action(10, 11, 0), PreEncryptAction::RefreshOrClose); + assert_eq!( + action(SEQ_SOFT_LIMIT, SEQ_HARD_LIMIT - 1, 0), + PreEncryptAction::RefreshOrClose + ); + assert_eq!( + action(SEQ_SOFT_LIMIT, SEQ_HARD_LIMIT - 1, 1), + PreEncryptAction::Refuse + ); + } + #[test] fn test_has_decrypted() { use crate::{ContentType, ProtocolVersion}; diff --git a/rustls/src/server/builder.rs b/rustls/src/server/builder.rs index daf6e094ecf..22b30abc5e8 100644 --- a/rustls/src/server/builder.rs +++ b/rustls/src/server/builder.rs @@ -121,6 +121,7 @@ impl ConfigBuilder { max_early_data_size: 0, send_half_rtt_data: false, send_tls13_tickets: 2, + max_tls13_tickets: 0, #[cfg(feature = "tls12")] require_ems, time_provider: self.time_provider, diff --git a/rustls/src/server/handy.rs b/rustls/src/server/handy.rs index ea3ec5d9db0..e695aa80aae 100644 --- a/rustls/src/server/handy.rs +++ b/rustls/src/server/handy.rs @@ -34,7 +34,7 @@ mod cache { use crate::{limited_cache, server}; /// An implementer of `StoresServerSessions` that stores everything - /// in memory. If enforces a limit on the number of stored sessions + /// in memory. It enforces a limit on the number of stored sessions /// to bound memory usage. pub struct ServerSessionMemoryCache { cache: Mutex, Vec>>, @@ -124,6 +124,8 @@ mod cache { assert_eq!(c.get(&[0x01]), Some(vec![0x04])); } + /// After five sessions are put into a cache of size 2, exactly the + /// two most recently added sessions remain. #[test] fn test_serversessionmemorycache_drops_to_maintain_size_invariant() { let c = ServerSessionMemoryCache::new(2); @@ -133,13 +135,24 @@ mod cache { assert!(c.put(vec![0x07], vec![0x08])); assert!(c.put(vec![0x09], vec![0x0a])); - let count = c.get(&[0x01]).iter().count() - + c.get(&[0x03]).iter().count() - + c.get(&[0x05]).iter().count() - + c.get(&[0x07]).iter().count() - + c.get(&[0x09]).iter().count(); + assert_eq!(c.get(&[0x01]), None); + assert_eq!(c.get(&[0x03]), None); + assert_eq!(c.get(&[0x05]), None); + assert_eq!(c.get(&[0x07]), Some(vec![0x08])); + assert_eq!(c.get(&[0x09]), Some(vec![0x0a])); + } + + /// A cache of size 1 keeps the session put into it, and a second + /// put replaces it. + #[test] + fn test_serversessionmemorycache_size_one_retains_session() { + let c = ServerSessionMemoryCache::new(1); + assert!(c.put(vec![0x01], vec![0x02])); + assert_eq!(c.get(&[0x01]), Some(vec![0x02])); - assert!(count < 5); + assert!(c.put(vec![0x03], vec![0x04])); + assert_eq!(c.get(&[0x01]), None); + assert_eq!(c.get(&[0x03]), Some(vec![0x04])); } } } diff --git a/rustls/src/server/hs.rs b/rustls/src/server/hs.rs index d98336e461b..98081ab34e1 100644 --- a/rustls/src/server/hs.rs +++ b/rustls/src/server/hs.rs @@ -313,7 +313,7 @@ pub(super) struct ExpectClientHello { pub(super) session_id: SessionId, #[cfg(feature = "tls12")] pub(super) using_ems: bool, - pub(super) done_retry: bool, + pub(super) previous_hello: Option, pub(super) send_tickets: usize, } @@ -336,7 +336,7 @@ impl ExpectClientHello { session_id: SessionId::empty(), #[cfg(feature = "tls12")] using_ems: false, - done_retry: false, + previous_hello: None, send_tickets: 0, } } @@ -351,10 +351,11 @@ impl ExpectClientHello { ) -> NextStateOrError<'static> { let tls13_enabled = self .config - .supports_version(ProtocolVersion::TLSv1_3); + .supports_version(ProtocolVersion::TLSv1_3, cx.common.protocol); let tls12_enabled = self .config - .supports_version(ProtocolVersion::TLSv1_2); + .supports_version(ProtocolVersion::TLSv1_2, cx.common.protocol) + && !self.previous_hello.is_some(); // Are we doing TLS1.3? let version = if let Some(versions) = &client_hello.supported_versions { @@ -378,15 +379,15 @@ impl ExpectClientHello { AlertDescription::ProtocolVersion, PeerIncompatible::Tls12NotOffered, )); - } else if !tls12_enabled && tls13_enabled { + } else if cx.common.is_quic() { return Err(cx.common.send_fatal_alert( AlertDescription::ProtocolVersion, - PeerIncompatible::SupportedVersionsExtensionRequired, + PeerIncompatible::Tls13RequiredForQuic, )); - } else if cx.common.is_quic() { + } else if !tls12_enabled && tls13_enabled { return Err(cx.common.send_fatal_alert( AlertDescription::ProtocolVersion, - PeerIncompatible::Tls13RequiredForQuic, + PeerIncompatible::SupportedVersionsExtensionRequired, )); } else { ProtocolVersion::TLSv1_2 @@ -470,6 +471,21 @@ impl ExpectClientHello { .send_fatal_alert(AlertDescription::HandshakeFailure, incompat) })?; + // RFC 9846 section 4.2.4: the server must negotiate the same cipher suite it + // named in its HelloRetryRequest + if let Some(PreviousClientHello { + suite: before_retry, + .. + }) = self.previous_hello + { + if before_retry != suite.suite() { + return Err(cx.common.send_fatal_alert( + AlertDescription::IllegalParameter, + PeerMisbehaved::CipherSuiteDifferedOnRetry, + )); + } + } + debug!("decided upon suite {suite:?}"); cx.common.suite = Some(suite); cx.common.kx_state = KxState::Start(skxg); @@ -502,7 +518,7 @@ impl ExpectClientHello { transcript, suite, randoms, - done_retry: self.done_retry, + previous_hello: self.previous_hello, send_tickets: self.send_tickets, extra_exts: self.extra_exts, } @@ -659,6 +675,11 @@ impl ExpectClientHello { } } +pub(super) struct PreviousClientHello { + pub(super) offered_psk: bool, + pub(super) suite: CipherSuite, +} + impl State for ExpectClientHello { fn handle<'m>( self: Box, @@ -668,7 +689,8 @@ impl State for ExpectClientHello { where Self: 'm, { - let (client_hello, sig_schemes) = process_client_hello(&m, self.done_retry, cx)?; + let (client_hello, sig_schemes) = + process_client_hello(&m, self.previous_hello.is_some(), cx)?; self.with_certified_key(sig_schemes, client_hello, &m, cx) } diff --git a/rustls/src/server/server_conn.rs b/rustls/src/server/server_conn.rs index 77f03e484da..2cfd8b82c4a 100644 --- a/rustls/src/server/server_conn.rs +++ b/rustls/src/server/server_conn.rs @@ -13,9 +13,9 @@ use super::hs; #[cfg(feature = "std")] use crate::WantsVerifier; use crate::builder::ConfigBuilder; -use crate::common_state::{CommonState, Side}; #[cfg(feature = "std")] -use crate::common_state::{Protocol, State}; +use crate::common_state::State; +use crate::common_state::{CommonState, Protocol, Side}; use crate::conn::{ConnectionCommon, ConnectionCore, UnbufferedConnectionCommon}; #[cfg(doc)] use crate::crypto; @@ -398,6 +398,18 @@ pub struct ServerConfig { /// do any resumption. pub send_tls13_tickets: usize, + /// Upper bound on the number of TLS 1.3 tickets sent in response to a + /// client [RFC 9149] `ticket_request` extension. + /// + /// A client requesting `n` tickets receives `min(n, max_tls13_tickets)`. + /// Set to 0 to ignore client requests entirely (clients get + /// `send_tls13_tickets` regardless). + /// + /// The default is 0 (extension is ignored, preserving current behavior). + /// + /// [RFC 9149]: https://datatracker.ietf.org/doc/html/rfc9149 + pub max_tls13_tickets: usize, + /// If set to `true`, requires the client to support the extended /// master secret extraction method defined in [RFC 7627]. /// @@ -558,13 +570,14 @@ impl ServerConfig { /// We support a given TLS version if it's quoted in the configured /// versions *and* at least one ciphersuite for this version is /// also configured. - pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool { + pub(crate) fn supports_version(&self, v: ProtocolVersion, protocol: Protocol) -> bool { self.versions.contains(v) && self .provider .cipher_suites .iter() .any(|cs| cs.version().version == v) + && protocol.supports_version(v) } #[cfg(feature = "std")] @@ -623,7 +636,7 @@ mod connection { } #[cfg(read_buf)] - fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> { + fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_, u8>) -> io::Result<()> { self.early_data.read_buf(cursor) } } @@ -1167,7 +1180,7 @@ impl EarlyDataState { } #[cfg(read_buf)] - fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> { + fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_, u8>) -> io::Result<()> { match self { Self::Accepted { received, .. } => received.read_buf(cursor), _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)), @@ -1276,7 +1289,7 @@ mod tests { use core::io::BorrowedBuf; let mut buf = [0u8; 5]; - let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into(); + let mut buf: BorrowedBuf<'_, u8> = buf.as_mut_slice().into(); assert_eq!( format!("{:?}", EarlyDataState::default().read_buf(buf.unfilled())), "Err(Kind(BrokenPipe))" diff --git a/rustls/src/server/test.rs b/rustls/src/server/test.rs index e052736504b..0eb4e1e7754 100644 --- a/rustls/src/server/test.rs +++ b/rustls/src/server/test.rs @@ -72,12 +72,21 @@ mod tests { ActiveKeyExchange, CryptoProvider, KeyExchangeAlgorithm, SupportedKxGroup, }; use crate::enums::CertificateType; + use crate::msgs::codec::{Codec, Reader}; + use crate::msgs::handshake::{ + PresharedKeyBinder, PresharedKeyIdentity, PresharedKeyOffer, PskKeyExchangeModes, + }; + use crate::msgs::message::HEADER_SIZE; + use crate::msgs::persist; use crate::pki_types::pem::PemObject; use crate::pki_types::{CertificateDer, PrivateKeyDer}; use crate::server::{AlwaysResolvesServerRawPublicKeys, ServerConfig, ServerConnection}; use crate::sign::CertifiedKey; use crate::sync::Arc; - use crate::{CipherSuiteCommon, SupportedCipherSuite, Tls12CipherSuite, version}; + use crate::tls13::key_schedule::KeyScheduleEarly; + use crate::{ + CipherSuiteCommon, SupportedCipherSuite, Tls12CipherSuite, Tls13CipherSuite, version, + }; #[cfg(feature = "tls12")] #[test] @@ -240,6 +249,244 @@ mod tests { ); } + #[test] + fn second_client_hello_cannot_withdraw_psk_offer() { + // Per RFC 9846 section 4.2.2, dropping a PreSharedKey offer is not one of the + // changes a client may make after a HelloRetryRequest. + let config = + ServerConfig::builder_with_provider(super::provider::default_provider().into()) + .with_protocol_versions(&[&version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(server_cert(), server_key()) + .unwrap(); + let mut conn = ServerConnection::new(config.into()).unwrap(); + + let encode = |hello| { + Message { + version: ProtocolVersion::TLSv1_3, + payload: MessagePayload::handshake(HandshakeMessagePayload( + HandshakePayload::ClientHello(hello), + )), + } + .into_wire_bytes() + }; + + // this hello offers a PSK, but no key share for a group we support, so + // it draws a HelloRetryRequest. + let mut first = minimal_client_hello(); + first.extensions.key_shares = Some(vec![]); + first.extensions.preshared_key_modes = Some(PskKeyExchangeModes { + psk_dhe: true, + psk: false, + }); + first.extensions.preshared_key_offer = Some(PresharedKeyOffer::new( + PresharedKeyIdentity::new(vec![0u8; 16], 0), + vec![0u8; 32], + )); + conn.read_tls(&mut encode(first).as_slice()) + .unwrap(); + conn.process_new_packets().unwrap(); + + // the second hello follows the retry, but drops the PSK offer entirely. + let mut second = minimal_client_hello(); + second.extensions.preshared_key_modes = Some(PskKeyExchangeModes { + psk_dhe: true, + psk: false, + }); + conn.read_tls(&mut encode(second).as_slice()) + .unwrap(); + + assert_eq!( + conn.process_new_packets().unwrap_err(), + PeerMisbehaved::MissingPskExtensionInSecondClientHello.into(), + ); + } + + #[test] + fn second_client_hello_cannot_change_cipher_suite() { + // RFC 9846 section 4.2.4 requires the server to negotiate the same cipher suite it + // named in its HelloRetryRequest, and section 4.2.2 does not let the client vary its + // offer, so a second hello that withdraws the retried suite cannot be honoured. + let provider = CryptoProvider { + cipher_suites: vec![ + super::provider::cipher_suite::TLS13_AES_128_GCM_SHA256, + TLS13_AES_128_GCM_SHA256_ALT, + ], + ..super::provider::default_provider() + }; + let config = ServerConfig::builder_with_provider(provider.into()) + .with_protocol_versions(&[&version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(server_cert(), server_key()) + .unwrap(); + let mut conn = ServerConnection::new(config.into()).unwrap(); + + let encode = |hello| { + Message { + version: ProtocolVersion::TLSv1_3, + payload: MessagePayload::handshake(HandshakeMessagePayload( + HandshakePayload::ClientHello(hello), + )), + } + .into_wire_bytes() + }; + + // this hello has no key share for a group we support, so it draws a + // HelloRetryRequest naming `TLS13_AES_128_GCM_SHA256`. + let mut first = minimal_client_hello(); + first.cipher_suites = vec![CipherSuite::TLS13_AES_128_GCM_SHA256]; + first.extensions.key_shares = Some(vec![]); + conn.read_tls(&mut encode(first).as_slice()) + .unwrap(); + conn.process_new_packets().unwrap(); + + // the second hello follows the retry, but offers only a different suite. It shares + // the retried suite's hash, so the transcript stays valid and nothing else objects. + let mut second = minimal_client_hello(); + second.cipher_suites = vec![TLS13_AES_128_GCM_SHA256_ALT.suite()]; + conn.read_tls(&mut encode(second).as_slice()) + .unwrap(); + + assert_eq!( + conn.process_new_packets().unwrap_err(), + PeerMisbehaved::CipherSuiteDifferedOnRetry.into(), + ); + } + + #[test] + fn early_data_accepted_for_first_psk_identity() { + let (selected, early_data_accepted) = resume_with_early_data(0); + assert_eq!(selected, Some(0)); + assert!(early_data_accepted); + } + + #[test] + fn early_data_rejected_for_later_psk_identity() { + // RFC 9846 section 4.3.10: "In order to accept early data, the server MUST have + // accepted a PSK cipher suite and selected the first key offered in the client's + // "pre_shared_key" extension." The server may still resume with a later PSK. + let (selected, early_data_accepted) = resume_with_early_data(1); + assert_eq!(selected, Some(1)); + assert!(!early_data_accepted); + } + + /// Offer a resumable PSK at `index` (preceded by unknown identities) along with an + /// early data request, returning the selected PSK index and whether early data was accepted. + fn resume_with_early_data(index: usize) -> (Option, bool) { + // ensures X25519 is offered irrespective of cfg(feature = "fips"), to match + // `minimal_client_hello()` + let provider = CryptoProvider { + kx_groups: vec![super::provider::kx_group::X25519], + ..super::provider::default_provider() + }; + let mut config = ServerConfig::builder_with_provider(provider.into()) + .with_protocol_versions(&[&version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(server_cert(), server_key()) + .unwrap(); + config.max_early_data_size = 1024; + + let SupportedCipherSuite::Tls13(suite) = + super::provider::cipher_suite::TLS13_AES_128_GCM_SHA256 + else { + unreachable!(); + }; + + let secret = [0x42u8; 32]; + let ticket = b"resumable ticket"; + let session = persist::ServerSessionValue::new( + None, + ProtocolVersion::TLSv1_3, + suite.common.suite, + &secret, + None, + None, + vec![], + config.current_time().unwrap(), + 0, + ); + assert!( + config + .session_storage + .put(ticket.to_vec(), session.get_encoding()) + ); + + let binder_len = suite.common.hash_provider.output_len(); + let mut identities = vec![PresharedKeyIdentity::new(b"unknown ticket".to_vec(), 0); index]; + identities.push(PresharedKeyIdentity::new(ticket.to_vec(), 0)); + let binders = vec![PresharedKeyBinder::from(vec![0u8; binder_len]); identities.len()]; + + let mut ch = minimal_client_hello(); + ch.cipher_suites = vec![suite.common.suite]; + ch.extensions.preshared_key_modes = Some(PskKeyExchangeModes { + psk_dhe: true, + psk: false, + }); + ch.extensions.early_data_request = Some(()); + ch.extensions.preshared_key_offer = Some(PresharedKeyOffer { + identities, + binders, + }); + let mut hmp = HandshakeMessagePayload(HandshakePayload::ClientHello(ch)); + + // compute a genuine binder for the resumable PSK over the final ClientHello + let key_schedule = KeyScheduleEarly::new(suite, &secret); + let handshake_hash = suite + .common + .hash_provider + .hash(&hmp.encoding_for_binder_signing()); + let binder = key_schedule.resumption_psk_binder_key_and_sign_verify_data(&handshake_hash); + let HandshakePayload::ClientHello(ch) = &mut hmp.0 else { + unreachable!(); + }; + ch.preshared_key_offer + .as_mut() + .unwrap() + .binders[index] = PresharedKeyBinder::from(binder.as_ref().to_vec()); + + let ch = Message { + version: ProtocolVersion::TLSv1_3, + payload: MessagePayload::handshake(hmp), + }; + let mut conn = ServerConnection::new(config.into()).unwrap(); + conn.read_tls(&mut ch.into_wire_bytes().as_slice()) + .unwrap(); + conn.process_new_packets().unwrap(); + + let mut flight = vec![]; + conn.write_tls(&mut flight).unwrap(); + let mut r = Reader::init(&flight[HEADER_SIZE..]); + let HandshakeMessagePayload(HandshakePayload::ServerHello(server_hello)) = + HandshakeMessagePayload::read(&mut r).unwrap() + else { + panic!("expected ServerHello"); + }; + + ( + server_hello.extensions.preshared_key, + conn.early_data().is_some(), + ) + } + + static TLS13_AES_128_GCM_SHA256_ALT: SupportedCipherSuite = + SupportedCipherSuite::Tls13(&TLS13_AES_128_GCM_SHA256_ALT_INNER); + + /// Differs from `TLS13_AES_128_GCM_SHA256` only in its code point: same hash, same everything else. + static TLS13_AES_128_GCM_SHA256_ALT_INNER: Tls13CipherSuite = + match &super::provider::cipher_suite::TLS13_AES_128_GCM_SHA256 { + SupportedCipherSuite::Tls13(provider) => Tls13CipherSuite { + common: CipherSuiteCommon { + suite: CipherSuite::Unknown(0xff14), + ..provider.common + }, + ..**provider + }, + _ => unreachable!(), + }; + fn server_config_for_rpk() -> ServerConfig { let x25519_provider = CryptoProvider { kx_groups: vec![super::provider::kx_group::X25519], diff --git a/rustls/src/server/tls12.rs b/rustls/src/server/tls12.rs index d3dfa5c83dd..d617e1c68e6 100644 --- a/rustls/src/server/tls12.rs +++ b/rustls/src/server/tls12.rs @@ -407,7 +407,8 @@ mod client_hello { return Ok(false); } - let verify_schemes = client_auth.supported_verify_schemes(); + let mut verify_schemes = client_auth.supported_verify_schemes(); + verify_schemes.retain(|scheme| scheme.algorithm().is_some()); let names = config .verifier diff --git a/rustls/src/server/tls13.rs b/rustls/src/server/tls13.rs index b8b70e721a7..55e32f1e5bd 100644 --- a/rustls/src/server/tls13.rs +++ b/rustls/src/server/tls13.rs @@ -48,9 +48,11 @@ mod client_hello { use crate::msgs::handshake::{ CertificatePayloadTls13, CertificateRequestExtensions, CertificateRequestPayloadTls13, ClientHelloPayload, HelloRetryRequest, HelloRetryRequestExtensions, KeyShareEntry, Random, - ServerExtensions, ServerExtensionsInput, ServerHelloPayload, SessionId, + ServerExtensions, ServerExtensionsInput, ServerHelloPayload, ServerTicketRequestHint, + SessionId, }; use crate::server::common::ActiveCertifiedKey; + use crate::server::hs::PreviousClientHello; use crate::sign; use crate::tls13::key_schedule::{ KeyScheduleEarly, KeyScheduleHandshake, KeySchedulePreHandshake, @@ -69,7 +71,7 @@ mod client_hello { pub(in crate::server) transcript: HandshakeHash, pub(in crate::server) suite: &'static Tls13CipherSuite, pub(in crate::server) randoms: ConnectionRandoms, - pub(in crate::server) done_retry: bool, + pub(in crate::server) previous_hello: Option, pub(in crate::server) send_tickets: usize, pub(in crate::server) extra_exts: ServerExtensionsInput<'static>, } @@ -98,9 +100,10 @@ mod client_hello { binder: &[u8], ) -> bool { let binder_plaintext = match &client_hello.payload { - MessagePayload::Handshake { parsed, encoded } => { - &encoded.bytes()[..encoded.bytes().len() - parsed.total_binder_length()] - } + MessagePayload::Handshake { parsed, encoded } => &encoded.bytes()[..encoded + .bytes() + .len() + .saturating_sub(parsed.total_binder_length())], _ => unreachable!(), }; @@ -190,14 +193,29 @@ mod client_hello { .early_data_request .is_some(); - // EarlyData extension is illegal in second ClientHello - if self.done_retry && early_data_requested { - return Err({ - cx.common.send_fatal_alert( - AlertDescription::IllegalParameter, - PeerMisbehaved::EarlyDataAttemptedInSecondClientHello, - ) - }); + if let Some(prior) = &self.previous_hello { + // EarlyData extension is illegal in second ClientHello + if early_data_requested { + return Err({ + cx.common.send_fatal_alert( + AlertDescription::IllegalParameter, + PeerMisbehaved::EarlyDataAttemptedInSecondClientHello, + ) + }); + } + + // RFC 9846 section 4.2.2 allows the second ClientHello to update a PreSharedKey + // offer (binders, incompatible PSKs), but not to withdraw it altogether + if prior.offered_psk + && client_hello + .preshared_key_offer + .is_none() + { + return Err(cx.common.send_fatal_alert( + AlertDescription::MissingExtension, + PeerMisbehaved::MissingPskExtensionInSecondClientHello, + )); + } } // See if there is a KeyShare for the selected kx group. @@ -210,7 +228,7 @@ mod client_hello { // for the mutually_preferred_group. self.transcript.add_message(chm); - if self.done_retry { + if self.previous_hello.is_some() { return Err(cx.common.send_fatal_alert( AlertDescription::IllegalParameter, PeerMisbehaved::RefusedToFollowHelloRetryRequest, @@ -235,7 +253,12 @@ mod client_hello { session_id: SessionId::empty(), #[cfg(feature = "tls12")] using_ems: false, - done_retry: true, + previous_hello: Some(PreviousClientHello { + offered_psk: client_hello + .preshared_key_offer + .is_some(), + suite: self.suite.common.suite, + }), send_tickets: self.send_tickets, extra_exts: self.extra_exts, }); @@ -327,7 +350,22 @@ mod client_hello { chosen_psk_index = None; resumedata = None; } else { - self.send_tickets = self.config.send_tls13_tickets; + // RFC 9149: if the client sent a ticket_request extension and the + // server has configured a max, honor the client's request. + self.send_tickets = if self.config.max_tls13_tickets > 0 { + if let Some(req) = &client_hello.ticket_request { + let requested = usize::from(if resumedata.is_some() { + req.resumption_count + } else { + req.new_session_count + }); + Ord::min(requested, self.config.max_tls13_tickets) + } else { + self.config.send_tls13_tickets + } + } else { + self.config.send_tls13_tickets + }; } if let Some(resume) = &resumedata { @@ -352,7 +390,7 @@ mod client_hello { .map(|x| &x.master_secret.0[..]), &self.config, )?; - if !self.done_retry { + if !self.previous_hello.is_some() { emit_fake_ccs(cx.common); } @@ -372,9 +410,10 @@ mod client_hello { cx, &mut ocsp_response, client_hello, - resumedata.as_ref(), + chosen_psk_index.zip(resumedata.as_ref()), self.extra_exts, &self.config, + self.send_tickets, )?; let doing_client_auth = if full_handshake { @@ -610,7 +649,7 @@ mod client_hello { fn decide_if_early_data_allowed( cx: &mut ServerContext<'_>, client_hello: &ClientHelloPayload, - resumedata: Option<&persist::ServerSessionValue>, + resuming: Option<(usize, &persist::ServerSessionValue)>, suite: &'static Tls13CipherSuite, config: &ServerConfig, ) -> EarlyDataDecision { @@ -622,7 +661,7 @@ mod client_hello { false => EarlyDataDecision::Disabled, }; - let Some(resume) = resumedata else { + let Some((psk_index, resume)) = resuming else { // never any early data if not resuming. return rejected_or_disabled; }; @@ -646,8 +685,13 @@ mod client_hello { * - The selected cipher suite * - The selected ALPN [RFC7301] protocol, if any" * + * "In order to accept early data, the server MUST have accepted a PSK + * cipher suite and selected the first key offered in the client's + * "pre_shared_key" extension." + * * (RFC8446, 4.2.10) */ let early_data_possible = early_data_requested + && psk_index == 0 && resume.is_fresh() && Some(resume.version) == cx.common.negotiated_version && resume.cipher_suite == suite.common.suite @@ -671,14 +715,28 @@ mod client_hello { cx: &mut ServerContext<'_>, ocsp_response: &mut Option<&[u8]>, hello: &ClientHelloPayload, - resumedata: Option<&persist::ServerSessionValue>, + resuming: Option<(usize, &persist::ServerSessionValue)>, extra_exts: ServerExtensionsInput<'static>, config: &ServerConfig, + send_tickets: usize, ) -> Result { let mut ep = hs::ExtensionProcessing::new(extra_exts); - ep.process_common(config, cx, ocsp_response, hello, resumedata)?; + ep.process_common( + config, + cx, + ocsp_response, + hello, + resuming.map(|(_, session)| session), + )?; + + // RFC 9149: echo the expected ticket count if the client sent the extension. + if hello.ticket_request.is_some() && config.max_tls13_tickets > 0 { + ep.extensions.ticket_request = Some(ServerTicketRequestHint { + expected_count: Ord::min(send_tickets, usize::from(u8::MAX)) as u8, + }); + } - let early_data = decide_if_early_data_allowed(cx, hello, resumedata, suite, config); + let early_data = decide_if_early_data_allowed(cx, hello, resuming, suite, config); if early_data == EarlyDataDecision::Accepted { ep.extensions.early_data_ack = Some(()); } @@ -1040,6 +1098,17 @@ impl State for ExpectCertificate { HandshakePayload::CertificateTls13 )?; + // RFC 8446: the certificate_request_context in the client's Certificate + // must match the one in our CertificateRequest, which we always send + // empty. The client applies the mirror-image check to the server's + // Certificate. + if !certp.context.0.is_empty() { + return Err(cx.common.send_fatal_alert( + AlertDescription::DecodeError, + InvalidMessage::InvalidCertRequest, + )); + } + // We don't send any CertificateRequest extensions, so any extensions // here are illegal. if certp diff --git a/rustls/src/stream.rs b/rustls/src/stream.rs index 9de94db1b26..88b5937c281 100644 --- a/rustls/src/stream.rs +++ b/rustls/src/stream.rs @@ -1,5 +1,5 @@ use core::ops::{Deref, DerefMut}; -use std::io::{BufRead, IoSlice, Read, Result, Write}; +use std::io::{BufRead, ErrorKind, IoSlice, Read, Result, Write}; use crate::conn::{ConnectionCommon, SideData}; @@ -45,14 +45,22 @@ where } fn prepare_read(&mut self) -> Result<()> { + // Return buffered plaintext without doing any IO: `complete_io()` does not read + // while plaintext is buffered, so blocked writes would otherwise hide it. + if !self.conn.received_plaintext.is_empty() { + return Ok(()); + } + self.complete_prior_io()?; // We call complete_io() in a loop since a single call may read only - // a partial packet from the underlying transport. A full packet is - // needed to get more plaintext, which we must do if EOF has not been - // hit. + // a partial packet from the underlying transport, or may only write + // pending TLS data (like an alert queued while processing received + // records). A full packet is needed to get more plaintext, which we + // must do if EOF has not been hit. while self.conn.wants_read() { - if self.conn.complete_io(self.sock)?.0 == 0 { + let (read, written) = self.conn.complete_io(self.sock)?; + if read == 0 && written == 0 { break; } } @@ -82,7 +90,7 @@ where } #[cfg(read_buf)] - fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> Result<()> { + fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_, u8>) -> Result<()> { self.prepare_read()?; self.conn.reader().read_buf(cursor) } @@ -146,11 +154,24 @@ where fn flush(&mut self) -> Result<()> { self.complete_prior_io()?; - self.conn.writer().flush()?; - if self.conn.wants_write() { - self.conn.complete_io(self.sock)?; + // `complete_prior_io()` may return after making only partial progress, so + // keep writing until all TLS output has been handed to the transport. + while self.conn.wants_write() { + match self.conn.write_tls(self.sock) { + Ok(0) => return Err(ErrorKind::WriteZero.into()), + Ok(_) => {} + Err(err) if err.kind() == ErrorKind::Interrupted => {} + Err(err) => return Err(err), + } } - Ok(()) + + // Always flush the transport, even if we had no TLS output: an earlier + // flush (for example, from within `write()`) may have failed. + self.sock.flush()?; + + // Report any fatal error the connection encountered after an earlier `write()` + // had already accepted its plaintext (for example, while processing received data). + self.conn.writer().flush() } } @@ -225,7 +246,7 @@ where } #[cfg(read_buf)] - fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> Result<()> { + fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_, u8>) -> Result<()> { self.as_stream().read_buf(cursor) } } diff --git a/rustls/src/suites.rs b/rustls/src/suites.rs index aebe1a37661..097f9cb399c 100644 --- a/rustls/src/suites.rs +++ b/rustls/src/suites.rs @@ -92,7 +92,7 @@ impl SupportedCipherSuite { } /// Return the inner `Tls13CipherSuite` for this suite, if it is a TLS1.3 suite. - pub fn tls13(&self) -> Option<&'static Tls13CipherSuite> { + pub const fn tls13(&self) -> Option<&'static Tls13CipherSuite> { match self { #[cfg(feature = "tls12")] Self::Tls12(_) => None, @@ -118,7 +118,7 @@ impl SupportedCipherSuite { Self::Tls12(inner) => inner .sign .iter() - .any(|scheme| scheme.algorithm() == _sig_alg), + .any(|scheme| scheme.algorithm() == Some(_sig_alg)), } } @@ -181,10 +181,12 @@ pub(crate) fn compatible_sigscheme_for_suites( sigscheme: SignatureScheme, common_suites: &[SupportedCipherSuite], ) -> bool { - let sigalg = sigscheme.algorithm(); common_suites .iter() - .any(|&suite| suite.usable_for_signature_algorithm(sigalg)) + .any(|&suite| match sigscheme.algorithm() { + Some(sigalg) => suite.usable_for_signature_algorithm(sigalg), + None => suite.tls13().is_some(), + }) } /// Secrets for transmitting/receiving data over a TLS session. diff --git a/rustls/src/tls13/key_schedule.rs b/rustls/src/tls13/key_schedule.rs index 4bf04214674..7914ae2761e 100644 --- a/rustls/src/tls13/key_schedule.rs +++ b/rustls/src/tls13/key_schedule.rs @@ -533,6 +533,9 @@ impl KeyScheduleTraffic { common.send_msg_encrypt(Message::build_key_update_request().into()); let secret = self.next_application_traffic_secret(common.side); self.ks.set_encrypter(&secret, common); + // Sending the request with the exhausted keys asked for another update, + // which the new keys make unnecessary. + common.refresh_traffic_keys_pending = false; Ok(()) } diff --git a/rustls/src/vecbuf.rs b/rustls/src/vecbuf.rs index 8a4a1f3e4b8..c050a3018c7 100644 --- a/rustls/src/vecbuf.rs +++ b/rustls/src/vecbuf.rs @@ -103,7 +103,10 @@ impl ChunkVecBuffer { #[cfg(read_buf)] /// Read data out of this object, writing it into `cursor`. - pub(crate) fn read_buf(&mut self, mut cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> { + pub(crate) fn read_buf( + &mut self, + mut cursor: core::io::BorrowedCursor<'_, u8>, + ) -> io::Result<()> { while !self.is_empty() && cursor.capacity() > 0 { let chunk = &self.chunks[0][self.prefix_used..]; let used = cmp::min(chunk.len(), cursor.capacity()); @@ -302,7 +305,7 @@ mod tests { cvb.append(b"data".to_vec()); let mut buf = [MaybeUninit::::uninit(); 8]; - let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into(); + let mut buf: BorrowedBuf<'_, u8> = buf.as_mut_slice().into(); cvb.read_buf(buf.unfilled()).unwrap(); assert_eq!(buf.filled(), b"test fix"); buf.clear(); @@ -318,7 +321,7 @@ mod tests { cvb.append(b"short message".to_vec()); let mut buf = [MaybeUninit::::uninit(); 1024]; - let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into(); + let mut buf: BorrowedBuf<'_, u8> = buf.as_mut_slice().into(); cvb.read_buf(buf.unfilled()).unwrap(); assert_eq!(buf.filled(), b"short message"); } diff --git a/rustls/src/webpki/anchors.rs b/rustls/src/webpki/anchors.rs index b526ed252ab..01cefed19ff 100644 --- a/rustls/src/webpki/anchors.rs +++ b/rustls/src/webpki/anchors.rs @@ -118,7 +118,7 @@ impl Extend> for RootCertStore { impl fmt::Debug for RootCertStore { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RootCertStore") - .field("roots", &format!("({} roots)", &self.roots.len())) + .field("roots", &format!("({} roots)", self.roots.len())) .finish() } } diff --git a/rustls/src/webpki/verify.rs b/rustls/src/webpki/verify.rs index 5c3e79bede5..67cad4e74bd 100644 --- a/rustls/src/webpki/verify.rs +++ b/rustls/src/webpki/verify.rs @@ -158,6 +158,10 @@ pub fn verify_tls12_signature( dss: &DigitallySignedStruct, supported_schemes: &WebPkiSupportedAlgorithms, ) -> Result { + if dss.scheme.algorithm().is_none() { + return Err(PeerMisbehaved::SignedHandshakeWithUnadvertisedSigScheme.into()); + } + let possible_algs = supported_schemes.convert_scheme(dss.scheme)?; let cert = webpki::EndEntityCert::try_from(cert).map_err(pki_error)?; diff --git a/rustls/tests/api.rs b/rustls/tests/api.rs index cadb29696db..3df7d7aa64d 100644 --- a/rustls/tests/api.rs +++ b/rustls/tests/api.rs @@ -9,14 +9,25 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use std::{fmt, mem}; +#[cfg(feature = "aws_lc_rs")] +use pki_types::PrivateKeyDer; use pki_types::{CertificateDer, IpAddr, ServerName, UnixTime}; -use rustls::client::{ResolvesClientCert, Resumption, verify_server_cert_signed_by_trust_anchor}; +use rcgen::{ + CertificateParams, CertifiedIssuer, ExtendedKeyUsagePurpose, IsCa, KeyPair, KeyUsagePurpose, +}; +use rustls::client::{ + ResolvesClientCert, Resumption, TicketRequest, verify_server_cert_signed_by_trust_anchor, +}; +use rustls::crypto::cipher::{AeadKey, InboundOpaqueMessage, Iv}; +use rustls::crypto::tls13::{HkdfExpander, OkmBlock, expand}; use rustls::crypto::{ActiveKeyExchange, CryptoProvider, SharedSecret, SupportedKxGroup}; use rustls::internal::msgs::base::Payload; use rustls::internal::msgs::codec::Codec; use rustls::internal::msgs::enums::{AlertLevel, ExtensionType}; use rustls::internal::msgs::message::{Message, MessagePayload, PlainMessage}; -use rustls::server::{CertificateType, ClientHello, ParsedCertificate, ResolvesServerCert}; +use rustls::server::{ + Acceptor, CertificateType, ClientHello, ParsedCertificate, ResolvesServerCert, +}; use rustls::{ AlertDescription, CertificateError, CipherSuite, ClientConfig, ClientConnection, ConnectionCommon, ConnectionTrafficSecrets, ContentType, DistinguishedName, Error, @@ -27,7 +38,7 @@ use rustls::{ }; #[cfg(feature = "aws_lc_rs")] use rustls::{ - client::{EchConfig, EchGreaseConfig, EchMode}, + client::{EchConfig, EchGreaseConfig, EchMode, EchStatus}, crypto::aws_lc_rs::hpke::ALL_SUPPORTED_SUITES, internal::msgs::base::PayloadU16, internal::msgs::handshake::{ @@ -391,6 +402,67 @@ fn versions() { ); } +#[test] +fn server_does_not_negotiate_tls12_after_hrr() { + let (_, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + + // first client hello requires a HRR + server + .read_tls( + &mut encoding::message_framing( + ContentType::Handshake, + ProtocolVersion::TLSv1_2, + encoding::client_hello_with_extensions(vec![ + encoding::Extension::new_sig_algs(), + encoding::Extension::new_kx_groups(), + encoding::Extension::new_versions(), + encoding::Extension { + typ: ExtensionType::KeyShare, + body: vec![0, 0], + }, + ]), + ) + .as_slice(), + ) + .unwrap(); + server.process_new_packets().unwrap(); + + let mut server_output = Vec::new(); + server + .write_tls(&mut server_output) + .unwrap(); + assert!( + &server_output[11..43] == HRR_RANDOM_VALUE, + "server didn't reply with a HRR" + ); + + // second client hello only offers TLS1.2 + server + .read_tls( + &mut encoding::message_framing( + ContentType::Handshake, + ProtocolVersion::TLSv1_2, + encoding::client_hello_with_extensions(vec![ + encoding::Extension::new_sig_algs(), + encoding::Extension::new_kx_groups(), + ]), + ) + .as_slice(), + ) + .unwrap(); + assert_eq!( + server + .process_new_packets() + .unwrap_err(), + PeerIncompatible::SupportedVersionsExtensionRequired.into() + ); +} + +const HRR_RANDOM_VALUE: &[u8] = &[ + 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, + 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c, +]; + fn check_read(reader: &mut dyn io::Read, bytes: &[u8]) { let mut buf = vec![0u8; bytes.len() + 1]; assert_eq!(bytes.len(), reader.read(&mut buf).unwrap()); @@ -421,7 +493,7 @@ fn check_read_buf(reader: &mut dyn io::Read, bytes: &[u8]) { use std::mem::MaybeUninit; let mut buf = [MaybeUninit::::uninit(); 128]; - let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into(); + let mut buf: BorrowedBuf<'_, u8> = buf.as_mut_slice().into(); reader.read_buf(buf.unfilled()).unwrap(); assert_eq!(buf.filled(), bytes); } @@ -432,7 +504,7 @@ fn check_read_buf_err(reader: &mut dyn io::Read, err_kind: io::ErrorKind) { use std::mem::MaybeUninit; let mut buf = [MaybeUninit::::uninit(); 1]; - let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into(); + let mut buf: BorrowedBuf<'_, u8> = buf.as_mut_slice().into(); let err = reader .read_buf(buf.unfilled()) .unwrap_err(); @@ -1945,6 +2017,12 @@ fn default_signature_schemes(version: ProtocolVersion) -> Vec { SignatureScheme::RSA_PKCS1_SHA384, SignatureScheme::RSA_PKCS1_SHA256, ]); + } else if provider_is_aws_lc_rs() { + v.extend_from_slice(&[ + SignatureScheme::ML_DSA_44, + SignatureScheme::ML_DSA_65, + SignatureScheme::ML_DSA_87, + ]); } v @@ -2216,6 +2294,54 @@ fn server_error_is_sticky() { assert!(err.is_err()); } +#[test] +fn write_reports_sticky_error() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); + + // corrupt a record, so the server fails and sends a fatal alert + client + .writer() + .write_all(b"hello") + .unwrap(); + let mut client_output = Vec::new(); + client + .write_tls(&mut client_output) + .unwrap(); + *client_output.last_mut().unwrap() ^= 1; + server + .read_tls(&mut client_output.as_slice()) + .unwrap(); + assert_eq!(server.process_new_packets(), Err(Error::DecryptError)); + let mut server_output = Vec::new(); + server + .write_tls(&mut server_output) + .unwrap(); + + for data in [&b"world"[..], b""] { + let err = server.writer().write(data).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert_eq!(err.to_string(), Error::DecryptError.to_string()); + } + assert!(!server.wants_write()); + + // the client receives the alert, but has not sent one itself + client + .read_tls(&mut server_output.as_slice()) + .unwrap(); + let expected = Error::AlertReceived(AlertDescription::BadRecordMac); + assert_eq!(client.process_new_packets(), Err(expected.clone())); + assert!(!client.wants_write()); + + let err = client + .writer() + .write(b"world") + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert_eq!(err.to_string(), expected.to_string()); + assert!(!client.wants_write()); +} + #[test] fn server_flush_does_nothing() { let (_, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); @@ -3224,6 +3350,256 @@ fn stream_write_swallows_underlying_io_error_after_plaintext_processed() { assert_eq!(format!("{rc:?}"), "Ok(5)"); } +#[cfg(feature = "tls12")] +#[test] +fn client_stream_read_after_renegotiation_refusal() { + test_client_stream_read_after_renegotiation_refusal(StreamKind::Ref, ReadKind::Buf); + test_client_stream_read_after_renegotiation_refusal(StreamKind::Owned, ReadKind::Buf); + test_client_stream_read_after_renegotiation_refusal(StreamKind::Ref, ReadKind::BufRead); + test_client_stream_read_after_renegotiation_refusal(StreamKind::Owned, ReadKind::BufRead); +} + +/// Sending the `no_renegotiation` alert must not be mistaken for EOF. +/// +/// See . +#[cfg(feature = "tls12")] +fn test_client_stream_read_after_renegotiation_refusal( + stream_kind: StreamKind, + read_kind: ReadKind, +) { + let provider = provider::default_provider(); + let client_config = + make_client_config_with_versions(KeyType::Rsa2048, &[&rustls::version::TLS12], &provider); + let mut server_config = make_server_config(KeyType::Rsa2048, &provider); + server_config.enable_secret_extraction = true; + + let (mut client, mut server) = make_pair_for_configs(client_config, server_config); + do_handshake(&mut client, &mut server); + + let mut raw_server = RawTls::new_server(server); + let hello_request = raw_server.encrypt(&PlainMessage { + typ: ContentType::Handshake, + version: ProtocolVersion::TLSv1_2, + payload: Payload::new(encoding::handshake_framing( + HandshakeType::HelloRequest, + vec![], + )), + }); + + let data = b"world"; + let app_data = raw_server.encrypt(&PlainMessage { + typ: ContentType::ApplicationData, + version: ProtocolVersion::TLSv1_2, + payload: Payload::new(data.to_vec()), + }); + + // Deliver each record in its own read, followed by EOF, so the alert is + // written before any plaintext is available. + let mut pipe = TestNonBlockIo { + writes: vec![usize::MAX], + reads: vec![vec![], app_data, hello_request], + }; + + let stream: Box = match stream_kind { + StreamKind::Ref => Box::new(Stream::new(&mut client, &mut pipe)), + StreamKind::Owned => Box::new(StreamOwned::new(client, pipe)), + }; + + test_stream_read(read_kind, stream, data) +} + +#[test] +fn stream_flush_would_block_with_pending_output() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); + + client + .writer() + .write_all(b"hello") + .unwrap(); + let pending = client + .process_new_packets() + .unwrap() + .tls_bytes_to_write(); + + // the transport accepts a single byte, then blocks + let mut pipe = TestNonBlockIo { + writes: vec![1], + reads: vec![], + }; + let mut client_stream = Stream::new(&mut client, &mut pipe); + + assert_eq!( + client_stream + .flush() + .unwrap_err() + .kind(), + io::ErrorKind::WouldBlock + ); + assert_eq!( + client_stream + .conn + .process_new_packets() + .unwrap() + .tls_bytes_to_write(), + pending - 1 + ); + + client_stream + .sock + .writes + .push(usize::MAX); + client_stream.flush().unwrap(); + assert!(!client_stream.conn.wants_write()); +} + +#[test] +fn stream_flush_retries_failed_transport_flush() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); + + let mut pipe = FailsFirstFlush::default(); + let mut client_stream = Stream::new(&mut client, &mut pipe); + + // `write()` hands all TLS output to the transport, but ignores its flush failure + assert_eq!(client_stream.write(b"hello").unwrap(), 5); + assert!(!client_stream.conn.wants_write()); + assert!(!client_stream.sock.buffered.is_empty()); + + client_stream.flush().unwrap(); + assert!(client_stream.sock.buffered.is_empty()); + + server + .read_tls(&mut pipe.flushed.as_slice()) + .unwrap(); + server.process_new_packets().unwrap(); + check_read(&mut server.reader(), b"hello"); +} + +/// A buffering transport whose first `flush()` fails +#[derive(Default)] +struct FailsFirstFlush { + buffered: Vec, + flushed: Vec, + failed: bool, +} + +impl Read for FailsFirstFlush { + fn read(&mut self, _b: &mut [u8]) -> io::Result { + Err(io::ErrorKind::WouldBlock.into()) + } +} + +impl Write for FailsFirstFlush { + fn write(&mut self, b: &[u8]) -> io::Result { + self.buffered.extend_from_slice(b); + Ok(b.len()) + } + + fn flush(&mut self) -> io::Result<()> { + if !self.failed { + self.failed = true; + return Err(io::ErrorKind::Interrupted.into()); + } + + self.flushed.append(&mut self.buffered); + Ok(()) + } +} + +/// See . +#[test] +fn stream_reports_error_after_write_accepted_plaintext() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); + + server + .writer() + .write_all(b"hello") + .unwrap(); + let mut server_output = Vec::new(); + server + .write_tls(&mut server_output) + .unwrap(); + *server_output.last_mut().unwrap() ^= 1; + + // the transport blocks writes, so the first `write()` goes on to read the corrupt record + let mut pipe = TestNonBlockIo { + writes: vec![], + reads: vec![server_output], + }; + let mut client_stream = Stream::new(&mut client, &mut pipe); + + assert_eq!(client_stream.write(b"before").unwrap(), 6); + + // one write for each of the pending records: our data and the fatal alert + client_stream + .sock + .writes + .extend([usize::MAX, usize::MAX]); + let err = client_stream + .write(b"after") + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert_eq!(err.to_string(), Error::DecryptError.to_string()); + assert!(!client_stream.conn.wants_write()); + + let err = client_stream.flush().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert_eq!(err.to_string(), Error::DecryptError.to_string()); +} + +#[test] +fn stream_write_applies_backpressure_to_received_plaintext() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); + + // the peer sends several records, but never reads what we send + let mut reads = Vec::new(); + for _ in 0..3 { + server + .writer() + .write_all(b"hello") + .unwrap(); + let mut server_output = Vec::new(); + server + .write_tls(&mut server_output) + .unwrap(); + reads.insert(0, server_output); + } + + let mut pipe = TestNonBlockIo { + writes: vec![], + reads, + }; + let mut client_stream = Stream::new(&mut client, &mut pipe); + + // writing only reads more data while no received plaintext is buffered + assert_eq!(client_stream.write(b"world").unwrap(), 5); + for _ in 0..5 { + assert_eq!( + client_stream + .write(b"world") + .unwrap_err() + .kind(), + io::ErrorKind::WouldBlock + ); + } + assert_eq!( + client_stream + .conn + .process_new_packets() + .unwrap() + .plaintext_bytes_to_read(), + 5 + ); + + // buffered plaintext is still readable while writes are blocked + for _ in 0..3 { + check_read(&mut client_stream, b"hello"); + } +} + fn make_disjoint_suite_configs() -> (ClientConfig, ServerConfig) { let kt = KeyType::Rsa2048; let client_provider = CryptoProvider { @@ -4193,35 +4569,190 @@ fn key_log_for_tls13() { assert_eq!(client_resume_log[4], server_resume_log[5]); } +/// A TLS1.3 client must not accept `EncryptedExtensions` carried in the same +/// plaintext record as `ServerHello`. +/// +/// The server's first flight is rewritten so the complete `EncryptedExtensions` +/// message follows `ServerHello` in its unprotected record, and the remaining +/// handshake messages are re-encrypted under the server handshake traffic secret. +/// The transcript is unchanged, so only the key change alignment check can +/// catch this. #[test] -fn vectored_write_for_server_appdata() { - let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); - do_handshake(&mut client, &mut server); +fn client_rejects_encrypted_extensions_in_server_hello_record() { + let SupportedCipherSuite::Tls13(suite) = cipher_suite::TLS13_AES_256_GCM_SHA384 else { + unreachable!(); + }; + let provider = CryptoProvider { + cipher_suites: vec![cipher_suite::TLS13_AES_256_GCM_SHA384], + ..provider::default_provider() + }; + let kt = KeyType::Rsa2048; - server - .writer() - .write_all(b"01234567890123456789") - .unwrap(); - server - .writer() - .write_all(b"01234567890123456789") - .unwrap(); - { - let mut pipe = OtherSession::new(&mut client); - let wrlen = server.write_tls(&mut pipe).unwrap(); - assert_eq!(84, wrlen); - assert_eq!(pipe.writevs, vec![vec![42, 42]]); + let key_log = Arc::new(KeyLogToVec::new("server")); + let mut server_config = make_server_config(kt, &provider); + server_config.key_log = key_log.clone(); + let (mut client, mut server) = + make_pair_for_configs(make_client_config(kt, &provider), server_config); + + transfer(&mut client, &mut server); + server.process_new_packets().unwrap(); + let mut server_flight = Vec::new(); + while server.wants_write() { + server + .write_tls(&mut server_flight) + .unwrap(); } - check_read( - &mut client.reader(), - b"0123456789012345678901234567890123456789", + + let secret = key_log + .take() + .into_iter() + .find(|item| item.label == "SERVER_HANDSHAKE_TRAFFIC_SECRET") + .unwrap() + .secret; + let flight = move_encrypted_extensions_into_server_hello(&server_flight, suite, &secret); + + let mut rd = flight.as_slice(); + while !rd.is_empty() { + client.read_tls(&mut rd).unwrap(); + } + assert_eq!( + client + .process_new_packets() + .unwrap_err(), + PeerMisbehaved::KeyEpochWithPendingFragment.into() ); } -#[test] -fn vectored_write_for_client_appdata() { - let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); - do_handshake(&mut client, &mut server); +fn move_encrypted_extensions_into_server_hello( + flight: &[u8], + suite: &rustls::Tls13CipherSuite, + secret: &[u8], +) -> Vec { + let expander = suite + .hkdf_provider + .expander_for_okm(&OkmBlock::new(secret)); + let traffic_key = || -> (AeadKey, Iv) { + ( + hkdf_expand_label::(&*expander, b"key"), + hkdf_expand_label::(&*expander, b"iv"), + ) + }; + + let mut records = Vec::new(); + let mut rest = flight; + while !rest.is_empty() { + let len = u16::from_be_bytes([rest[3], rest[4]]) as usize; + records.push(rest[..5 + len].to_vec()); + rest = &rest[5 + len..]; + } + + let (key, iv) = traffic_key(); + let mut decrypter = suite.aead_alg.decrypter(key, iv); + let mut handshake = Vec::new(); + for (seq, record) in records + .iter_mut() + .filter(|record| ContentType::from(record[0]) == ContentType::ApplicationData) + .enumerate() + { + let decrypted = decrypter + .decrypt( + InboundOpaqueMessage::new( + ContentType::ApplicationData, + ProtocolVersion::TLSv1_2, + &mut record[5..], + ), + seq as u64, + ) + .unwrap(); + assert_eq!(decrypted.typ, ContentType::Handshake); + handshake.extend_from_slice(decrypted.payload); + } + + assert_eq!( + HandshakeType::from(handshake[0]), + HandshakeType::EncryptedExtensions + ); + let ee_len = 4 + u32::from_be_bytes([0, handshake[1], handshake[2], handshake[3]]) as usize; + let (encrypted_extensions, remainder) = handshake.split_at(ee_len); + + let mut output = Vec::new(); + for record in records + .iter() + .filter(|record| ContentType::from(record[0]) != ContentType::ApplicationData) + { + let mut body = record[5..].to_vec(); + if ContentType::from(record[0]) == ContentType::Handshake { + assert_eq!(HandshakeType::from(body[0]), HandshakeType::ServerHello); + body.extend_from_slice(encrypted_extensions); + } + output.extend(encoding::message_framing( + ContentType::from(record[0]), + ProtocolVersion::TLSv1_2, + body, + )); + } + + let (key, iv) = traffic_key(); + let mut encrypter = suite.aead_alg.encrypter(key, iv); + let remainder = PlainMessage { + typ: ContentType::Handshake, + version: ProtocolVersion::TLSv1_2, + payload: Payload::new(remainder.to_vec()), + }; + output.extend( + encrypter + .encrypt(remainder.borrow_outbound(), 0) + .unwrap() + .encode(), + ); + output +} + +fn hkdf_expand_label, const N: usize>( + expander: &dyn HkdfExpander, + label: &[u8], +) -> T { + expand( + expander, + &[ + &(N as u16).to_be_bytes(), + &[(b"tls13 ".len() + label.len()) as u8], + b"tls13 ", + label, + &[0], + ], + ) +} + +#[test] +fn vectored_write_for_server_appdata() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); + + server + .writer() + .write_all(b"01234567890123456789") + .unwrap(); + server + .writer() + .write_all(b"01234567890123456789") + .unwrap(); + { + let mut pipe = OtherSession::new(&mut client); + let wrlen = server.write_tls(&mut pipe).unwrap(); + assert_eq!(84, wrlen); + assert_eq!(pipe.writevs, vec![vec![42, 42]]); + } + check_read( + &mut client.reader(), + b"0123456789012345678901234567890123456789", + ); +} + +#[test] +fn vectored_write_for_client_appdata() { + let (mut client, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + do_handshake(&mut client, &mut server); client .writer() @@ -5008,6 +5539,7 @@ fn server_detects_excess_streamed_early_data() { mod test_quic { use rustls::quic::{self, ConnectionCommon}; + use rustls::{CipherSuiteCommon, Tls13CipherSuite}; use super::*; @@ -5382,6 +5914,57 @@ mod test_quic { } } + #[test] + fn test_quic_server_rejects_tls12_hello() { + let mut server = quic::ServerConnection::new( + Arc::new(make_server_config( + KeyType::EcdsaP256, + &provider::default_provider(), + )), + quic::Version::V2, + vec![], + ) + .unwrap(); + assert_eq!( + server + .read_hs(&encoding::client_hello( + ProtocolVersion::TLSv1_2, + &[0x12; 32], + &[0x00], + vec![CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256], + vec![encoding::Extension::new_sig_algs()], + )) + .err(), + Some(PeerIncompatible::Tls13RequiredForQuic.into()) + ); + } + + #[test] + fn test_quic_client_rejects_tls12_server() { + let mut client = quic::ClientConnection::new( + Arc::new(make_client_config( + KeyType::EcdsaP256, + &provider::default_provider(), + )), + quic::Version::V2, + "hello.com".try_into().unwrap(), + vec![], + ) + .unwrap(); + assert_eq!( + client + .read_hs(&encoding::server_hello( + ProtocolVersion::TLSv1_2, + &[0x12; 32], + &[0], + CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + vec![] + )) + .err(), + Some(PeerIncompatible::ServerTlsVersionIsDisabledByOurConfig.into()), + ); + } + #[test] fn test_quic_server_no_params_received() { let provider = provider::default_provider(); @@ -5434,11 +6017,76 @@ mod test_quic { assert_eq!( server.read_hs(buf.as_slice()).err(), Some(Error::PeerIncompatible( - PeerIncompatible::SupportedVersionsExtensionRequired + PeerIncompatible::Tls13RequiredForQuic )), ); } + #[test] + fn client_rejects_server_choosing_non_quic_suite() { + // we support [TLS13_AES_128_GCM_SHA256_WITHOUT_QUIC, TLS13_AES_256_GCM_SHA384]. our + // offer is [TLS13_AES_256_GCM_SHA384]. The server chooses TLS13_AES_128_GCM_SHA256_WITHOUT_QUIC + // which we should reject. + let provider = CryptoProvider { + cipher_suites: vec![ + TLS13_AES_128_GCM_SHA256_WITHOUT_QUIC, + provider::cipher_suite::TLS13_AES_256_GCM_SHA384, + ], + kx_groups: vec![provider::kx_group::SECP256R1], + ..provider::default_provider() + }; + let mut client = quic::ClientConnection::new( + Arc::new(make_client_config(KeyType::EcdsaP256, &provider)), + quic::Version::V2, + "hello.com".try_into().unwrap(), + vec![], + ) + .unwrap(); + assert_eq!( + client + .read_hs(&encoding::server_hello( + ProtocolVersion::TLSv1_2, + &[0x12; 32], + &[0], + CipherSuite::TLS13_AES_128_GCM_SHA256, + vec![ + encoding::Extension::new_versions_server_tls13(), + encoding::Extension::new_dummy_key_share_server() + ] + )) + .err(), + Some(PeerMisbehaved::SelectedUnofferedCipherSuite.into()), + ); + } + + /// TLS13_AES_128_GCM_SHA256 which doesn't support QUIC. + /// + /// Once `clone` is const this can be more directly written. + const TLS13_AES_128_GCM_SHA256_WITHOUT_QUIC: SupportedCipherSuite = + SupportedCipherSuite::Tls13(&Tls13CipherSuite { + common: CipherSuiteCommon { + suite: TLS13_AES_128_GCM_SHA256_INNER + .common + .suite, + hash_provider: TLS13_AES_128_GCM_SHA256_INNER + .common + .hash_provider, + confidentiality_limit: TLS13_AES_128_GCM_SHA256_INNER + .common + .confidentiality_limit, + }, + hkdf_provider: TLS13_AES_128_GCM_SHA256_INNER.hkdf_provider, + aead_alg: TLS13_AES_128_GCM_SHA256_INNER.aead_alg, + quic: None, + }); + + /// nb. `Option::unwrap` is not const until rust 1.83. + const TLS13_AES_128_GCM_SHA256_INNER: &Tls13CipherSuite = + match provider::cipher_suite::TLS13_AES_128_GCM_SHA256.tls13() { + Some(inner) => inner, + None => unreachable!(), + }; + #[test] fn packet_key_api() { use cipher_suite::TLS13_AES_128_GCM_SHA256; @@ -6380,8 +7028,6 @@ fn test_client_tls12_no_resume_after_server_downgrade() { #[test] fn test_acceptor() { - use rustls::server::Acceptor; - let provider = provider::default_provider(); let client_config = Arc::new(make_client_config(KeyType::Ed25519, &provider)); let mut client = ClientConnection::new(client_config, server_name("localhost")).unwrap(); @@ -6483,9 +7129,101 @@ fn test_acceptor() { } #[test] -fn test_acceptor_rejected_handshake() { - use rustls::server::Acceptor; +fn client_hello_acceptor_rejects_record_containing_subsequent_messages() { + let mut hello = encoding::basic_client_hello(vec![]); + hello.extend(encoding::handshake_framing( + HandshakeType::EncryptedExtensions, + vec![0, 0], + )); + hello.extend(encoding::handshake_framing( + HandshakeType::Finished, + vec![0; 32], + )); + let hello = encoding::message_framing(ContentType::Handshake, ProtocolVersion::TLSv1_2, hello); + let mut acceptor = Acceptor::default(); + acceptor + .read_tls(&mut hello.as_slice()) + .unwrap(); + let (err, mut alert) = acceptor.accept().unwrap_err(); + assert_eq!(err, PeerMisbehaved::KeyEpochWithPendingFragment.into()); + let mut alert_content = Vec::new(); + let _ = alert.write(&mut alert_content); + assert_eq!( + alert_content, + build_alert(AlertLevel::Fatal, AlertDescription::UnexpectedMessage, &[]) + ); +} + +#[test] +fn client_connection_rejects_record_containing_subsequent_messages() { + let mut server_flight = encoding::server_hello( + ProtocolVersion::TLSv1_2, + &[b'a'; 32], + &[0], + CipherSuite::TLS13_AES_128_GCM_SHA256, + vec![ + encoding::Extension::new_versions_server_tls13(), + encoding::Extension::new_dummy_key_share_server(), + ], + ); + server_flight.extend(encoding::handshake_framing( + HandshakeType::EncryptedExtensions, + vec![0, 0], + )); + server_flight.extend(encoding::handshake_framing( + HandshakeType::Finished, + vec![0; 32], + )); + let server_flight = encoding::message_framing( + ContentType::Handshake, + ProtocolVersion::TLSv1_2, + server_flight, + ); + + let provider = CryptoProvider { + kx_groups: vec![provider::kx_group::SECP256R1], + ..provider::default_provider() + }; + let (mut client, _) = make_pair(KeyType::Rsa2048, &provider); + client + .read_tls(&mut server_flight.as_slice()) + .unwrap(); + assert_eq!( + client + .process_new_packets() + .unwrap_err(), + PeerMisbehaved::KeyEpochWithPendingFragment.into() + ); +} + +#[test] +fn server_connection_rejects_record_containing_subsequent_messages() { + let mut client_flight = encoding::basic_client_hello(vec![]); + client_flight.extend(encoding::handshake_framing( + HandshakeType::Finished, + vec![0; 32], + )); + let client_flight = encoding::message_framing( + ContentType::Handshake, + ProtocolVersion::TLSv1_2, + client_flight, + ); + + let (_, mut server) = make_pair(KeyType::Rsa2048, &provider::default_provider()); + server + .read_tls(&mut client_flight.as_slice()) + .unwrap(); + assert_eq!( + server + .process_new_packets() + .unwrap_err(), + PeerMisbehaved::KeyEpochWithPendingFragment.into() + ); +} + +#[test] +fn test_acceptor_rejected_handshake() { let client_config = finish_client_config( KeyType::Ed25519, ClientConfig::builder_with_provider(provider::default_provider().into()) @@ -7184,6 +7922,77 @@ fn test_client_fips_service_indicator_includes_ech_hpke_suite() { } } +#[cfg(feature = "aws_lc_rs")] +#[test] +fn test_client_sends_no_application_data_after_ech_rejection() { + // The server has no ECH keys, so it rejects ECH and completes the outer handshake + // with a certificate that is valid for the ECH config's `public_name` only. + let suite = ALL_SUPPORTED_SUITES[0]; + let (public_key, _) = suite.generate_key_pair().unwrap(); + let suite_id = suite.suite(); + let config = EchConfigPayload::V18(EchConfigContents { + key_config: HpkeKeyConfig { + config_id: 0, + kem_id: suite_id.kem, + public_key: PayloadU16::new(public_key.0.clone()), + symmetric_cipher_suites: vec![HpkeSymmetricCipherSuite { + kdf_id: suite_id.sym.kdf_id, + aead_id: suite_id.sym.aead_id, + }], + }, + maximum_name_length: 0, + public_name: DnsName::try_from("testserver.com").unwrap(), + extensions: vec![], + }); + let mut config_bytes = Vec::new(); + vec![config].encode(&mut config_bytes); + let ech_config = EchConfig::new(EchConfigListBytes::from(config_bytes), &[suite]).unwrap(); + + let provider = provider::default_provider(); + let client_config = ClientConfig::builder_with_provider(provider.clone().into()) + .with_ech(EchMode::Enable(ech_config)) + .unwrap(); + let client_config = finish_client_config(KeyType::Rsa2048, client_config); + let server_config = make_server_config(KeyType::Rsa2048, &provider); + + let mut client = + ClientConnection::new(Arc::new(client_config), server_name("private.example")).unwrap(); + let mut server = ServerConnection::new(Arc::new(server_config)).unwrap(); + + // Application data written before the handshake completes is buffered until then. + client + .writer() + .write_all(b"ech-inner-secret") + .unwrap(); + + let err = do_handshake_until_error(&mut client, &mut server).unwrap_err(); + assert!(matches!( + err, + ErrorFromPeer::Client(Error::PeerIncompatible( + PeerIncompatible::ServerRejectedEncryptedClientHello(_) + )) + )); + assert_eq!(client.ech_status(), EchStatus::Rejected); + + // The connection is only authenticated for the `public_name`, so it must not become + // usable for application data intended for the inner server name. + assert!(client.is_handshaking()); + assert!(client.refresh_traffic_keys().is_err()); + + transfer(&mut client, &mut server); + assert_eq!( + server + .process_new_packets() + .unwrap_err(), + Error::AlertReceived(AlertDescription::EncryptedClientHelloRequired) + ); + let mut server_received = Vec::new(); + let _ = server + .reader() + .read_to_end(&mut server_received); + assert!(server_received.is_empty()); +} + #[test] fn test_complete_io_errors_if_close_notify_received_too_early() { let mut server = ServerConnection::new(Arc::new(make_server_config( @@ -7598,6 +8407,29 @@ fn test_cert_decompression_by_server_produces_invalid_cert_payload() { ); } +#[test] +fn test_cert_decompression_by_server_rejects_nonempty_context() { + let provider = provider::default_provider(); + let mut server_config = + make_server_config_with_mandatory_client_auth(KeyType::Rsa2048, &provider); + server_config.cert_decompressors = vec![&NonEmptyContextDecompressor]; + let mut client_config = make_client_config_with_auth(KeyType::Rsa2048, &provider); + client_config.cert_compressors = vec![&IdentityCompressor]; + + let (mut client, mut server) = make_pair_for_configs(client_config, server_config); + assert_eq!( + do_handshake_until_error(&mut client, &mut server), + Err(ErrorFromPeer::Server(Error::InvalidMessage( + InvalidMessage::InvalidCertRequest + ))) + ); + transfer(&mut server, &mut client); + assert_eq!( + client.process_new_packets(), + Err(Error::AlertReceived(AlertDescription::DecodeError)) + ); +} + #[test] fn test_cert_decompression_by_server_fails() { let provider = provider::default_provider(); @@ -7669,6 +8501,37 @@ impl rustls::compress::CertDecompressor for GarbageDecompressor { } } +#[derive(Debug)] +struct NonEmptyContextDecompressor; + +impl rustls::compress::CertDecompressor for NonEmptyContextDecompressor { + fn decompress( + &self, + _input: &[u8], + output: &mut [u8], + ) -> Result<(), rustls::compress::DecompressionFailed> { + // Emit a syntactically valid `CertificatePayloadTls13` whose + // certificate_request_context is one byte long instead of empty, + // followed by a single certificate entry sized to fill `output`. A + // server following RFC 8446 must reject the non-empty context. + let Some(cert_len) = output.len().checked_sub(10) else { + return Err(rustls::compress::DecompressionFailed); + }; + let mut buf = Vec::with_capacity(output.len()); + buf.extend_from_slice(&[1, 0]); // certificate_request_context: length 1 (non-empty) + buf.extend_from_slice(&((cert_len + 5) as u32).to_be_bytes()[1..]); // certificate_list length (u24) + buf.extend_from_slice(&(cert_len as u32).to_be_bytes()[1..]); // cert_data length (u24) + buf.resize(buf.len() + cert_len, 0); // cert_data + buf.extend_from_slice(&[0, 0]); // per-entry extensions length + output.copy_from_slice(&buf); + Ok(()) + } + + fn algorithm(&self) -> rustls::CertificateCompressionAlgorithm { + rustls::CertificateCompressionAlgorithm::Zlib + } +} + #[derive(Debug)] struct FailingDecompressor; @@ -7953,11 +8816,14 @@ fn test_automatic_refresh_traffic_keys() { server.process_new_packets().unwrap() ); - // at CONFIDENTIALITY_LIMIT messages, we also have a key_update message sent + // the key_update message takes the last record allowed under the initial key, + // so it is sent before the message that would otherwise take that record assert_eq!( transferred, match i { - CONFIDENTIALITY_LIMIT => KEY_UPDATE_SIZE + encrypted_size(message.len()), + i if i == CONFIDENTIALITY_LIMIT - 1 => { + KEY_UPDATE_SIZE + encrypted_size(message.len()) + } _ => encrypted_size(message.len()), } ); @@ -7983,17 +8849,22 @@ fn test_automatic_refresh_traffic_keys() { assert_eq!(transferred, KEY_UPDATE_SIZE + encrypted_size(message.len())); } -#[cfg(feature = "tls12")] #[test] -fn tls12_connection_fails_after_key_reaches_confidentiality_limit() { - let provider = aes_128_gcm_with_1024_confidentiality_limit(provider::default_provider()); +fn tls13_keys_are_updated_within_fragmented_write() { + // With this maximum fragment size, each record carries 27 bytes of plaintext + // and encrypts to 44 bytes, while an encrypted key_update message is 22 bytes. + const RECORD_PLAINTEXT_LEN: usize = 27; + const KEY_UPDATE_LEN: usize = 22; - let client_config = finish_client_config( + let provider = aes_128_gcm_with_1024_confidentiality_limit(provider::default_provider()); + let mut client_config = finish_client_config( KeyType::Ed25519, ClientConfig::builder_with_provider(provider.clone()) - .with_protocol_versions(&[&rustls::version::TLS12]) + .with_protocol_versions(&[&rustls::version::TLS13]) .unwrap(), ); + client_config.max_fragment_size = Some(32); + client_config.enable_secret_extraction = true; let server_config = finish_server_config( KeyType::Ed25519, ServerConfig::builder_with_provider(provider) @@ -8004,30 +8875,214 @@ fn tls12_connection_fails_after_key_reaches_confidentiality_limit() { let (mut client, mut server) = make_pair_for_configs(client_config, server_config); do_handshake(&mut client, &mut server); + // A single write of enough records to exhaust the traffic keys twice over. + let records = 2 * CONFIDENTIALITY_LIMIT as usize + 1; + let payload = vec![0x42; records * RECORD_PLAINTEXT_LEN]; + client.set_buffer_limit(None); + assert_eq!(client.writer().write(&payload).unwrap(), payload.len()); + + let mut client_output = Vec::new(); + while client.wants_write() { + client + .write_tls(&mut client_output) + .unwrap(); + } + + let mut key_updates = Vec::new(); + let mut index = 0; + let mut wire = client_output.as_slice(); + while !wire.is_empty() { + let len = usize::from(u16::from_be_bytes([wire[3], wire[4]])); + if len == KEY_UPDATE_LEN { + key_updates.push(index); + } + wire = &wire[5 + len..]; + index += 1; + } + + // Each key_update message takes the last record allowed under the previous keys. + let limit = CONFIDENTIALITY_LIMIT as usize; + assert_eq!(key_updates, [limit - 1, 2 * limit - 1]); + assert_eq!(index, records + 2); + + let mut received = Vec::new(); + let mut wire = client_output.as_slice(); + while !wire.is_empty() { + server.read_tls(&mut wire).unwrap(); + let state = server.process_new_packets().unwrap(); + let mut buf = vec![0u8; state.plaintext_bytes_to_read()]; + server + .reader() + .read_exact(&mut buf) + .unwrap(); + received.extend(buf); + } + assert_eq!(received, payload); + + // The remaining records were encrypted under the newest keys. + let secrets = client + .dangerous_extract_secrets() + .unwrap(); + assert_eq!( + secrets.tx.0, + records as u64 - 2 * (CONFIDENTIALITY_LIMIT - 1) + ); +} + +#[cfg(feature = "tls12")] +#[test] +fn tls12_connection_fails_after_key_reaches_confidentiality_limit() { + let (mut client, mut server) = tls12_pair_with_limited_confidentiality(); + for i in 0..CONFIDENTIALITY_LIMIT { let message = format!("{i:08}"); client .writer() .write_all(message.as_bytes()) .unwrap(); - let transferred = transfer(&mut client, &mut server); - println!( - "{}: {} -> {:?}", - i, - transferred, - server.process_new_packets().unwrap() - ); - - let mut buf = [0u8; 32]; - let recvd = server.reader().read(&mut buf).unwrap(); + let (received, peer_closed) = receive(&mut client, &mut server); match i { - 1023 => assert_eq!(recvd, 0), - _ => assert_eq!(&buf[..recvd], message.as_bytes()), + 1023 => { + assert!(peer_closed); + assert_eq!(received.len(), 0); + } + _ => { + assert!(!peer_closed); + assert_eq!(&received, message.as_bytes()); + } } } } +#[cfg(feature = "tls12")] +#[test] +fn tls12_connection_fails_after_alert_at_confidentiality_limit() { + let (mut client, mut server) = tls12_pair_with_limited_confidentiality(); + + for i in 1..CONFIDENTIALITY_LIMIT { + let message = format!("{i:08}"); + client + .writer() + .write_all(message.as_bytes()) + .unwrap(); + let (received, peer_closed) = receive(&mut client, &mut server); + assert!(!peer_closed); + assert_eq!(&received, message.as_bytes()); + } + + // Alerts are not subject to the limit, so the client's rejection of a renegotiation + // request takes the last sequence number before it. + let mut raw_server = RawTls::new_server(server); + let hello_request = PlainMessage { + typ: ContentType::Handshake, + version: ProtocolVersion::TLSv1_2, + payload: Payload::new(encoding::handshake_framing( + HandshakeType::HelloRequest, + vec![], + )), + }; + raw_server.encrypt_and_send(&hello_request, &mut client); + client.process_new_packets().unwrap(); + raw_server.receive_and_decrypt(&mut client, |m| { + assert_eq!( + format!("{m:?}"), + "Message { version: TLSv1_2, payload: Alert(AlertMessagePayload { level: Warning, description: NoRenegotiation }) }" + ); + }); + + // No application data may be encrypted with the exhausted key. + client + .writer() + .write_all(b"later") + .unwrap(); + raw_server.receive_and_decrypt(&mut client, |m| { + assert_eq!( + format!("{m:?}"), + "Message { version: TLSv1_2, payload: Alert(AlertMessagePayload { level: Warning, description: CloseNotify }) }" + ); + }); +} + +#[cfg(feature = "tls12")] +#[test] +fn tls12_write_is_not_split_across_confidentiality_limit() { + let (mut client, mut server) = tls12_pair_with_limited_confidentiality(); + + // Leave three records before the limit. + for i in 1..CONFIDENTIALITY_LIMIT - 3 { + let message = format!("{i:08}"); + client + .writer() + .write_all(message.as_bytes()) + .unwrap(); + let (received, peer_closed) = receive(&mut client, &mut server); + assert!(!peer_closed); + assert_eq!(&received, message.as_bytes()); + } + + // A write that fits in the remaining records is sent in full. + let two_records = vec![b'a'; MAX_FRAGMENT_LEN + 1]; + client + .writer() + .write_all(&two_records) + .unwrap(); + let (received, peer_closed) = receive(&mut client, &mut server); + assert!(!peer_closed); + assert_eq!(received, two_records); + + // With one record left, none of a two-record write is sent. + client + .writer() + .write_all(&two_records) + .unwrap(); + let (received, peer_closed) = receive(&mut client, &mut server); + assert!(peer_closed); + assert_eq!(received.len(), 0); +} + +/// Complete a TLS 1.2 handshake using a suite limited to [`CONFIDENTIALITY_LIMIT`] records. +/// +/// The client's `Finished` message used sequence number 0. The server has secret extraction +/// enabled. +#[cfg(feature = "tls12")] +fn tls12_pair_with_limited_confidentiality() -> (ClientConnection, ServerConnection) { + let provider = aes_128_gcm_with_1024_confidentiality_limit(provider::default_provider()); + + let client_config = finish_client_config( + KeyType::Ed25519, + ClientConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS12]) + .unwrap(), + ); + let mut server_config = finish_server_config( + KeyType::Ed25519, + ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap(), + ); + server_config.enable_secret_extraction = true; + + let (mut client, mut server) = make_pair_for_configs(client_config, server_config); + do_handshake(&mut client, &mut server); + (client, server) +} + +/// Deliver the client's pending TLS data to the server. +/// +/// Returns the application data received, and whether the client has closed. +#[cfg(feature = "tls12")] +fn receive(client: &mut ClientConnection, server: &mut ServerConnection) -> (Vec, bool) { + transfer(client, server); + let state = server.process_new_packets().unwrap(); + let mut received = vec![0u8; state.plaintext_bytes_to_read()]; + server + .reader() + .read_exact(&mut received) + .unwrap(); + (received, state.peer_has_closed()) +} + #[test] fn test_keys_match_for_all_signing_key_types() { let provider = provider::default_provider(); @@ -8183,3 +9238,186 @@ impl ActiveKeyExchange for FakeHybridActive { } const CONFIDENTIALITY_LIMIT: u64 = 1024; + +/// Default maximum plaintext length of a record. +#[cfg(feature = "tls12")] +const MAX_FRAGMENT_LEN: usize = 16_384; + +#[test] +fn tls13_ticket_request_new_vs_resumed() { + let provider = provider::default_provider(); + let shared_storage = Arc::new(ClientStorage::new()); + + let mut client_config = + make_client_config_with_versions(KeyType::Rsa2048, &[&rustls::version::TLS13], &provider); + client_config.resumption = Resumption::store(shared_storage.clone()); + client_config.send_ticket_request = Some(TicketRequest { + new_session_count: 3, + resumption_count: 1, + }); + let client_config = Arc::new(client_config); + + let mut server_config = make_server_config(KeyType::Rsa2048, &provider); + server_config.max_tls13_tickets = 5; + let server_config = Arc::new(server_config); + + // new connection: server sends new_session_count (3) + let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); + do_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(HandshakeKind::Full)); + + let ops = shared_storage.ops_and_reset(); + let ticket_inserts = ops + .iter() + .filter(|op| matches!(op, ClientStorageOp::InsertTls13Ticket(_))) + .count(); + assert_eq!(ticket_inserts, 3); + + // resumed connection: server sends resumption_count (1) + let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); + do_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(HandshakeKind::Resumed)); + + let ops = shared_storage.ops_and_reset(); + let ticket_inserts = ops + .iter() + .filter(|op| matches!(op, ClientStorageOp::InsertTls13Ticket(_))) + .count(); + assert_eq!(ticket_inserts, 1); +} + +#[test] +fn tls13_ticket_request_zero_means_no_tickets() { + let provider = provider::default_provider(); + let shared_storage = Arc::new(ClientStorage::new()); + + let mut client_config = + make_client_config_with_versions(KeyType::Rsa2048, &[&rustls::version::TLS13], &provider); + client_config.resumption = Resumption::store(shared_storage.clone()); + client_config.send_ticket_request = Some(TicketRequest { + new_session_count: 0, + resumption_count: 0, + }); + let client_config = Arc::new(client_config); + + let mut server_config = make_server_config(KeyType::Rsa2048, &provider); + server_config.max_tls13_tickets = 5; + let server_config = Arc::new(server_config); + + let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); + do_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(HandshakeKind::Full)); + + let ops = shared_storage.ops_and_reset(); + let ticket_inserts = ops + .iter() + .filter(|op| matches!(op, ClientStorageOp::InsertTls13Ticket(_))) + .count(); + assert_eq!(ticket_inserts, 0); +} + +#[test] +fn tls13_ticket_request_capped_by_server() { + let provider = provider::default_provider(); + let shared_storage = Arc::new(ClientStorage::new()); + + let mut client_config = + make_client_config_with_versions(KeyType::Rsa2048, &[&rustls::version::TLS13], &provider); + client_config.resumption = Resumption::store(shared_storage.clone()); + client_config.send_ticket_request = Some(TicketRequest { + new_session_count: 10, + resumption_count: 10, + }); + let client_config = Arc::new(client_config); + + let mut server_config = make_server_config(KeyType::Rsa2048, &provider); + server_config.max_tls13_tickets = 3; + let server_config = Arc::new(server_config); + + let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); + do_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(HandshakeKind::Full)); + + let ops = shared_storage.ops_and_reset(); + let ticket_inserts = ops + .iter() + .filter(|op| matches!(op, ClientStorageOp::InsertTls13Ticket(_))) + .count(); + assert_eq!(ticket_inserts, 3); +} + +#[test] +fn tls13_ticket_request_not_sent_when_none() { + let provider = provider::default_provider(); + let shared_storage = Arc::new(ClientStorage::new()); + + let mut client_config = + make_client_config_with_versions(KeyType::Rsa2048, &[&rustls::version::TLS13], &provider); + client_config.resumption = Resumption::store(shared_storage.clone()); + client_config.send_ticket_request = None; + let client_config = Arc::new(client_config); + + let mut server_config = make_server_config(KeyType::Rsa2048, &provider); + server_config.max_tls13_tickets = 8; + let server_config = Arc::new(server_config); + + // without the extension, server uses send_tls13_tickets (default 2) + let (mut client, mut server) = make_pair_for_arc_configs(&client_config, &server_config); + do_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(HandshakeKind::Full)); + + let ops = shared_storage.ops_and_reset(); + let ticket_inserts = ops + .iter() + .filter(|op| matches!(op, ClientStorageOp::InsertTls13Ticket(_))) + .count(); + assert_eq!(ticket_inserts, 2); +} + +#[cfg(feature = "aws_lc_rs")] +#[test] +fn ml_dsa() { + if !provider_is_aws_lc_rs() { + return; + } + + let ca_key = KeyPair::generate_for(&rcgen::PKCS_ML_DSA_44).unwrap(); + let mut ca_params = CertificateParams::new(vec!["Test CA".into()]).unwrap(); + ca_params.is_ca = IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + ca_params.key_usages = vec![ + KeyUsagePurpose::DigitalSignature, + KeyUsagePurpose::KeyCertSign, + ]; + ca_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + let issuer = CertifiedIssuer::self_signed(ca_params, ca_key).unwrap(); + + let ee_key = KeyPair::generate_for(&rcgen::PKCS_ML_DSA_87).unwrap(); + let ee_params = CertificateParams::new(vec!["localhost".into()]).unwrap(); + let ee_cert = ee_params + .signed_by(&ee_key, &issuer) + .unwrap(); + + let provider = Arc::new(provider::default_provider()); + let server_config = ServerConfig::builder_with_provider(provider.clone()) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![ee_cert.der().clone()], + PrivateKeyDer::try_from(ee_key.serialize_der()).unwrap(), + ) + .unwrap(); + + let mut roots = RootCertStore::empty(); + roots.add(issuer.der().clone()).unwrap(); + let client_config = ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + + let mut client = + ClientConnection::new(Arc::new(client_config), "localhost".try_into().unwrap()).unwrap(); + let mut server = ServerConnection::new(Arc::new(server_config)).unwrap(); + do_handshake(&mut client, &mut server); +} diff --git a/rustls/tests/bogo.rs b/rustls/tests/bogo.rs index 297a6d744d4..06595dc9d7e 100644 --- a/rustls/tests/bogo.rs +++ b/rustls/tests/bogo.rs @@ -20,12 +20,6 @@ fn run_bogo_tests_aws_lc_rs_fips() { run_bogo_tests("aws-lc-rs-fips"); } -#[test] -#[ignore] -fn run_bogo_tests_post_quantum() { - run_bogo_tests("post-quantum"); -} - fn run_bogo_tests(provider: &str) { use std::process::Command; diff --git a/rustls/tests/unbuffered.rs b/rustls/tests/unbuffered.rs index d7e6b632a60..63e0894e285 100644 --- a/rustls/tests/unbuffered.rs +++ b/rustls/tests/unbuffered.rs @@ -746,7 +746,7 @@ fn refresh_traffic_keys_automatically() { const KEY_UPDATE_SIZE: usize = encrypted_size(5); const CONFIDENTIALITY_LIMIT: usize = 1024; - const CONFIDENTIALITY_LIMIT_PLUS_ONE: usize = CONFIDENTIALITY_LIMIT + 1; + const CONFIDENTIALITY_LIMIT_MINUS_ONE: usize = CONFIDENTIALITY_LIMIT - 1; let client_config = finish_client_config( KeyType::Rsa2048, @@ -786,8 +786,10 @@ fn refresh_traffic_keys_automatically() { assert_eq!( used, match i { - // The key_update message triggered by write N appears in write N+1 - CONFIDENTIALITY_LIMIT_PLUS_ONE => + // the key_update message takes the last record allowed under + // the initial key, so it is sent before the message that would + // otherwise take that record + CONFIDENTIALITY_LIMIT_MINUS_ONE => KEY_UPDATE_SIZE + encrypted_size(message.len()), _ => encrypted_size(message.len()), } diff --git a/tokio-rustls-smoke/Cargo.toml b/tokio-rustls-smoke/Cargo.toml deleted file mode 100644 index d7fa76f4205..00000000000 --- a/tokio-rustls-smoke/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "tokio-rustls-smoke" -version = "0.0.0" -edition = "2021" -publish = false - -[dependencies] -rcgen = { workspace = true } -rustls = { path = "../rustls" } -tokio = { version = "1.52.3", features = ["io-util", "macros", "rt"] } -tokio-rustls = "0.26.4" diff --git a/tokio-rustls-smoke/src/lib.rs b/tokio-rustls-smoke/src/lib.rs deleted file mode 100644 index a6ee5c44cef..00000000000 --- a/tokio-rustls-smoke/src/lib.rs +++ /dev/null @@ -1,105 +0,0 @@ -#[cfg(test)] -mod tests { - use std::io; - use std::sync::Arc; - - use rcgen::{CertifiedKey, generate_simple_self_signed}; - use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; - use rustls::pki_types::{ - CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime, - }; - use rustls::{ClientConfig, DigitallySignedStruct, Error, ServerConfig}; - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - use tokio_rustls::{TlsAcceptor, TlsConnector}; - - #[derive(Debug)] - struct AcceptAnyServerCert; - - impl ServerCertVerifier for AcceptAnyServerCert { - fn verify_server_cert( - &self, - _end_entity: &CertificateDer<'_>, - _intermediates: &[CertificateDer<'_>], - _server_name: &ServerName<'_>, - _ocsp_response: &[u8], - _now: UnixTime, - ) -> Result { - Ok(ServerCertVerified::assertion()) - } - - fn verify_tls12_signature( - &self, - _message: &[u8], - _cert: &CertificateDer<'_>, - _dss: &DigitallySignedStruct, - ) -> Result { - Ok(HandshakeSignatureValid::assertion()) - } - - fn verify_tls13_signature( - &self, - _message: &[u8], - _cert: &CertificateDer<'_>, - _dss: &DigitallySignedStruct, - ) -> Result { - Ok(HandshakeSignatureValid::assertion()) - } - - fn supported_verify_schemes(&self) -> Vec { - rustls::crypto::aws_lc_rs::default_provider() - .signature_verification_algorithms - .supported_schemes() - } - } - - #[tokio::test] - async fn tokio_rustls_connector_uses_local_rustls_fork() -> io::Result<()> { - let CertifiedKey { cert, signing_key } = - generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); - let cert_chain = vec![CertificateDer::from(cert.der().to_vec())]; - let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(signing_key.serialize_der())); - - let server_config = ServerConfig::builder() - .with_no_client_auth() - .with_single_cert(cert_chain, key) - .unwrap(); - - let client_config = ClientConfig::builder() - .dangerous() - .with_custom_certificate_verifier(Arc::new(AcceptAnyServerCert)) - .with_no_client_auth(); - - let acceptor = TlsAcceptor::from(Arc::new(server_config)); - let connector = TlsConnector::from(Arc::new(client_config)); - let (client_io, server_io) = tokio::io::duplex(4096); - - let server = tokio::spawn(async move { - let mut stream = acceptor - .accept(server_io) - .await - .unwrap(); - let mut request = [0u8; 4]; - stream - .read_exact(&mut request) - .await - .unwrap(); - assert_eq!(&request, b"ping"); - stream.write_all(b"pong").await.unwrap(); - }); - - let mut client = connector - .connect(ServerName::try_from("localhost").unwrap(), client_io) - .await - .unwrap(); - client.write_all(b"ping").await.unwrap(); - let mut response = [0u8; 4]; - client - .read_exact(&mut response) - .await - .unwrap(); - assert_eq!(&response, b"pong"); - - server.await.unwrap(); - Ok(()) - } -}