diff --git a/Cargo.lock b/Cargo.lock index 4525066..37d07ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2067,8 +2067,6 @@ dependencies = [ [[package]] name = "dimpl" version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07d467d37bfdcc290bb8dcbedc8ca356eb730e46459b1687f98c3bae28aa6814" dependencies = [ "aes 0.8.4", "arrayvec", diff --git a/Cargo.toml b/Cargo.toml index 74c34d0..4fe7be0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,8 @@ [workspace] resolver = "3" -exclude = ["fuzz"] +# third_party: vendored crates patched in below (not workspace members, so +# their own tests and dev-dependencies stay out of our builds). +exclude = ["fuzz", "third_party"] members = [ "crates/proto/tsproto-types", "crates/proto/tsproto-structs", @@ -88,3 +90,8 @@ debug = "line-tables-only" [profile.dev.package."*"] debug = false + +# dimpl (DTLS for str0m), vendored to be patched; see +# third_party/dimpl/VOELIN-PATCH.md. +[patch.crates-io] +dimpl = { path = "third_party/dimpl" } diff --git a/scripts/own-crates.sh b/scripts/own-crates.sh index 9e770db..087baf4 100755 --- a/scripts/own-crates.sh +++ b/scripts/own-crates.sh @@ -1,10 +1,10 @@ #!/usr/bin/env bash # Print `-p ` for every workspace crate outside the vendored crates/proto -# (manifest paths with / or \ separators, for Windows), +# and third_party (manifest paths with / or \ separators, for Windows), # for commands that apply strict checks to our own code only: # cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps -- -D warnings set -euo pipefail cd "$(dirname "$0")/.." cargo metadata --no-deps --format-version 1 | - jq -r '.packages[] | select(.manifest_path | gsub("\\\\"; "/") | contains("/crates/proto/") | not) | "-p \(.name)"' | + jq -r '.packages[] | select(.manifest_path | gsub("\\\\"; "/") | (contains("/crates/proto/") or contains("/third_party/")) | not) | "-p \(.name)"' | tr '\n' ' ' diff --git a/third_party/dimpl/.cargo/config.toml b/third_party/dimpl/.cargo/config.toml new file mode 100644 index 0000000..d4e3992 --- /dev/null +++ b/third_party/dimpl/.cargo/config.toml @@ -0,0 +1,2 @@ +[env] +MACOSX_DEPLOYMENT_TARGET = "11.0" diff --git a/third_party/dimpl/.cargo_vcs_info.json b/third_party/dimpl/.cargo_vcs_info.json new file mode 100644 index 0000000..dc30900 --- /dev/null +++ b/third_party/dimpl/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "09bf3fc89c3cdb06030a90e8e1043983c791e2b6" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/third_party/dimpl/.github/workflows/cargo.yml b/third_party/dimpl/.github/workflows/cargo.yml new file mode 100644 index 0000000..f4aad51 --- /dev/null +++ b/third_party/dimpl/.github/workflows/cargo.yml @@ -0,0 +1,85 @@ +name: CI +permissions: + contents: read + +on: + push: + branches: ["main"] + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + rust: [stable, beta, 1.85.0] + feature: ["aws-lc-rs", "rust-crypto", "rcgen", ""] + + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v6 + - uses: dtolnay/rust-toolchain@v1 + id: toolchain + with: + toolchain: ${{ matrix.rust }} + - uses: Swatinem/rust-cache@v2 + - name: Install autotools (macOS) + if: runner.os == 'macOS' + run: brew install autoconf automake libtool + - name: Set MACOSX_DEPLOYMENT_TARGET + if: runner.os == 'macOS' + run: echo "MACOSX_DEPLOYMENT_TARGET=$(sw_vers -productVersion | cut -d. -f1)" >> $GITHUB_ENV + - name: Build + run: cargo +${{steps.toolchain.outputs.name}} build --no-default-features --features "${{ matrix.feature }}" + - name: Test + if: matrix.feature == 'aws-lc-rs' || matrix.feature == 'rust-crypto' + run: cargo +${{steps.toolchain.outputs.name}} test --no-default-features --features "${{ matrix.feature }}" + + snowflake: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + - name: Martin's snowflake formatting rules + uses: algesten/snowflake@v1.0.4 + with: + check_diff: true + line_width_rules: "CHANGELOG.md:120;c_cpp_properties.json:160;Cargo.toml:199;README.md:180;README.tpl:180;*.md:110;*.rs:110;*.toml:110;DEFAULT=110" + + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: dtolnay/rust-toolchain@v1 + id: toolchain + with: + toolchain: stable + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - name: fmt + run: cargo +${{steps.toolchain.outputs.name}} fmt --all -- --check + - name: clippy + run: cargo +${{steps.toolchain.outputs.name}} clippy -- -D warnings + - uses: dtolnay/rust-toolchain@v1 + with: + toolchain: stable + components: clippy + - name: doc + run: cargo doc --no-deps + env: + RUSTDOCFLAGS: -Dwarnings + + cargo-deny: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: EmbarkStudios/cargo-deny-action@v2 + with: + command: check + arguments: --all-features diff --git a/third_party/dimpl/.github/workflows/codeql.yml b/third_party/dimpl/.github/workflows/codeql.yml new file mode 100644 index 0000000..76fce1f --- /dev/null +++ b/third_party/dimpl/.github/workflows/codeql.yml @@ -0,0 +1,101 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL Advanced" + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + schedule: + - cron: '39 9 * * 5' + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners (GitHub.com only) + # Consider using larger runners or machines with greater resources for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + permissions: + # required for all workflows + security-events: write + + # required to fetch internal or private CodeQL packs + packages: read + + # only required for workflows in private repositories + actions: read + contents: read + + strategy: + fail-fast: false + matrix: + include: + - language: actions + build-mode: none + - language: rust + build-mode: none + # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift' + # Use `c-cpp` to analyze code written in C, C++ or both + # Use 'java-kotlin' to analyze code written in Java, Kotlin or both + # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both + # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, + # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. + # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how + # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + # Add any setup steps before running the `github/codeql-action/init` action. + # This includes steps like installing compilers or runtimes (`actions/setup-node` + # or others). This is typically only required for manual builds. + # - name: Setup runtime (example) + # uses: actions/setup-example@v1 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + config: | + query-filters: + - exclude: + id: rust/hard-coded-cryptographic-value + - exclude: + id: rust/cleartext-logging-of-sensitive-information + + # If the analyze step fails for one of the languages you are analyzing with + # "We were unable to automatically build your code", modify the matrix above + # to set the build mode to "manual" for that language. Then modify this step + # to build your code. + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + - name: Run manual build steps + if: matrix.build-mode == 'manual' + shell: bash + run: | + echo 'If you are using a "manual" build mode for one or more of the' \ + 'languages you are analyzing, replace this with the commands to build' \ + 'your code, for example:' + echo ' make bootstrap' + echo ' make release' + exit 1 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + with: + category: "/language:${{matrix.language}}" diff --git a/third_party/dimpl/.github/workflows/fuzz.yml b/third_party/dimpl/.github/workflows/fuzz.yml new file mode 100644 index 0000000..4e1fa16 --- /dev/null +++ b/third_party/dimpl/.github/workflows/fuzz.yml @@ -0,0 +1,55 @@ +name: Fuzz + +on: + push: + branches: ['main'] + pull_request: + # Allow manual trigger + workflow_dispatch: + # Run fuzz tests daily + schedule: + - cron: '0 0 * * *' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + fuzz: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + target: + - fuzz_dtls_packet + - fuzz_record_parse + - fuzz_dtls13_packet + - fuzz_dtls13_record_parse + steps: + - uses: actions/checkout@v6 + - uses: dtolnay/rust-toolchain@v1 + with: + toolchain: nightly + - name: Install cargo-fuzz + run: cargo install cargo-fuzz + - name: Cache fuzz corpus + uses: actions/cache@v5 + with: + path: fuzz/corpus + key: fuzz-corpus-${{ matrix.target }}-${{ github.sha }} + restore-keys: | + fuzz-corpus-${{ matrix.target }}- + - name: Run fuzz target + run: | + cargo fuzz run ${{ matrix.target }} -- \ + -max_total_time=60 \ + -max_len=65536 + - name: Upload crash artifacts + if: failure() + uses: actions/upload-artifact@v7 + with: + name: crash-${{ matrix.target }} + path: fuzz/artifacts/${{ matrix.target }}/ diff --git a/third_party/dimpl/.gitignore b/third_party/dimpl/.gitignore new file mode 100644 index 0000000..6246eaa --- /dev/null +++ b/third_party/dimpl/.gitignore @@ -0,0 +1,2 @@ +/target +.wt diff --git a/third_party/dimpl/.taplo.toml b/third_party/dimpl/.taplo.toml new file mode 100644 index 0000000..7cd36c7 --- /dev/null +++ b/third_party/dimpl/.taplo.toml @@ -0,0 +1,8 @@ +# Taplo TOML formatter configuration +[formatting] +# Set column width to 150 before line breaking +column_width = 150 +# Prevent automatic array expansion - keep arrays compact unless they exceed column_width +array_auto_expand = false +# Keep arrays on single line if they fit within column_width +array_auto_collapse = true diff --git a/third_party/dimpl/.vscode/settings.json b/third_party/dimpl/.vscode/settings.json new file mode 100644 index 0000000..4d9636b --- /dev/null +++ b/third_party/dimpl/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "rust-analyzer.showUnlinkedFileNotification": false +} \ No newline at end of file diff --git a/third_party/dimpl/AGENTS.md b/third_party/dimpl/AGENTS.md new file mode 100644 index 0000000..1825850 --- /dev/null +++ b/third_party/dimpl/AGENTS.md @@ -0,0 +1,130 @@ +# CLAUDE.md + +Code style guide for Claude sessions working on dimpl. + +## File Ordering + +1. Imports +2. Constants +3. Primary type (matches module name: `foo.rs` → `struct Foo`) +4. Related types, ordered by first appearance in primary type's fields/variants +5. `impl` block for primary type +6. Helper types and functions +7. Standard trait impls (`Display`, `Debug`, `From`) +8. Tests (`#[cfg(test)] mod tests`) + +Example: `struct Foo { bar: Bar, baz: Baz }` → define `Bar` before `Baz`. + +## State Machine Files (client.rs, server.rs) + +Protocol flow dictates ordering throughout: + +1. Module-level comment documenting the protocol flow +2. Imports +3. Primary struct (`Client` / `Server`) +4. `State` enum (variants in protocol order) +5. `impl PrimaryType` (public API: `new`, `handle_*`, `poll_*`) +6. `impl State` (`name()`, `make_progress()`, then handlers in enum order) +7. Free helper functions (ordered by first use in protocol flow) + +## Imports + +Group: std → external → crate. Alphabetical within groups. + +```rust +use std::collections::VecDeque; +use std::time::Instant; + +use arrayvec::ArrayVec; + +use crate::buffer::Buf; +use crate::engine::Engine; +``` + +Use short paths: `std::Vec` not `std::vec::Vec`. + +## Modules + +Private modules with selective re-exports: + +```rust +mod certificate; +pub use certificate::Certificate; +``` + +## Visibility + +Prefer `pub` over `pub(crate)`. Only use `pub(crate)` when explicitly preventing +items from becoming part of the public API. Internal modules that are kept private +by their parent don't need `pub(crate)` on their items. + +```rust +// Good: parent module is private, so pub here won't leak +mod internal { + pub struct Helper; // Not in public API because `internal` is private +} + +// Bad: unnecessary restriction +mod internal { + pub(crate) struct Helper; // Redundant - parent already private +} +``` + +## Fields and Methods + +Fields are private. Expose via getter methods. + +## Documentation + +Doc examples must compile and run as tests. Never use `ignore`. Use `no_run` only +when hardware/network required. + +## Unwrap + +Comment `unwrap()` calls explaining why they're safe: + +```rust +// unwrap: is ok because we set the random in handle_timeout +let random = self.random.unwrap(); +``` + +## Sans-IO API Contract + +dimpl is Sans-IO: no sockets, no threads, no async. The caller drives I/O. + +**Poll-to-Timeout Rule**: Every mutation (`handle_packet`, `handle_timeout`) must +be followed by polling until `Output::Timeout`: + +```rust +client.handle_timeout(now); +loop { + match client.poll_output(&mut buf) { + Output::Packet(data) => { /* send to peer */ } + Output::Connected => { /* handshake complete */ } + Output::Timeout(when) => break, + } +} +``` + +Never stop polling early. Internal state is only consistent after reaching `Timeout`. + +## Memory + +**Summary**: Allocation-conscious design - pool reuse, single-copy, in-place +mutation, boxing for ABI, bounded stack collections. + +**Buffer Pooling** +- Reuse allocations instead of malloc/free per packet +- Clear contents but retain capacity + +**Single-Copy Parsing** +- One copy from network into working buffer +- Parse and decrypt in-place on that buffer + +**ABI Optimization** +- Box large inner data so outer structs fit in registers +- Avoids memmove on function calls + +**Bounded Stack Collections** +- Fixed-capacity arrays for small, known-bounded collections +- Fail explicitly if bounds exceeded diff --git a/third_party/dimpl/CHANGELOG.md b/third_party/dimpl/CHANGELOG.md new file mode 100644 index 0000000..82d4fbb --- /dev/null +++ b/third_party/dimpl/CHANGELOG.md @@ -0,0 +1,175 @@ +# Unreleased + +# 0.7.4 + + * Preserve DTLS 1.3 client key shares on cookie-only retries #163 + +# 0.7.3 + + * Fix DTLS 1.2 ClientHello retransmissions #160 + +# 0.7.2 + + * Stop advertising unsupported RSA signatures in DTLS 1.2 CertificateRequest #157 + +# 0.7.1 + + * Add `Dtls::is_closing()` and `Dtls::is_closed()` shutdown predicates #155 + +# 0.7.0 + + * Omit empty DTLS 1.3 CertificateRequest certificate authorities #153 + * Fix DTLS handshake defragmentation across message sequences #151 + * Return `BufferTooSmall` instead of panicking on undersized poll buffers #150 + * Fix DTLS 1.3 RFC 9147 conformance issues #147 + * Reject malformed fragmented DTLS handshakes before consuming fragments #144 + * Represent DTLS wire-code identifiers as compact newtypes (breaking) #137 + * Make public errors structured and fatal-only (breaking) #134 + +# 0.6.2 + + * Split local DTLS invalid-state errors from peer-input errors #126 + * Reject malformed DTLS 1.3 ClientHello extension vectors #133 + * Reject malformed DTLS 1.3 KeyUpdate bodies #131 + * Reject malformed DTLS 1.3 ACK record-number vectors #130 + * Parse DTLS 1.2-only ClientHellos for auto-sense fallback #129 + * Reject malformed DTLS 1.3 Cookie extension bodies #128 + * Reject oversized DTLS 1.2 CertificateRequest certificate authorities #127 + * Bound DTLS 1.3 ACK tracking during handshake replacement #120 + * Stop DTLS 1.2 flight resends once the peer handshake is confirmed #125 + * Drop plaintext DTLS 1.3 ACKs and alerts after peer encryption #118 + * Reject oversized DTLS extension vectors #119 + * Replace pending DTLS 1.2 handshake output on resend #116 + * Discard bad protected DTLS 1.2 records after handshake #115 + * Reject oversized DTLS certificate lists #113 + * Reject duplicate supported DTLS extensions #114 + * Reject malformed DTLS signature_algorithms vectors #111 + * Discard short DTLS 1.2 and 1.3 encrypted records #112 + * Drop late retransmitted DTLS 1.2 CCS after handshake #110 + +# 0.6.1 + + * Fix auto-sense server falling back to DTLS 1.2 on non-ClientHello parse errors #106 + +# 0.6.0 + + * Implement graceful shutdown #91 + * Add PSK (Pre-Shared Key) cipher suite `PSK_AES128_CCM_8` for DTLS 1.2 (breaking) #92 + * Fix DTLS 1.2 signature hash mismatch for P-384 keys #97 + +# 0.5.0 + + * Remove PrfProvider/HkdfProvider, derive from HmacProvider (breaking) #94 + +# 0.4.3 + + * Fix server auto-sensing DTLS version with fragmented ClientHello #87 + * DTLS 1.2 DTLS 1.3, parser reject ApplicationData in epoch 0/plaintext #90 + * DTLS 1.3 reject plaintext records with non-zero epoch #90 + * Silently discard invalid records and process subsequent valid records #90 + +# 0.4.2 + + * Downgrade rand to 0.9 to avoid double chacha20 dep #84 + +# 0.4.1 (yanked) + + * Edition 2024 and bump deps (big cargo fmt) #83 + * Add DTLS 1.2 ChaCha20 and X25519 support #77 + * Bump MSRV to 1.85.0 #75 + * Make cipher and kx configurable #73 + +# 0.4.0 + + * Restrict DTLS 1.2 key exchange to P-256/P-384 (for now) #70 + * Add AEAD, encrypt_sn, and key exchange validation to CryptoProvider #68 + * Add #[non_exhaustive] to public API enums likely to grow (breaking) #69 + * feat: Add protocol_version() accessor to Dtls #59 + * Bump all deps (possible with the current MSRV) #67 + * DTLS1.3 chacha20poly1305 and x25519 support #64 + * Fix panic in auto DTLS version selection #65 + * Add `Error::HandshakePending` for auto-sense pending state (breaking) #65 + * DTLS 1.2 ECDSA determine curve from certificate, not hash algorithm #57 + * DTLS 1.3 enforce SignatureScheme curve matches certificate key #60 + +# 0.3.0 + + * DTLS 1.3 (breaking) #53 + * Refactor all/known/supported() (breaking) #55 + * Require now: Instant in Dtls::new() instead of panicking #54 + +# 0.2.7 + + * Ensure compiling without features pulls in no deps #52 + +# 0.2.6 + + * Fix ClientHello parser failing due to incorrect is_known method logic + +# 0.2.5 + + * Fix ClientHello Parser Failing when too many Cipher Suites #46 + +# 0.2.4 + + * Drop dupe handshakes to not block newer messages #44 + +# 0.2.3 + + * Fix DTLS HelloVerifyRequest by clearing queue_rx after sending HVR #40 + * Configurable RNG seed for tests #41 + +# 0.2.2 + + * Add debug warn! for ReceiveQueueFull error #39 + +# 0.2.1 + + * Fix DTLS protocol version in HelloVerifyRequest #36 + * Handle multiple Handshake in one Record #36 + * dimpl is not compatible with aws-lc-rs < 1.14 #35 + +# 0.2.0 + + * Add fuzz testing to #32 + * Re-export Aad and Nonce that was missing #30 + * Add CodeQL analysis workflow configuration #27 + * Constant time equality #26 + * Pluggable CryptoProvider #16 + * aws-lc-rs backend (default) + * rust-crypto backend (pure Rust) + +# 0.1.5 + + * Optimize parse speed using Box #14 + * Replace self_cell with indexes #14 + * Fix bug not retuning pooled Buf #14 + * Replace tinyvec with arrayvec #14 + * Remove zeroize - for now #13 + +# 0.1.4 + + * Replace RustCrypto with aws-lc-rs #12 + * Fix SRTP key to include client_random and server_random #11 + * Make generated certs compatible with Firefox #11 + +# 0.1.3 + + * Fixes to extension parsing #10 + * Better connection/flight timers #9 + * Remove rcgen/ring dependency #8 + +# 0.1.2 + + * Bump MSRV to 1.81.0 #7 + * Bump rand to 0.9.x #7 + +# 0.1.1 + + * Remove Diffie-Hellman (since no RSA) #6 + * Add github actions as CI #5 + * Fix bad MTU packing causing flaky tests #4 + * Remove ciphers using RSA #3 + +# 0.1.0 + * First published version diff --git a/third_party/dimpl/CLAUDE.md b/third_party/dimpl/CLAUDE.md new file mode 100644 index 0000000..1825850 --- /dev/null +++ b/third_party/dimpl/CLAUDE.md @@ -0,0 +1,130 @@ +# CLAUDE.md + +Code style guide for Claude sessions working on dimpl. + +## File Ordering + +1. Imports +2. Constants +3. Primary type (matches module name: `foo.rs` → `struct Foo`) +4. Related types, ordered by first appearance in primary type's fields/variants +5. `impl` block for primary type +6. Helper types and functions +7. Standard trait impls (`Display`, `Debug`, `From`) +8. Tests (`#[cfg(test)] mod tests`) + +Example: `struct Foo { bar: Bar, baz: Baz }` → define `Bar` before `Baz`. + +## State Machine Files (client.rs, server.rs) + +Protocol flow dictates ordering throughout: + +1. Module-level comment documenting the protocol flow +2. Imports +3. Primary struct (`Client` / `Server`) +4. `State` enum (variants in protocol order) +5. `impl PrimaryType` (public API: `new`, `handle_*`, `poll_*`) +6. `impl State` (`name()`, `make_progress()`, then handlers in enum order) +7. Free helper functions (ordered by first use in protocol flow) + +## Imports + +Group: std → external → crate. Alphabetical within groups. + +```rust +use std::collections::VecDeque; +use std::time::Instant; + +use arrayvec::ArrayVec; + +use crate::buffer::Buf; +use crate::engine::Engine; +``` + +Use short paths: `std::Vec` not `std::vec::Vec`. + +## Modules + +Private modules with selective re-exports: + +```rust +mod certificate; +pub use certificate::Certificate; +``` + +## Visibility + +Prefer `pub` over `pub(crate)`. Only use `pub(crate)` when explicitly preventing +items from becoming part of the public API. Internal modules that are kept private +by their parent don't need `pub(crate)` on their items. + +```rust +// Good: parent module is private, so pub here won't leak +mod internal { + pub struct Helper; // Not in public API because `internal` is private +} + +// Bad: unnecessary restriction +mod internal { + pub(crate) struct Helper; // Redundant - parent already private +} +``` + +## Fields and Methods + +Fields are private. Expose via getter methods. + +## Documentation + +Doc examples must compile and run as tests. Never use `ignore`. Use `no_run` only +when hardware/network required. + +## Unwrap + +Comment `unwrap()` calls explaining why they're safe: + +```rust +// unwrap: is ok because we set the random in handle_timeout +let random = self.random.unwrap(); +``` + +## Sans-IO API Contract + +dimpl is Sans-IO: no sockets, no threads, no async. The caller drives I/O. + +**Poll-to-Timeout Rule**: Every mutation (`handle_packet`, `handle_timeout`) must +be followed by polling until `Output::Timeout`: + +```rust +client.handle_timeout(now); +loop { + match client.poll_output(&mut buf) { + Output::Packet(data) => { /* send to peer */ } + Output::Connected => { /* handshake complete */ } + Output::Timeout(when) => break, + } +} +``` + +Never stop polling early. Internal state is only consistent after reaching `Timeout`. + +## Memory + +**Summary**: Allocation-conscious design - pool reuse, single-copy, in-place +mutation, boxing for ABI, bounded stack collections. + +**Buffer Pooling** +- Reuse allocations instead of malloc/free per packet +- Clear contents but retain capacity + +**Single-Copy Parsing** +- One copy from network into working buffer +- Parse and decrypt in-place on that buffer + +**ABI Optimization** +- Box large inner data so outer structs fit in registers +- Avoids memmove on function calls + +**Bounded Stack Collections** +- Fixed-capacity arrays for small, known-bounded collections +- Fail explicitly if bounds exceeded diff --git a/third_party/dimpl/Cargo.lock b/third_party/dimpl/Cargo.lock new file mode 100644 index 0000000..9547fba --- /dev/null +++ b/third_party/dimpl/Cargo.lock @@ -0,0 +1,1742 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "asn1-rs" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "autotools" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef941527c41b0fc0dd48511a8154cd5fc7e29200a0ff8b7203c5d777dbc795cf" +dependencies = [ + "cc", +] + +[[package]] +name = "aws-lc-rs" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc" +dependencies = [ + "aws-lc-sys", + "untrusted", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa7e52a4c5c547c741610a2c6f123f3881e409b714cd27e6798ef020c514f0a" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn", +] + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "build-target" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78e2ceaf91e22593e194211930aea78a41af58e49e872474ebf4335bf649aad1" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "ccm" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae3c82e4355234767756212c570e29833699ab63e6ffd161887314cc5b43847" +dependencies = [ + "aead", + "cipher", + "ctr", + "subtle", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "clang-sys" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cmake" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "data-encoding" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "dimpl" +version = "0.7.4" +dependencies = [ + "aes", + "aes-gcm", + "arrayvec", + "aws-lc-rs", + "bytes", + "ccm", + "chacha20", + "chacha20poly1305", + "der", + "ecdsa", + "env_logger", + "generic-array", + "hkdf", + "hmac", + "libc", + "log", + "nom 8.0.0", + "once_cell", + "openssl", + "p256", + "p384", + "pkcs8", + "rand", + "rand_core 0.6.4", + "rcgen", + "sec1", + "sha2", + "signature", + "spki", + "subtle", + "time", + "wolfssl", + "x25519-dalek", + "x509-cert", + "x509-parser", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "env_filter" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "jiff" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359" +dependencies = [ + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-static" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "lenient_semver" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de8de3f4f3754c280ce1c8c42ed8dd26a9c8385c2e5ad4ec5a77e774cea9c1ec" +dependencies = [ + "lenient_semver_parser", + "lenient_version", + "semver", +] + +[[package]] +name = "lenient_semver_parser" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f650c1d024ddc26b4bb79c3076b30030f2cf2b18292af698c81f7337a64d7d6" +dependencies = [ + "lenient_semver_version_builder", + "semver", +] + +[[package]] +name = "lenient_semver_version_builder" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9049f8ff49f75b946f95557148e70230499c8a642bf2d6528246afc7d0282d17" +dependencies = [ + "semver", +] + +[[package]] +name = "lenient_version" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad7b41cc0ad9b8a9f8d8fcb7c2ab6703a6da4b369cbb7e3a63ee0840769b4eb" +dependencies = [ + "lenient_semver_parser", + "lenient_semver_version_builder", +] + +[[package]] +name = "libc" +version = "0.2.182" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "msbuild" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e3d8fc9e04620b75d822dfaf2ae73ff7aa806916f9641c984fa12c51ef15603" +dependencies = [ + "lenient_semver", + "serde_json", + "winreg", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl" +version = "0.10.78" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38c4372413cdaaf3cc79dd92d29d7d9f5ab09b51b10dded508fb90bb70b9222" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-src" +version = "300.5.5+3.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f1787d533e03597a7934fd0a765f0d28e94ecc5fb7789f8053b1e699a56f709" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13ce1245cd07fcc4cfdb438f7507b0c7e4f3849a69fd84d52374c66d83741bb6" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "portable-atomic-util" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ec095654a25171c2124e9e3393a930bddbffdc939556c914957a4c3e0a87166" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rcgen" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10b99e0098aa4082912d4c649628623db6aba77335e4f4569ff5083a6448b32e" +dependencies = [ + "aws-lc-rs", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "zeroize", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca" + +[[package]] +name = "time-macros" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "wolfssl" +version = "7.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a15819c1173cfd9088fcb6c31bf0412d75a51c7c9665f50b6d95cb607809d0aa" +dependencies = [ + "bytes", + "log", + "thiserror", + "wolfssl-sys", +] + +[[package]] +name = "wolfssl-sys" +version = "4.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b48547937d9e3ac557ff9838c0a06d0eac700512485b07e791a27b2978d450c" +dependencies = [ + "autotools", + "bindgen", + "build-target", + "msbuild", +] + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid", + "der", + "spki", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "aws-lc-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + +[[package]] +name = "zerocopy" +version = "0.8.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a789c6e490b576db9f7e6b6d661bcc9799f7c0ac8352f56ea20193b2681532e5" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/third_party/dimpl/Cargo.toml b/third_party/dimpl/Cargo.toml new file mode 100644 index 0000000..bcd5937 --- /dev/null +++ b/third_party/dimpl/Cargo.toml @@ -0,0 +1,247 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.85.0" +name = "dimpl" +version = "0.7.4" +authors = ["Martin Algesten "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "DTLS 1.2/1.3 implementation (Sans‑IO, Sync)" +readme = "README.md" +keywords = [ + "dtls", + "tls", + "webrtc", + "psk", +] +categories = [ + "network-programming", + "cryptography", + "security", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/algesten/dimpl" + +[features] +_crypto-common = [ + "dep:der", + "dep:pkcs8", + "dep:sec1", + "dep:signature", + "dep:spki", + "dep:x509-cert", +] +aws-lc-rs = [ + "dep:aws-lc-rs", + "dep:ccm", + "dep:aes", + "_crypto-common", +] +default = [ + "aws-lc-rs", + "rcgen", +] +rcgen = [ + "dep:rcgen", + "aws-lc-rs", +] +rust-crypto = [ + "dep:aes-gcm", + "dep:chacha20poly1305", + "dep:chacha20", + "dep:p256", + "dep:p384", + "dep:x25519-dalek", + "dep:sha2", + "dep:hmac", + "dep:hkdf", + "dep:ecdsa", + "dep:generic-array", + "dep:rand_core", + "dep:ccm", + "dep:aes", + "_crypto-common", +] + +[lib] +name = "dimpl" +path = "src/lib.rs" + +[[test]] +name = "auto" +path = "tests/auto/main.rs" + +[[test]] +name = "dtls12" +path = "tests/dtls12/main.rs" + +[[test]] +name = "dtls13" +path = "tests/dtls13/main.rs" + +[[test]] +name = "dtls13_cookie" +path = "tests/dtls13_cookie.rs" + +[dependencies.aes] +version = "0.8" +optional = true + +[dependencies.aes-gcm] +version = "0.10" +optional = true + +[dependencies.arrayvec] +version = "0.7.6" + +[dependencies.aws-lc-rs] +version = "^1.16" +features = [ + "aws-lc-sys", + "prebuilt-nasm", +] +optional = true +default-features = false + +[dependencies.ccm] +version = "0.5" +optional = true +default-features = false + +[dependencies.chacha20] +version = "0.9" +optional = true + +[dependencies.chacha20poly1305] +version = "0.10" +optional = true + +[dependencies.der] +version = "0.7" +optional = true + +[dependencies.ecdsa] +version = "0.16" +features = [ + "signing", + "verifying", +] +optional = true + +[dependencies.generic-array] +version = "0.14" +optional = true + +[dependencies.hkdf] +version = "0.12" +optional = true + +[dependencies.hmac] +version = "0.12" +optional = true + +[dependencies.log] +version = "0.4.29" + +[dependencies.nom] +version = "8" +features = ["std"] +default-features = false + +[dependencies.once_cell] +version = "1.21.3" + +[dependencies.p256] +version = "0.13" +features = ["ecdh"] +optional = true + +[dependencies.p384] +version = "0.13" +features = ["ecdh"] +optional = true + +[dependencies.pkcs8] +version = "0.10" +features = ["pem"] +optional = true + +[dependencies.rand] +version = "0.9" + +[dependencies.rand_core] +version = "0.6" +optional = true + +[dependencies.rcgen] +version = "0.14.7" +features = ["aws_lc_rs"] +optional = true +default-features = false + +[dependencies.sec1] +version = "0.7" +optional = true + +[dependencies.sha2] +version = "0.10" +optional = true + +[dependencies.signature] +version = "2.2" +optional = true + +[dependencies.spki] +version = "0.7" +optional = true + +[dependencies.subtle] +version = "2.6" + +[dependencies.time] +version = "0.3" +features = ["formatting"] + +[dependencies.x25519-dalek] +version = "2" +features = ["static_secrets"] +optional = true + +[dependencies.x509-cert] +version = "0.2" +optional = true +default-features = false + +[dev-dependencies.bytes] +version = "1" + +[dev-dependencies.env_logger] +version = "0.11.9" + +[dev-dependencies.libc] +version = "0.2" + +[dev-dependencies.openssl] +version = "0.10.75" +features = ["vendored"] + +[dev-dependencies.x509-parser] +version = "0.18" + +[target."cfg(not(windows))".dev-dependencies.wolfssl] +version = "7.2.0" diff --git a/third_party/dimpl/Cargo.toml.orig b/third_party/dimpl/Cargo.toml.orig new file mode 100644 index 0000000..d0ea961 --- /dev/null +++ b/third_party/dimpl/Cargo.toml.orig @@ -0,0 +1,88 @@ +[package] +name = "dimpl" +authors = ["Martin Algesten "] +description = "DTLS 1.2/1.3 implementation (Sans‑IO, Sync)" +version = "0.7.4" +edition = "2024" +license = "MIT OR Apache-2.0" +repository = "https://github.com/algesten/dimpl" +readme = "README.md" +keywords = ["dtls", "tls", "webrtc", "psk"] +categories = ["network-programming", "cryptography", "security"] + +# MSRV +rust-version = "1.85.0" + +[features] +default = ["aws-lc-rs", "rcgen"] + +# Default crypto provider +aws-lc-rs = ["dep:aws-lc-rs", "dep:ccm", "dep:aes", "_crypto-common"] + +# Pure Rust crypto provider +rust-crypto = [ + "dep:aes-gcm", "dep:chacha20poly1305", "dep:chacha20", "dep:p256", + "dep:p384", "dep:x25519-dalek", "dep:sha2", "dep:hmac", "dep:hkdf", + "dep:ecdsa", "dep:generic-array", "dep:rand_core", + "dep:ccm", "dep:aes", + "_crypto-common" +] + +# Internal for all cryptos +_crypto-common = ["dep:der", "dep:pkcs8", "dep:sec1", "dep:signature", "dep:spki", "dep:x509-cert"] + +# Self-signed certificate generation. +# rcgen can either use ring or aws-lc-rs. We have decided to use aws-lc-rs to limit the number +# of crypto libraries we depend upon. If you enable rcgen, you are implicitly also compiling aws-lc-rs. +# The self-signed certificate comes with a sha256 fingerprint that, where we use aws-lc-rs to compute it. +# Since we are compiling aws-lc-rs anyway, enabling the feature is no extra cost. +rcgen = ["dep:rcgen", "aws-lc-rs"] + +[dependencies] +log = "0.4.29" +nom = { version = "8", default-features = false, features = ["std"] } +once_cell = "1.21.3" +rand = "0.9" +time = { version = "0.3", features = ["formatting"] } +arrayvec = "0.7.6" +subtle = "2.6" + +der = { version = "0.7", optional = true } +pkcs8 = { version = "0.10", features = ["pem"], optional = true } +sec1 = { version = "0.7", optional = true } +signature = { version = "2.2", optional = true } +spki = { version = "0.7", optional = true } +x509-cert = { version = "0.2", default-features = false, optional = true } + +# aws-lc-rs backend +aws-lc-rs = { version = "^1.16", default-features = false, features = ["aws-lc-sys", "prebuilt-nasm"], optional = true } + +# RustCrypto backend +aes-gcm = { version = "0.10", optional = true } +p256 = { version = "0.13", optional = true, features = ["ecdh"] } +p384 = { version = "0.13", optional = true, features = ["ecdh"] } +sha2 = { version = "0.10", optional = true } +hmac = { version = "0.12", optional = true } +hkdf = { version = "0.12", optional = true } +ecdsa = { version = "0.16", optional = true, features = ["signing", "verifying"] } +generic-array = { version = "0.14", optional = true } +rand_core = { version = "0.6", optional = true } +chacha20poly1305 = { version = "0.10", optional = true } +chacha20 = { version = "0.9", optional = true } +ccm = { version = "0.5", default-features = false, optional = true } +aes = { version = "0.8", optional = true } +x25519-dalek = { version = "2", optional = true, features = ["static_secrets"] } + +# certificate generation +rcgen = { version = "0.14.7", default-features = false, features = ["aws_lc_rs"], optional = true } + +[dev-dependencies] +openssl = { version = "0.10.75", features = ["vendored"] } +libc = "0.2" +env_logger = "0.11.9" +x509-parser = "0.18" +bytes = "1" + +# wolfssl doesn't build on Windows +[target.'cfg(not(windows))'.dev-dependencies] +wolfssl = "7.2.0" diff --git a/third_party/dimpl/LICENSE-APACHE.txt b/third_party/dimpl/LICENSE-APACHE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/third_party/dimpl/LICENSE-APACHE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/third_party/dimpl/LICENSE-MIT.txt b/third_party/dimpl/LICENSE-MIT.txt new file mode 100644 index 0000000..235abe2 --- /dev/null +++ b/third_party/dimpl/LICENSE-MIT.txt @@ -0,0 +1,7 @@ +Copyright 2022 Martin Algesten + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third_party/dimpl/README.md b/third_party/dimpl/README.md new file mode 100644 index 0000000..cbc924a --- /dev/null +++ b/third_party/dimpl/README.md @@ -0,0 +1,214 @@ +# dimpl + +dimpl — DTLS 1.2 and 1.3 implementation (Sans‑IO, Sync) + +dimpl is a DTLS 1.2 and 1.3 implementation aimed at WebRTC. It is a Sans‑IO +state machine you embed into your own UDP/RTC event loop: you feed incoming +datagrams, poll for outgoing records or timers, and wire up certificate +verification and SRTP key export yourself. + +## Goals +- **DTLS 1.2 and 1.3**: Implements the DTLS handshake and record layer used by WebRTC. +- **Safety**: `forbid(unsafe_code)` throughout the crate. +- **Minimal Rust‑only deps**: Uses small, well‑maintained Rust crypto crates. +- **Low overhead**: Tight control over allocations and buffers; Sans‑IO integration. + +### Non‑goals +- **DTLS 1.0** +- **Async** (the crate is Sans‑IO and event‑loop agnostic) +- **no_std** (at least not without allocation) +- **RSA** +- **DHE** + +### Version selection + +Four constructors control which DTLS version is used: +- [`Dtls::new_12`][new_12] — explicit DTLS 1.2 (certificate‑based) +- [`Dtls::new_12_psk`][new_12_psk] — explicit DTLS 1.2 (PSK, no certificates) +- [`Dtls::new_13`][new_13] — explicit DTLS 1.3 +- [`Dtls::new_auto`][new_auto] — auto‑sense: the first + incoming ClientHello determines the version (based on the + `supported_versions` extension) + +## Cryptography surface +- **Cipher suites (TLS 1.2 over DTLS)** + - `ECDHE_ECDSA_AES256_GCM_SHA384` + - `ECDHE_ECDSA_AES128_GCM_SHA256` + - `ECDHE_ECDSA_CHACHA20_POLY1305_SHA256` +- **PSK cipher suites (TLS 1.2 over DTLS)** + - `PSK_AES128_CCM_8` +- **Cipher suites (TLS 1.3 over DTLS)** + - `TLS_AES_128_GCM_SHA256` + - `TLS_AES_256_GCM_SHA384` + - `TLS_CHACHA20_POLY1305_SHA256` +- **AEAD**: AES‑GCM 128/256, ChaCha20‑Poly1305 (no CBC/EtM modes). +- **Key exchange**: ECDHE (P‑256/P‑384), X25519 +- **Signatures**: ECDSA P‑256/SHA‑256, ECDSA P‑384/SHA‑384 +- **DTLS‑SRTP**: Exports keying material for `SRTP_AEAD_AES_256_GCM`, + `SRTP_AEAD_AES_128_GCM`, and `SRTP_AES128_CM_SHA1_80` ([RFC 5764], [RFC 7714]). +- **Extended Master Secret** ([RFC 7627]) is negotiated and enforced (DTLS 1.2). + +### Certificate model +During the handshake the engine emits +[`Output::PeerCert`][peer_cert] with the peer's leaf +certificate (DER). The crate uses that certificate to verify DTLS +handshake messages, but it does not perform any PKI validation. Your +application is responsible for validating the peer certificate according to +your policy (fingerprint, chain building, name/EKU checks, pinning, etc.). + +### Sans‑IO integration model +Drive the engine with three calls: +- [`Dtls::handle_packet`][handle_packet] — feed an entire + received UDP datagram. +- [`Dtls::poll_output`][poll_output] — drain pending output: + DTLS records, timers, events. +- [`Dtls::handle_timeout`][handle_timeout] — trigger + retransmissions/time‑based progress. + +The output is an [`Output`][output] enum with borrowed +references into your provided buffer: +- `Packet(&[u8])`: send on your UDP socket +- `BufferTooSmall { needed }`: resize the poll buffer and retry +- `Timeout(Instant)`: schedule a timer and call `handle_timeout` at/after it +- `Connected`: handshake complete +- `PeerCert(&[u8])`: peer leaf certificate (DER) — validate in your app +- `KeyingMaterial(KeyingMaterial, SrtpProfile)`: DTLS‑SRTP export +- `ApplicationData(&[u8])`: plaintext received from peer +- `CloseNotify`: peer sent a `close_notify` alert (graceful shutdown) + +## Error handling + +Every `Error` returned by the public API +([`handle_packet`][handle_packet], [`handle_timeout`][handle_timeout], +`send_application_data`, and `close`) is **fatal**: the connection is no +longer usable and must be thrown away. The engine has no recoverable +error states, so the correct response is always to drop the `Dtls` +instance — and start a fresh handshake if you still need a connection. + +Transient, non‑fatal conditions inherent to running over an unreliable +transport — malformed datagrams, replayed or out‑of‑window records, and +other parser noise — are handled internally and never surface as an +`Error`. Such packets are discarded (logged at `debug!`) while the +connection keeps running. You therefore never need to distinguish +"retry" from "give up": a returned `Error` always means give up on this +connection. + +## Example (Sans‑IO loop) + +```rust +use std::sync::Arc; +use std::time::Instant; + +use dimpl::{certificate, Config, Dtls, Output}; + +// Stub I/O to keep the example focused on the state machine +enum Event { Udp(Vec), Timer(Instant) } +fn wait_next_event(_next_wake: Option) -> Event { Event::Udp(Vec::new()) } +fn send_udp(_bytes: &[u8]) {} + +fn example_event_loop(mut dtls: Dtls) -> Result<(), dimpl::Error> { + let mut next_wake: Option = None; + loop { + // Drain engine output until we have to wait for I/O or a timer + let mut out_buf = vec![0u8; 2048]; + loop { + match dtls.poll_output(&mut out_buf) { + Output::Packet(p) => send_udp(p), + Output::BufferTooSmall { needed } => { + out_buf.resize(needed, 0); + } + Output::Timeout(t) => { next_wake = Some(t); break; } + Output::Connected => { + // DTLS established — application may start sending + } + Output::PeerCert(_der) => { + // Inspect peer leaf certificate if desired + } + Output::KeyingMaterial(_km, _profile) => { + // Provide to SRTP stack + } + Output::ApplicationData(_data) => { + // Deliver plaintext to application + } + Output::CloseNotify => { + // Peer initiated graceful shutdown — leave the event loop + return Ok(()); + } + _ => {} + } + } + + // Block waiting for either UDP input or the scheduled timeout + match wait_next_event(next_wake) { + Event::Udp(pkt) => dtls.handle_packet(&pkt)?, + Event::Timer(now) => dtls.handle_timeout(now)?, + } + } +} + +fn mk_dtls_client() -> Dtls { + let cert = certificate::generate_self_signed_certificate().unwrap(); + let cfg = Arc::new(Config::default()); + let mut dtls = Dtls::new_12(cfg, cert, Instant::now()); + dtls.set_active(true); // client role + dtls +} + +// Putting it together +let dtls = mk_dtls_client(); +let _ = example_event_loop(dtls); +``` + +## Example (PSK client) + +```rust +use std::sync::Arc; +use std::time::Instant; + +use dimpl::{Config, Dtls, PskResolver}; + +struct MyPsk; + +impl PskResolver for MyPsk { + fn resolve(&self, identity: &[u8]) -> Option> { + if identity == b"device-01" { + Some(b"shared-secret-key".to_vec()) + } else { + None + } + } +} + +let config = Arc::new( + Config::builder() + .with_psk_client(b"device-01".to_vec(), Arc::new(MyPsk)) + .build() + .unwrap(), +); + +let mut dtls = Dtls::new_12_psk(config, Instant::now()); +dtls.set_active(true); // client role +``` + +#### MSRV +Rust 1.85.0 + +#### Status +- Session resumption is not implemented (WebRTC does a full handshake on ICE restart). +- Renegotiation is not implemented (WebRTC does full restart). + +[new_12]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_12 +[new_12_psk]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_12_psk +[new_13]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_13 +[new_auto]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_auto +[peer_cert]: https://docs.rs/dimpl/latest/dimpl/enum.Output.html#variant.PeerCert +[handle_packet]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.handle_packet +[poll_output]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.poll_output +[handle_timeout]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.handle_timeout +[output]: https://docs.rs/dimpl/latest/dimpl/enum.Output.html +[RFC 5764]: https://www.rfc-editor.org/rfc/rfc5764 +[RFC 7714]: https://www.rfc-editor.org/rfc/rfc7714 +[RFC 7627]: https://www.rfc-editor.org/rfc/rfc7627 + + +License: MIT OR Apache-2.0 diff --git a/third_party/dimpl/VOELIN-PATCH.md b/third_party/dimpl/VOELIN-PATCH.md new file mode 100644 index 0000000..4332485 --- /dev/null +++ b/third_party/dimpl/VOELIN-PATCH.md @@ -0,0 +1,32 @@ +# dimpl in Voelin + +This directory is dimpl 0.7.4 from crates.io (`MIT OR Apache-2.0`, see +`LICENSE-MIT.txt` and `LICENSE-APACHE.txt`), vendored so that it can be +patched. The root `Cargo.toml` replaces the crates.io crate with it: + +```toml +[patch.crates-io] +dimpl = { path = "third_party/dimpl" } +``` + +Everything that depends on dimpl (str0m through `str0m-proto` and +`str0m-aws-lc-rs`, and `voelin-stream`) builds against this copy. The +directory is excluded from the workspace (`exclude = ["fuzz", "third_party"]`), +so its own tests and dev-dependencies are not part of our builds, and +`scripts/own-crates.sh` leaves it out of the strict fmt/clippy checks. + +The first commit that added this directory is the unmodified crate as +published (the `.crate` contents, `Cargo.toml` normalized by crates.io, +`Cargo.toml.orig` the original manifest). `git diff` against that commit +shows our changes. + +## Running its tests + +From this directory (its own workspace; it has its own `Cargo.lock`): + +```sh +cargo test --lib +``` + +The upstream dev-dependencies (OpenSSL vendored, wolfSSL) are built for +that, so the first run takes a few minutes. diff --git a/third_party/dimpl/cargo_deny.sh b/third_party/dimpl/cargo_deny.sh new file mode 100755 index 0000000..2602814 --- /dev/null +++ b/third_party/dimpl/cargo_deny.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# +# https://github.com/EmbarkStudios/cargo-deny +# +# cargo-deny checks our dependency tree for copy-left licenses, +# duplicate dependencies, and rustsec advisories (https://rustsec.org/advisories). +# +# Install: `cargo install cargo-deny` +# +# This scripts checks the dependency tree for all targets. +# cargo-deny is configured in `deny.toml`. + +set -eu +script_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) +cd "$script_path" +set -x + +# cargo install cargo-deny +cargo deny --all-features --log-level error --target aarch64-apple-darwin check +cargo deny --all-features --log-level error --target i686-pc-windows-gnu check +cargo deny --all-features --log-level error --target i686-pc-windows-msvc check +cargo deny --all-features --log-level error --target i686-unknown-linux-gnu check +cargo deny --all-features --log-level error --target wasm32-unknown-unknown check +cargo deny --all-features --log-level error --target x86_64-apple-darwin check +cargo deny --all-features --log-level error --target x86_64-pc-windows-gnu check +cargo deny --all-features --log-level error --target x86_64-pc-windows-msvc check +cargo deny --all-features --log-level error --target x86_64-unknown-linux-gnu check +cargo deny --all-features --log-level error --target x86_64-unknown-linux-musl check +cargo deny --all-features --log-level error --target x86_64-unknown-redox check diff --git a/third_party/dimpl/clippy.toml b/third_party/dimpl/clippy.toml new file mode 100644 index 0000000..e3a5e48 --- /dev/null +++ b/third_party/dimpl/clippy.toml @@ -0,0 +1,6 @@ +# Temporary mitigation for the `time` advisory flagged by Dependabot. +# We cannot take `time` 0.3.47 yet because that upgrade needs Rust 1.88, so +# until our Rust MSRV moves from 1.85 to 1.88 we ban the affected `Rfc2822` +# format description in our own code. Remove this once we can bump `time` to +# 0.3.47 or newer. +disallowed-types = ["time::format_description::well_known::Rfc2822"] diff --git a/third_party/dimpl/deny.toml b/third_party/dimpl/deny.toml new file mode 100644 index 0000000..b8a120e --- /dev/null +++ b/third_party/dimpl/deny.toml @@ -0,0 +1,68 @@ +# https://github.com/EmbarkStudios/cargo-deny +# +# cargo-deny checks our dependency tree for copy-left licenses, +# duplicate dependencies, and rustsec advisories (https://rustsec.org/advisories). +# +# Install: `cargo install cargo-deny` +# Check: `cargo deny check` or run `cargo_deny.sh`. + +# Note: running just `cargo deny check` without a `--target` can result in +# false positives due to https://github.com/EmbarkStudios/cargo-deny/issues/324 +[graph] +targets = [ + { triple = "aarch64-apple-darwin" }, + { triple = "i686-pc-windows-gnu" }, + { triple = "i686-pc-windows-msvc" }, + { triple = "i686-unknown-linux-gnu" }, + { triple = "wasm32-unknown-unknown" }, + { triple = "x86_64-apple-darwin" }, + { triple = "x86_64-pc-windows-gnu" }, + { triple = "x86_64-pc-windows-msvc" }, + { triple = "x86_64-unknown-linux-gnu" }, + { triple = "x86_64-unknown-linux-musl" }, + { triple = "x86_64-unknown-redox" }, +] + +exclude = ["rand_core"] + +[advisories] +yanked = "deny" +ignore = [ + # DoS via stack exhaustion in time RFC 2822 parsing. + # Fix (>=0.3.47) requires Rust 1.88.0, our MSRV is 1.85.0. + # dimpl only uses OffsetDateTime::now_utc() and Duration::days() for + # certificate generation — no RFC 2822 parsing. A clippy disallowed-types + # rule prevents accidental introduction of Rfc2822. + "RUSTSEC-2026-0009", +] + +[bans] +multiple-versions = "deny" +wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed +deny = [] + +skip = [] +skip-tree = [] + + +[licenses] +private = { ignore = true } +confidence-threshold = 0.92 # We want really high confidence when inferring licenses from text +allow = [ + "Apache-2.0 WITH LLVM-exception", # https://spdx.org/licenses/LLVM-exception.html + "Apache-2.0", # https://tldrlegal.com/license/apache-license-2.0-(apache-2.0) + "BSD-2-Clause", # https://tldrlegal.com/license/bsd-2-clause-license-(freebsd) + "BSD-3-Clause", # https://tldrlegal.com/license/bsd-3-clause-license-(revised) + "BSL-1.0", # https://tldrlegal.com/license/boost-software-license-1.0-explained + "CC0-1.0", # https://creativecommons.org/publicdomain/zero/1.0/ + "ISC", # https://tldrlegal.com/license/-isc-license + "LicenseRef-UFL-1.0", # https://tldrlegal.com/license/ubuntu-font-license,-1.0 + "MIT-0", # https://choosealicense.com/licenses/mit-0/ + "MIT", # https://tldrlegal.com/license/mit-license + "MPL-2.0", # https://www.mozilla.org/en-US/MPL/2.0/FAQ/ + "OFL-1.1", # https://spdx.org/licenses/OFL-1.1.html + "OpenSSL", # https://www.openssl.org/source/license.html - used on Linux + "Unicode-DFS-2016", # https://spdx.org/licenses/Unicode-DFS-2016.html + "Unicode-3.0", # https://spdx.org/licenses/Unicode-3.0.html + "Zlib", # https://tldrlegal.com/license/zlib-libpng-license-(zlib) +] diff --git a/third_party/dimpl/src/auto.rs b/third_party/dimpl/src/auto.rs new file mode 100644 index 0000000..c32219c --- /dev/null +++ b/third_party/dimpl/src/auto.rs @@ -0,0 +1,662 @@ +/// Version detection and hybrid ClientHello for auto-sensing DTLS endpoints. +/// +/// `server_hello_version` does lightweight parsing of the first record in a +/// datagram. It looks for a `HelloVerifyRequest` or a `ServerHello` with the +/// `supported_versions` extension to decide between DTLS 1.2 and 1.3 for the +/// client auto-sense path. +/// +/// [`HybridClientHello`] constructs a ClientHello compatible with both +/// DTLS 1.2 and 1.3 servers: it offers both versions cipher suites and +/// includes `supported_versions` with both versions. Once the server +/// responds, the caller inspects the reply with `server_hello_version` +/// and forks into the appropriate handshake path. +/// +/// Server-side auto-sense does not use lightweight detection. Instead, +/// it starts a DTLS 1.3 server which handles fragment reassembly natively +/// and falls back to DTLS 1.2 via [`Error::Dtls12Fallback`] if the +/// reassembled ClientHello does not offer DTLS 1.3. +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use arrayvec::ArrayVec; + +use crate::buffer::Buf; +use crate::crypto::ActiveKeyExchange; +use crate::dtls13::message::KeyShareClientHello; +use crate::dtls13::message::KeyShareEntry; +use crate::dtls13::message::Random; +use crate::dtls13::message::SignatureAlgorithmsExtension; +use crate::dtls13::message::SupportedGroupsExtension; +use crate::dtls13::message::UseSrtpExtension; +use crate::types::NamedGroup; +use crate::{Config, CryptoError, DtlsCertificate, Error, Output, SeededRng, TimeoutError}; +// Extension type constants +const EXT_SUPPORTED_GROUPS: u16 = 0x000A; +const EXT_EC_POINT_FORMATS: u16 = 0x000B; +const EXT_SIGNATURE_ALGORITHMS: u16 = 0x000D; +const EXT_USE_SRTP: u16 = 0x000E; +const EXT_PADDING: u16 = 0x0015; +const EXT_EXTENDED_MASTER_SECRET: u16 = 0x0017; +const EXT_SUPPORTED_VERSIONS: u16 = 0x002B; +const EXT_KEY_SHARE: u16 = 0x0033; +const EXT_RENEGOTIATION_INFO: u16 = 0xFF01; + +/// A self-contained hybrid ClientHello compatible with both DTLS 1.2 and 1.3. +/// +/// Holds the serialized bytes and crypto state needed to fork into either +/// version's handshake once the server responds: +/// +/// - **DTLS 1.3 fork**: transcript bytes and ECDHE private key are injected +/// into a `Client13` via `new_from_hybrid`. +/// - **DTLS 1.2 fork**: all state is discarded (HelloVerifyRequest clears +/// the transcript), and a fresh `Client12` is created. +pub(crate) struct HybridClientHello { + /// Client random used in the ClientHello. + pub random: Random, + + /// ECDHE private key from the key_share extension. + pub active_key_exchange: Box, + + /// TLS-style transcript bytes: msg_type(1) + length(3) + CH body. + /// Does not include DTLS message_seq/fragment_offset/fragment_length. + pub transcript_bytes: Buf, + + /// DTLS handshake fragment: msg_type(1) + length(3) + message_seq(2) + /// + fragment_offset(3) + fragment_length(3) + CH body. + /// Used by [`wire_packet`](Self::wire_packet) to build the on-wire record + /// and by `Client12::new_from_hybrid` for transcript injection. + pub handshake_fragment: Buf, +} + +impl HybridClientHello { + /// Build a hybrid ClientHello from the given configuration. + /// + /// Serializes the ClientHello body with both DTLS 1.2 and 1.3 cipher + /// suites, `supported_versions` offering both versions, and 1.2-compat + /// extensions (`ec_point_formats`, `extended_master_secret`, + /// `renegotiation_info`). + pub fn new(config: &Arc) -> Result { + let mut rng = SeededRng::new(config.rng_seed()); + let random = Random::new(&mut rng); + + // Start ECDHE key exchange with the first supported group (filtered) + let group = config.kx_groups().next().ok_or(Error::CryptoError( + CryptoError::NoSupportedKeyExchangeGroups, + ))?; + let kx_buf = Buf::new(); + let key_exchange = group.start_exchange(kx_buf).map_err(Error::CryptoError)?; + + // ---- Build the ClientHello body ---- + let mut ch_body = Buf::new(); + + // legacy_version: DTLS 1.2 + ch_body.extend_from_slice(&0xFEFDu16.to_be_bytes()); + + // random + random.serialize(&mut ch_body); + + // legacy_session_id: empty + ch_body.push(0); + + // legacy_cookie: empty (DTLS 1.3 requires zero-length) + ch_body.push(0); + + // cipher_suites: 1.3 suites first, then non-PSK DTLS 1.2 suites. + // The DTLS 1.2 fallback (`Client12::new_from_hybrid`) is + // certificate-auth only and cannot complete a PSK suite. + let mut suites: ArrayVec = ArrayVec::new(); + for cs in config.dtls13_cipher_suites() { + suites.push(cs.suite().as_u16()); + } + for cs in config + .dtls12_cipher_suites() + .filter(|cs| !cs.suite().is_psk()) + { + suites.push(cs.suite().as_u16()); + } + ch_body.extend_from_slice(&((suites.len() * 2) as u16).to_be_bytes()); + for &suite in &suites { + ch_body.extend_from_slice(&suite.to_be_bytes()); + } + + // compression_methods: [null] + ch_body.push(1); + ch_body.push(0); + + // ---- Extensions ---- + // Build extension data into a separate buffer, then write the + // extensions_length + extension entries into ch_body. + let mut ext_buf = Buf::new(); + let mut ext_entries: Vec<(u16, usize, usize)> = Vec::new(); + + // 1. supported_versions: [DTLS 1.3, DTLS 1.2] + let start = ext_buf.len(); + ext_buf.push(4); // list_len = 2 versions * 2 bytes + ext_buf.extend_from_slice(&0xFEFCu16.to_be_bytes()); // DTLS 1.3 + ext_buf.extend_from_slice(&0xFEFDu16.to_be_bytes()); // DTLS 1.2 + ext_entries.push((EXT_SUPPORTED_VERSIONS, start, ext_buf.len())); + + // 2. supported_groups (filtered by config) + let start = ext_buf.len(); + let groups: ArrayVec = config.kx_groups().map(|g| g.name()).collect(); + let sg = SupportedGroupsExtension { groups }; + sg.serialize(&mut ext_buf); + ext_entries.push((EXT_SUPPORTED_GROUPS, start, ext_buf.len())); + + // 3. key_share (ECDHE public key) + let pub_key = key_exchange.pub_key(); + let mut key_data = Buf::new(); + let pub_key_start = key_data.len(); + key_data.extend_from_slice(pub_key); + let pub_key_end = key_data.len(); + + let start = ext_buf.len(); + let mut entries = ArrayVec::new(); + entries.push(KeyShareEntry { + group: group.name(), + key_exchange_range: pub_key_start..pub_key_end, + }); + let ks = KeyShareClientHello { entries }; + ks.serialize(&key_data, &mut ext_buf); + ext_entries.push((EXT_KEY_SHARE, start, ext_buf.len())); + + // 4. signature_algorithms + let start = ext_buf.len(); + let sa = SignatureAlgorithmsExtension::default(); + sa.serialize(&mut ext_buf); + ext_entries.push((EXT_SIGNATURE_ALGORITHMS, start, ext_buf.len())); + + // 5. use_srtp + let start = ext_buf.len(); + let use_srtp = UseSrtpExtension::default(); + use_srtp.serialize(&mut ext_buf); + ext_entries.push((EXT_USE_SRTP, start, ext_buf.len())); + + // 6. ec_point_formats (DTLS 1.2 compat: uncompressed only) + let start = ext_buf.len(); + ext_buf.push(1); // list length + ext_buf.push(0); // ECPointFormat::Uncompressed + ext_entries.push((EXT_EC_POINT_FORMATS, start, ext_buf.len())); + + // 7. extended_master_secret (empty, DTLS 1.2 compat) + ext_entries.push((EXT_EXTENDED_MASTER_SECRET, ext_buf.len(), ext_buf.len())); + + // 8. renegotiation_info (empty renegotiated_connection, DTLS 1.2 compat) + let start = ext_buf.len(); + ext_buf.push(0); // renegotiated_connection length = 0 + ext_entries.push((EXT_RENEGOTIATION_INFO, start, ext_buf.len())); + + // 9. padding: fill to MTU + let record_header = 13usize; + let handshake_header = 12usize; + let body_so_far = ch_body.len() + + 2 // extensions_length field + + ext_entries.iter().map(|(_, s, e)| 4 + (e - s)).sum::(); + let total_so_far = record_header + handshake_header + body_so_far; + let deficit = config.mtu().saturating_sub(total_so_far); + if deficit >= 4 { + let pad_data_len = deficit - 4; // 4 = type(2) + len(2) + let start = ext_buf.len(); + for _ in 0..pad_data_len { + ext_buf.push(0); + } + ext_entries.push((EXT_PADDING, start, ext_buf.len())); + } + + // Write extensions into ch_body + let ext_total_len: usize = ext_entries.iter().map(|(_, s, e)| 4 + (e - s)).sum(); + ch_body.extend_from_slice(&(ext_total_len as u16).to_be_bytes()); + for &(ext_type, start, end) in &ext_entries { + ch_body.extend_from_slice(&ext_type.to_be_bytes()); + ch_body.extend_from_slice(&((end - start) as u16).to_be_bytes()); + if end > start { + ch_body.extend_from_slice(&ext_buf[start..end]); + } + } + + // ---- Build transcript bytes: msg_type(1) + length(3) + body ---- + let mut transcript_bytes = Buf::new(); + transcript_bytes.push(0x01); // ClientHello msg_type + let body_len = ch_body.len() as u32; + transcript_bytes.extend_from_slice(&body_len.to_be_bytes()[1..]); + transcript_bytes.extend_from_slice(&ch_body); + + // ---- Build DTLS handshake fragment ---- + // msg_type(1) + length(3) + message_seq(2) + frag_offset(3) + frag_len(3) + body + let mut handshake_fragment = Buf::new(); + handshake_fragment.push(0x01); // msg_type = ClientHello + handshake_fragment.extend_from_slice(&body_len.to_be_bytes()[1..]); // length (3 bytes) + handshake_fragment.extend_from_slice(&0u16.to_be_bytes()); // message_seq = 0 + handshake_fragment.extend_from_slice(&0u32.to_be_bytes()[1..]); // fragment_offset (3 bytes) + handshake_fragment.extend_from_slice(&body_len.to_be_bytes()[1..]); // fragment_length (3 bytes) + handshake_fragment.extend_from_slice(&ch_body); + + Ok(HybridClientHello { + random, + active_key_exchange: key_exchange, + transcript_bytes, + handshake_fragment, + }) + } + + /// Build the full wire-format DTLSPlaintext record for the hybrid CH. + pub fn wire_packet(&self) -> Buf { + let mut pkt = Buf::new(); + // DTLSPlaintext header: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) + pkt.push(0x16); // Handshake + pkt.extend_from_slice(&0xFEFDu16.to_be_bytes()); // DTLS 1.2 + pkt.extend_from_slice(&0u16.to_be_bytes()); // epoch 0 + pkt.extend_from_slice(&[0u8; 6]); // sequence 0 + pkt.extend_from_slice(&(self.handshake_fragment.len() as u16).to_be_bytes()); + pkt.extend_from_slice(&self.handshake_fragment); + pkt + } +} + +/// Auto-sense client that sends a hybrid ClientHello and waits for the server's response +/// to determine the DTLS version. +pub(crate) struct ClientPending { + hybrid: HybridClientHello, + config: Arc, + certificate: DtlsCertificate, + /// Pre-built wire packet (record header + handshake fragment). + wire_packet: Buf, + /// Whether the wire_packet hasn't been polled yet. + needs_send: bool, + /// Last time handle_timeout was called. + last_now: Instant, + /// When to retransmit the wire_packet. + retransmit_at: Option, + /// How many retransmits have occurred. + retransmit_count: usize, +} + +impl ClientPending { + pub fn new( + config: Arc, + certificate: DtlsCertificate, + now: Instant, + ) -> Result { + let hybrid = HybridClientHello::new(&config)?; + let wire_packet = hybrid.wire_packet(); + Ok(ClientPending { + hybrid, + config, + certificate, + wire_packet, + needs_send: true, + last_now: now, + retransmit_at: None, + retransmit_count: 0, + }) + } + + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + self.last_now = now; + // Arm initial retransmit timer on first call + if self.retransmit_at.is_none() { + self.retransmit_at = Some(now + Duration::from_secs(1)); + return Ok(()); + } + if let Some(deadline) = self.retransmit_at { + if now >= deadline { + if self.retransmit_count >= self.config.flight_retries() { + return Err(Error::Timeout(TimeoutError::HybridClientHello)); + } + self.retransmit_count += 1; + self.needs_send = true; + // Exponential backoff: 2s, 4s, 8s, ... + let shift = self.retransmit_count.min(5) as u32; + let rto = Duration::from_secs(1u64 << shift); + self.retransmit_at = Some(now + rto); + } + } + Ok(()) + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { + if self.needs_send { + let len = self.wire_packet.len(); + if buf.len() < len { + // Keep needs_send armed so the packet is emitted on retry. + return Output::BufferTooSmall { needed: len }; + } + self.needs_send = false; + buf[..len].copy_from_slice(&self.wire_packet); + return Output::Packet(&buf[..len]); + } + let next = self + .retransmit_at + .unwrap_or(self.last_now + Duration::from_secs(1)); + Output::Timeout(next) + } + + pub fn into_parts(self) -> (HybridClientHello, Arc, DtlsCertificate, Instant) { + (self.hybrid, self.config, self.certificate, self.last_now) + } +} + +// ========================================================================= +// Version detection helpers +// ========================================================================= + +/// Detected DTLS version from packet inspection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DetectedVersion { + Dtls12, + Dtls13, + Unknown, +} + +/// Detect DTLS version from a server response (ServerHello or HelloVerifyRequest). +/// +/// - HelloVerifyRequest (msg_type 3) → `Dtls12` +/// - ServerHello with `supported_versions` containing DTLS 1.3 → `Dtls13` +/// - ServerHello without `supported_versions` → `Dtls12` +/// - Anything else → `Unknown` +pub(crate) fn server_hello_version(packet: &[u8]) -> DetectedVersion { + server_hello_version_inner(packet).unwrap_or(DetectedVersion::Unknown) +} + +fn server_hello_version_inner(packet: &[u8]) -> Option { + // Record header: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) = 13 + if packet.len() < 13 { + return None; + } + + // content_type must be 0x16 (Handshake) + if packet[0] != 0x16 { + return None; + } + + let record_len = u16::from_be_bytes([packet[11], packet[12]]) as usize; + let record_body = packet.get(13..13 + record_len)?; + + // Handshake header: msg_type(1) + length(3) + message_seq(2) + + // fragment_offset(3) + fragment_length(3) = 12 + if record_body.len() < 12 { + return None; + } + + let msg_type = record_body[0]; + + // HelloVerifyRequest → DTLS 1.2 + if msg_type == 3 { + return Some(DetectedVersion::Dtls12); + } + + // ServerHello → inspect supported_versions + if msg_type != 2 { + return None; + } + + let fragment_len = ((record_body[9] as usize) << 16) + | ((record_body[10] as usize) << 8) + | (record_body[11] as usize); + let body = record_body.get(12..12 + fragment_len)?; + + // ServerHello body: + // server_version(2) + random(32) + session_id_len(1) + session_id + ... + if body.len() < 35 { + return Some(DetectedVersion::Dtls12); + } + let mut pos = 34; // past version(2) + random(32) + + // session_id: 1-byte length + data + let sid_len = *body.get(pos)? as usize; + pos += 1 + sid_len; + + // cipher_suite: 2 bytes + pos += 2; + + // compression_method: 1 byte + pos += 1; + + // extensions: 2-byte total length (optional) + if pos + 2 > body.len() { + // No extensions → DTLS 1.2 + return Some(DetectedVersion::Dtls12); + } + let ext_total_len = u16::from_be_bytes([body[pos], body[pos + 1]]) as usize; + pos += 2; + let ext_end = pos + ext_total_len; + if ext_end > body.len() { + return Some(DetectedVersion::Dtls12); + } + + // Walk extensions looking for supported_versions (0x002B) + while pos + 4 <= ext_end { + let ext_type = u16::from_be_bytes([body[pos], body[pos + 1]]); + let ext_len = u16::from_be_bytes([body[pos + 2], body[pos + 3]]) as usize; + pos += 4; + + if ext_type == 0x002B { + // ServerHello supported_versions: just 2 bytes (selected_version) + if ext_len >= 2 { + let version = u16::from_be_bytes([body[pos], body[pos + 1]]); + if version == 0xFEFC { + return Some(DetectedVersion::Dtls13); + } + } + return Some(DetectedVersion::Dtls12); + } + + pos += ext_len; + } + + // No supported_versions → DTLS 1.2 + Some(DetectedVersion::Dtls12) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PskResolver; + use crate::dtls12::message::Dtls12CipherSuite; + + fn offered_cipher_suites(hybrid: &HybridClientHello) -> Vec { + let body = &hybrid.handshake_fragment[12..]; + let mut offset = 2 + 32; // legacy_version + random + + let session_id_len = body[offset] as usize; + offset += 1 + session_id_len; + + let cookie_len = body[offset] as usize; + offset += 1 + cookie_len; + + let suites_len = u16::from_be_bytes([body[offset], body[offset + 1]]) as usize; + offset += 2; + + body[offset..offset + suites_len] + .chunks_exact(2) + .map(|chunk| u16::from_be_bytes([chunk[0], chunk[1]])) + .collect() + } + + struct DummyResolver; + + impl PskResolver for DummyResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"0123456789abcdef".to_vec()) + } + } + + #[test] + fn hello_verify_request_is_dtls12() { + // Minimal HelloVerifyRequest packet + let mut pkt = Vec::new(); + // Record header: content_type=22, version=DTLS1.2, epoch=0, seq=0, length=TBD + pkt.push(0x16); // handshake + pkt.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 + pkt.extend_from_slice(&[0x00, 0x00]); // epoch 0 + pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // seq 0 + // length placeholder (will fill) + let len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00]); + + // Handshake header: msg_type=3 (HVR), length=5, msg_seq=0, frag_off=0, frag_len=5 + pkt.push(3); // HelloVerifyRequest + pkt.extend_from_slice(&[0x00, 0x00, 0x05]); // length + pkt.extend_from_slice(&[0x00, 0x00]); // message_seq + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); // fragment_offset + pkt.extend_from_slice(&[0x00, 0x00, 0x05]); // fragment_length + + // HVR body: server_version(2) + cookie_len(1) + cookie(2) + pkt.extend_from_slice(&[0xFE, 0xFD]); // server_version + pkt.push(0x02); // cookie length + pkt.extend_from_slice(&[0xAA, 0xBB]); // cookie + + // Fill record length + let record_len = (pkt.len() - 13) as u16; + pkt[len_pos] = (record_len >> 8) as u8; + pkt[len_pos + 1] = record_len as u8; + + assert_eq!(server_hello_version(&pkt), DetectedVersion::Dtls12); + } + + #[test] + fn server_hello_with_supported_versions_is_dtls13() { + let mut pkt = Vec::new(); + // Record header + pkt.push(0x16); + pkt.extend_from_slice(&[0xFE, 0xFD]); + pkt.extend_from_slice(&[0x00, 0x00]); + pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); + let len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00]); + + // Handshake header: msg_type=2 (ServerHello) + pkt.push(2); + let hs_len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); // length placeholder + pkt.extend_from_slice(&[0x00, 0x00]); // message_seq + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); // fragment_offset + let frag_len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); // fragment_length placeholder + + let body_start = pkt.len(); + + // ServerHello body: version(2) + random(32) + session_id + pkt.extend_from_slice(&[0xFE, 0xFD]); // legacy version DTLS 1.2 + pkt.extend_from_slice(&[0u8; 32]); // random + pkt.push(0x00); // session_id length = 0 + pkt.extend_from_slice(&[0x13, 0x01]); // cipher_suite AES_128_GCM_SHA256 + pkt.push(0x00); // compression_method = null + + // Extensions + let ext_len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00]); // extensions length placeholder + + let ext_start = pkt.len(); + + // supported_versions extension: type=0x002B, data=0xFEFC (DTLS 1.3) + pkt.extend_from_slice(&[0x00, 0x2B]); // type + pkt.extend_from_slice(&[0x00, 0x02]); // length + pkt.extend_from_slice(&[0xFE, 0xFC]); // DTLS 1.3 + + let ext_total = pkt.len() - ext_start; + pkt[ext_len_pos] = (ext_total >> 8) as u8; + pkt[ext_len_pos + 1] = ext_total as u8; + + let body_len = pkt.len() - body_start; + // Fill handshake length and fragment length + pkt[hs_len_pos] = 0; + pkt[hs_len_pos + 1] = (body_len >> 8) as u8; + pkt[hs_len_pos + 2] = body_len as u8; + pkt[frag_len_pos] = 0; + pkt[frag_len_pos + 1] = (body_len >> 8) as u8; + pkt[frag_len_pos + 2] = body_len as u8; + + // Fill record length + let record_len = (pkt.len() - 13) as u16; + pkt[len_pos] = (record_len >> 8) as u8; + pkt[len_pos + 1] = record_len as u8; + + assert_eq!(server_hello_version(&pkt), DetectedVersion::Dtls13); + } + + #[test] + fn server_hello_without_supported_versions_is_dtls12() { + let mut pkt = Vec::new(); + // Record header + pkt.push(0x16); + pkt.extend_from_slice(&[0xFE, 0xFD]); + pkt.extend_from_slice(&[0x00, 0x00]); + pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); + let len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00]); + + // Handshake header: msg_type=2 (ServerHello) + pkt.push(2); + let hs_len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); + pkt.extend_from_slice(&[0x00, 0x00]); + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); + let frag_len_pos = pkt.len(); + pkt.extend_from_slice(&[0x00, 0x00, 0x00]); + + let body_start = pkt.len(); + + // ServerHello body without extensions + pkt.extend_from_slice(&[0xFE, 0xFD]); // version + pkt.extend_from_slice(&[0u8; 32]); // random + pkt.push(0x00); // session_id length + pkt.extend_from_slice(&[0xC0, 0x2B]); // cipher_suite (1.2 ECDHE) + pkt.push(0x00); // compression + + let body_len = pkt.len() - body_start; + pkt[hs_len_pos] = 0; + pkt[hs_len_pos + 1] = (body_len >> 8) as u8; + pkt[hs_len_pos + 2] = body_len as u8; + pkt[frag_len_pos] = 0; + pkt[frag_len_pos + 1] = (body_len >> 8) as u8; + pkt[frag_len_pos + 2] = body_len as u8; + + let record_len = (pkt.len() - 13) as u16; + pkt[len_pos] = (record_len >> 8) as u8; + pkt[len_pos + 1] = record_len as u8; + + assert_eq!(server_hello_version(&pkt), DetectedVersion::Dtls12); + } + + #[test] + fn garbage_packet_is_unknown() { + assert_eq!( + server_hello_version(&[0xFF, 0x00]), + DetectedVersion::Unknown + ); + assert_eq!(server_hello_version(&[]), DetectedVersion::Unknown); + } + + #[test] + fn too_short_is_unknown() { + // Non-handshake content type + let pkt = [ + 0x17, 0xFE, 0xFD, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xFF, + ]; + assert_eq!(server_hello_version(&pkt), DetectedVersion::Unknown); + } + + #[test] + fn hybrid_client_hello_excludes_psk_dtls12_suites() { + let config = Arc::new( + Config::builder() + .with_psk_client(b"identity".to_vec(), Arc::new(DummyResolver)) + .build() + .expect("config with PSK should build"), + ); + + assert!( + config.dtls12_cipher_suites().any(|cs| cs.suite().is_psk()), + "precondition: PSK-enabled config should expose a PSK DTLS 1.2 suite" + ); + + let hybrid = HybridClientHello::new(&config).expect("hybrid ClientHello should build"); + let offered = offered_cipher_suites(&hybrid); + + assert!( + !offered.contains(&Dtls12CipherSuite::PSK_AES128_CCM_8.as_u16()), + "auto client must not advertise PSK DTLS 1.2 suites it cannot use after fallback" + ); + } +} diff --git a/third_party/dimpl/src/buffer.rs b/third_party/dimpl/src/buffer.rs new file mode 100644 index 0000000..b1856c1 --- /dev/null +++ b/third_party/dimpl/src/buffer.rs @@ -0,0 +1,220 @@ +//! Buffer management for efficient memory reuse. +//! +//! This module provides buffer types used throughout dimpl for managing byte data +//! with minimal allocations. The [`BufferPool`] allows reusing buffers, and [`Buf`] +//! wraps `Vec` with convenient operations for protocol data handling. + +use std::collections::VecDeque; +use std::fmt; +use std::ops::{Deref, DerefMut}; + +/// Buffer pool for reusing allocated buffers. +/// +/// This pool manages a collection of reusable `Buf` instances to reduce allocations +/// during DTLS operations. Buffers are returned to the pool when no longer needed +/// and can be reused for subsequent operations. +#[derive(Default)] +pub struct BufferPool { + free: VecDeque, +} + +impl BufferPool { + /// Take a Buffer from the pool. + /// + /// Creates a new buffer if none is free. + pub fn pop(&mut self) -> Buf { + if self.free.is_empty() { + self.free.push_back(Buf::new()); + } + // Unwrap is OK see above handling of empty. + self.free.pop_front().unwrap() + } + + /// Return a buffer to the pool. + pub fn push(&mut self, mut buffer: Buf) { + buffer.clear(); + self.free.push_front(buffer); + } +} + +impl fmt::Debug for BufferPool { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BufferPool") + .field("free", &self.free.len()) + .finish() + } +} + +/// Growable buffer wrapper used throughout dimpl for efficient memory management. +/// +/// This is a newtype around `Vec` that provides convenient access to byte buffers +/// and integrates with dimpl's buffer pooling system. +#[derive(Default)] +pub struct Buf(Vec); + +impl Buf { + /// Create a new empty buffer. + pub fn new() -> Self { + Self::default() + } + + /// Clear the buffer, removing all data. + pub fn clear(&mut self) { + self.0.clear(); + } + + /// Extend the buffer with a slice of bytes. + pub fn extend_from_slice(&mut self, other: &[u8]) { + self.0.extend_from_slice(other); + } + + /// Push a single byte onto the buffer. + pub fn push(&mut self, byte: u8) { + self.0.push(byte); + } + + /// Resize the buffer to the specified length, filling with the given value. + pub fn resize(&mut self, len: usize, value: u8) { + self.0.resize(len, value); + } + + /// Convert the buffer into the underlying `Vec`. + pub fn into_vec(mut self) -> Vec { + std::mem::take(&mut self.0) + } +} + +// aws-lc-rs AEAD operations require Extend<&u8> for appending authentication tags +impl<'a> Extend<&'a u8> for Buf { + fn extend>(&mut self, iter: T) { + self.0.extend(iter.into_iter().copied()); + } +} + +impl Deref for Buf { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Buf { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl AsRef<[u8]> for Buf { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +impl AsMut<[u8]> for Buf { + fn as_mut(&mut self) -> &mut [u8] { + &mut self.0 + } +} + +impl fmt::Debug for Buf { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Buf").field("len", &self.0.len()).finish() + } +} + +/// Trait for types that can be converted into a `Buf`. +pub trait ToBuf { + /// Convert this value into a `Buf`. + fn to_buf(self) -> Buf; +} + +impl ToBuf for Vec { + fn to_buf(self) -> Buf { + Buf(self) + } +} + +impl ToBuf for &[u8] { + fn to_buf(self) -> Buf { + self.to_vec().to_buf() + } +} + +/// Temporary mutable buffer wrapper for in-place operations. +/// +/// Used primarily for decryption operations where data needs to be modified in-place. +/// Provides mutable access to a slice with tracked length. +#[allow(clippy::len_without_is_empty)] +pub struct TmpBuf<'a>(&'a mut [u8], usize); + +impl core::fmt::Debug for TmpBuf<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TmpBuf").field("data_len", &self.1).finish() + } +} + +impl<'a> TmpBuf<'a> { + /// Create a new temporary buffer from a mutable slice. + pub fn new(buf: &'a mut [u8]) -> Self { + Self(buf, buf.len()) + } +} + +impl<'a> TmpBuf<'a> { + /// Get the length of the buffer + pub fn len(&self) -> usize { + self.1 + } + + /// Truncate the buffer to the specified length + pub fn truncate(&mut self, len: usize) { + self.1 = len; + } +} + +impl<'a> AsRef<[u8]> for TmpBuf<'a> { + fn as_ref(&self) -> &[u8] { + &self.0[..self.1] + } +} + +impl<'a> AsMut<[u8]> for TmpBuf<'a> { + fn as_mut(&mut self) -> &mut [u8] { + &mut self.0[..self.1] + } +} + +#[cfg(feature = "rust-crypto")] +impl<'a> aes_gcm::aead::Buffer for TmpBuf<'a> { + fn extend_from_slice(&mut self, other: &[u8]) -> Result<(), aes_gcm::aead::Error> { + // Check if there's enough capacity in the underlying slice + let available = self.0.len() - self.1; + if available < other.len() { + return Err(aes_gcm::aead::Error); + } + // Copy the data into the buffer + self.0[self.1..self.1 + other.len()].copy_from_slice(other); + self.1 += other.len(); + Ok(()) + } + + fn truncate(&mut self, len: usize) { + if len <= self.1 { + self.1 = len; + } + } +} + +/// Implement the `aead::Buffer` trait for `Buf` to support in-place AEAD operations. +#[cfg(feature = "rust-crypto")] +impl aes_gcm::aead::Buffer for Buf { + fn extend_from_slice(&mut self, other: &[u8]) -> Result<(), aes_gcm::aead::Error> { + self.0.extend_from_slice(other); + Ok(()) + } + + fn truncate(&mut self, len: usize) { + self.0.truncate(len); + } +} diff --git a/third_party/dimpl/src/certificate.rs b/third_party/dimpl/src/certificate.rs new file mode 100644 index 0000000..77f2be4 --- /dev/null +++ b/third_party/dimpl/src/certificate.rs @@ -0,0 +1,184 @@ +//! Certificate generation and formatting utilities exposed via the public `certificate` module. +//! +//! This module provides helpers to generate self-signed certificates suitable for DTLS, +//! compute fingerprints, and format them for display. + +use aws_lc_rs::digest; +use rand::random; +use rcgen::{CertificateParams, DistinguishedName, DnType, IsCa, KeyPair, PKCS_ECDSA_P256_SHA256}; +use std::fmt; + +/// Certificate utility error types +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CertificateError { + /// Invalid certificate format + InvalidFormat, + /// Fingerprint verification failed + FingerprintMismatch, + /// Certificate generation failed + GenerationFailed, +} + +impl fmt::Display for CertificateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CertificateError::InvalidFormat => write!(f, "Invalid certificate format"), + CertificateError::FingerprintMismatch => write!(f, "Fingerprint mismatch"), + CertificateError::GenerationFailed => write!(f, "Certificate generation failed"), + } + } +} + +impl std::error::Error for CertificateError {} + +pub use crate::DtlsCertificate; + +/// Generate a self-signed certificate for DTLS +/// +/// This function requires the `rcgen` feature to be enabled. +pub fn generate_self_signed_certificate() -> Result { + // Create a key pair for the certificate + let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256) + .map_err(|_| CertificateError::GenerationFailed)?; + + // Set up certificate parameters + let mut params = CertificateParams::new(Vec::::new()) + .map_err(|_| CertificateError::GenerationFailed)?; + + // Set up distinguished name + let mut distinguished_name = DistinguishedName::new(); + distinguished_name.push(DnType::OrganizationName, "DTLS".to_string()); + distinguished_name.push(DnType::CommonName, "DTLS Peer".to_string()); + params.distinguished_name = distinguished_name; + + // Configure as end entity certificate (not a CA) + params.is_ca = IsCa::NoCa; + + // Set validity period (1 year) + let not_before = time::OffsetDateTime::now_utc(); + let not_after = not_before + time::Duration::days(365); + params.not_before = not_before; + params.not_after = not_after; + + // Serial number: must be unique for Firefox compatibility, not only across all certificates + // of this process, but also across all certificates of other processes/machines! + // See: https://github.com/versatica/mediasoup/issues/127#issuecomment-474460153 + // and https://github.com/algesten/str0m/issues/517 + let serial_buf: [u8; 16] = random(); + params.serial_number = Some(serial_buf.to_vec().into()); + + // Build the certificate + let cert = params + .self_signed(&key_pair) + .map_err(|_| CertificateError::GenerationFailed)?; + + // Get the certificate in DER format + let cert_der = cert.der().to_vec(); + + // Get the private key in DER format + let key_der = key_pair.serialize_der(); + + Ok(DtlsCertificate { + certificate: cert_der, + private_key: key_der, + }) +} + +/// Calculate a certificate fingerprint using SHA-256 +/// +/// This function requires the `rcgen` feature to be enabled. +pub fn calculate_fingerprint(cert_der: &[u8]) -> Vec { + // Use SHA-256 to calculate the fingerprint + digest::digest(&digest::SHA256, cert_der).as_ref().to_vec() +} + +/// Format a fingerprint as a colon-separated hex string +/// Example: "AF:12:F6:..." +pub fn format_fingerprint(fingerprint: &[u8]) -> String { + fingerprint + .iter() + .map(|byte| format!("{:02X}", byte)) + .collect::>() + .join(":") +} + +impl DtlsCertificate { + /// Returns the certificate fingerprint as raw bytes. + /// + /// The fingerprint is computed by hashing the DER-encoded certificate + /// with SHA-256 and is therefore 32 bytes long. + /// + /// This method requires the `rcgen` feature to be enabled. + pub fn fingerprint(&self) -> Vec { + calculate_fingerprint(&self.certificate) + } + + /// Returns the certificate fingerprint as a human-readable string. + /// + /// The string is the SHA-256 fingerprint formatted as uppercase + /// hex byte pairs separated by colons, for example "AF:12:F6:...". + /// + /// This method requires the `rcgen` feature to be enabled. + pub fn fingerprint_str(&self) -> String { + format_fingerprint(&self.fingerprint()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_self_signed_certificate() { + // Generate a certificate + let cert = generate_self_signed_certificate().unwrap(); + + // Check certificate format + assert!(!cert.certificate.is_empty()); + assert!(!cert.private_key.is_empty()); + + // Fingerprint should be 32 bytes (SHA-256) + assert_eq!(cert.fingerprint().len(), 32); + } + + #[test] + fn test_unique_serial_numbers() { + // Generate two certificates + let cert1 = generate_self_signed_certificate().unwrap(); + let cert2 = generate_self_signed_certificate().unwrap(); + + // Fingerprints should be different (unique serial numbers + keys) + assert_ne!(cert1.fingerprint(), cert2.fingerprint()); + + // Parse the certificates to verify serial numbers are different + use x509_parser::prelude::*; + let (_, parsed1) = X509Certificate::from_der(&cert1.certificate).unwrap(); + let (_, parsed2) = X509Certificate::from_der(&cert2.certificate).unwrap(); + assert_ne!( + parsed1.serial, parsed2.serial, + "Serial numbers must be unique for Firefox compatibility" + ); + } + + #[test] + fn test_fingerprint_formatting() { + let test_fingerprint = vec![0xAF, 0x12, 0xF6, 0x38, 0x2A]; + let formatted = format_fingerprint(&test_fingerprint); + assert_eq!(formatted, "AF:12:F6:38:2A"); + + // Test with an actual generated certificate + let cert = generate_self_signed_certificate().unwrap(); + let formatted = format_fingerprint(&cert.fingerprint()); + + // Verify the format + assert_eq!(formatted.len(), 95); // 32 bytes * 3 - 1 = 95 (32 hex pairs with : between them) + assert!(formatted.contains(':')); + + // Each segment should be 2 hex chars + for segment in formatted.split(':') { + assert_eq!(segment.len(), 2); + // Verify it's valid hex + assert!(u8::from_str_radix(segment, 16).is_ok()); + } + } +} diff --git a/third_party/dimpl/src/config.rs b/third_party/dimpl/src/config.rs new file mode 100644 index 0000000..b84dc12 --- /dev/null +++ b/third_party/dimpl/src/config.rs @@ -0,0 +1,1020 @@ +use std::fmt; +use std::panic::{RefUnwindSafe, UnwindSafe}; +use std::sync::Arc; +use std::time::Duration; + +use crate::crypto::{CryptoProvider, SupportedDtls12CipherSuite}; +use crate::crypto::{SupportedDtls13CipherSuite, SupportedKxGroup}; +use crate::dtls12::message::Dtls12CipherSuite; +use crate::types::{Dtls13CipherSuite, NamedGroup}; +use crate::{ConfigError, Error}; + +/// Callback for resolving PSK identities to shared secrets. +/// +/// Implement this trait and provide it via [`ConfigBuilder::with_psk_client`] +/// or [`ConfigBuilder::with_psk_server`] to enable PSK cipher suites. +pub trait PskResolver: Send + Sync + UnwindSafe + RefUnwindSafe { + /// Look up a pre-shared key by the peer's identity. + /// + /// Returns the shared secret bytes, or `None` if the identity is unknown. + fn resolve(&self, identity: &[u8]) -> Option>; +} + +/// PSK configuration for a DTLS endpoint. +/// +/// Use [`Psk::Client`] for endpoints that initiate PSK handshakes (send identity), +/// and [`Psk::Server`] for endpoints that resolve incoming identities. +/// +/// `#[non_exhaustive]` so new variants (e.g. DTLS 1.3 external PSKs) or new +/// fields can be added without a major version bump. +#[derive(Clone)] +#[non_exhaustive] +pub enum Psk { + /// Client-side PSK: sends `identity` during handshake, uses `resolver` + /// to look up the shared secret. + #[non_exhaustive] + Client { + /// The identity to send to the server. + identity: Vec, + /// Resolver for looking up shared secrets. + resolver: Arc, + }, + /// Server-side PSK: optionally sends a `hint` to help the client choose + /// an identity, uses `resolver` to look up secrets by client identity. + #[non_exhaustive] + Server { + /// Optional hint sent to the client in ServerKeyExchange. + hint: Option>, + /// Resolver for looking up shared secrets. + resolver: Arc, + }, +} + +#[cfg(feature = "aws-lc-rs")] +use crate::crypto::aws_lc_rs; + +#[cfg(feature = "rust-crypto")] +use crate::crypto::rust_crypto; + +/// DTLS configuration shared by all connections. +/// +/// Build with [`Config::builder()`] or use [`Config::default()`]. +#[derive(Clone)] +pub struct Config { + mtu: usize, + max_queue_rx: usize, + max_queue_tx: usize, + require_client_certificate: bool, + use_server_cookie: bool, + flight_start_rto: Duration, + flight_retries: usize, + handshake_timeout: Duration, + crypto_provider: CryptoProvider, + rng_seed: Option, + aead_encryption_limit: u64, + dtls12_cipher_suites: Option>, + dtls13_cipher_suites: Option>, + kx_groups: Option>, + psk: Option, +} + +impl Config { + /// Create a new configuration builder. + pub fn builder() -> ConfigBuilder { + ConfigBuilder { + mtu: 1150, + max_queue_rx: 30, + max_queue_tx: 10, + require_client_certificate: true, + use_server_cookie: true, + flight_start_rto: Duration::from_secs(1), + flight_retries: 4, + handshake_timeout: Duration::from_secs(40), + crypto_provider: None, + rng_seed: None, + aead_encryption_limit: 1 << 23, + dtls12_cipher_suites: None, + dtls13_cipher_suites: None, + kx_groups: None, + psk: None, + } + } + + /// Max transmission unit. + /// + /// The largest size UDP packets we will produce. + #[inline(always)] + pub fn mtu(&self) -> usize { + self.mtu + } + + /// Max amount of incoming packets to buffer before rejecting more input. + #[inline(always)] + pub fn max_queue_rx(&self) -> usize { + self.max_queue_rx + } + + /// Max amount of outgoing packets to buffer. + #[inline(always)] + pub fn max_queue_tx(&self) -> usize { + self.max_queue_tx + } + + /// For a server, require a client certificate. + /// + /// This will cause the server to send a CertificateRequest message. + /// Makes the server fail if the client does not send a certificate. + /// + /// Applies only to certificate-authenticated cipher suites. For RFC 4279 + /// PSK suites the client never sends a certificate, so this flag has no + /// effect on a negotiated PSK handshake. + #[inline(always)] + pub fn require_client_certificate(&self) -> bool { + self.require_client_certificate + } + + /// Whether the server sends a cookie exchange before the handshake. + /// + /// When true (the default), the server requires a stateless cookie + /// roundtrip for DoS protection: HelloVerifyRequest in DTLS 1.2, + /// HelloRetryRequest with a cookie in DTLS 1.3. + /// + /// When false, the server proceeds directly to ServerHello without + /// a cookie exchange. + #[inline(always)] + pub fn use_server_cookie(&self) -> bool { + self.use_server_cookie + } + + /// Time of first retry. + /// + /// Every flight restarts with this value. + /// Doubled for every retry with a Âą25% jitter. + #[inline(always)] + pub fn flight_start_rto(&self) -> Duration { + self.flight_start_rto + } + + /// Max number of retries per flight. + #[inline(always)] + pub fn flight_retries(&self) -> usize { + self.flight_retries + } + + /// Timeout for the entire handshake, regardless of flights. + #[inline(always)] + pub fn handshake_timeout(&self) -> Duration { + self.handshake_timeout + } + + /// Cryptographic provider. + /// + /// Provides all cryptographic operations (ciphers, key exchange, signing, etc.). + #[inline(always)] + pub fn crypto_provider(&self) -> &CryptoProvider { + &self.crypto_provider + } + + /// Optional seed for deterministic random number generation. + /// + /// When set, most non-cryptographic randomness (backoff jitter, TLS random bytes, + /// AEAD nonces, cookie secrets) will be deterministic based on this seed. + /// This is useful for testing and reproducibility. + /// + /// Note: Cryptographic operations (key exchange, signatures) always use + /// secure system randomness regardless of this setting. + #[inline(always)] + pub fn rng_seed(&self) -> Option { + self.rng_seed + } + + /// Maximum number of AEAD encryptions before triggering a KeyUpdate. + /// + /// When the number of application-epoch ciphertext records reaches this + /// limit, the endpoint automatically initiates a KeyUpdate to rotate keys. + /// Defaults to 2^23 (8,388,608). + #[inline(always)] + pub fn aead_encryption_limit(&self) -> u64 { + self.aead_encryption_limit + } + + /// PSK configuration, if any. + pub fn psk(&self) -> Option<&Psk> { + self.psk.as_ref() + } + + /// PSK identity for the client to send during handshake. + pub fn psk_identity(&self) -> Option<&[u8]> { + match &self.psk { + Some(Psk::Client { identity, .. }) => Some(identity), + _ => None, + } + } + + /// PSK identity hint for the server to send during handshake. + pub fn psk_identity_hint(&self) -> Option<&[u8]> { + match &self.psk { + Some(Psk::Server { hint, .. }) => hint.as_deref(), + _ => None, + } + } + + /// PSK resolver for looking up shared secrets by identity. + pub fn psk_resolver(&self) -> Option<&dyn PskResolver> { + match &self.psk { + Some(Psk::Client { resolver, .. } | Psk::Server { resolver, .. }) => { + Some(resolver.as_ref()) + } + None => None, + } + } + + /// Allowed DTLS 1.2 cipher suites, filtered by the config's allow-list. + /// + /// Returns all provider-supported DTLS 1.2 cipher suites when no filter + /// is set. When a filter is set via the builder's `dtls12_cipher_suites` + /// method, only suites in both the provider and the filter are returned. + /// + /// PSK cipher suites are excluded when no [`PskResolver`] is configured, + /// preventing a certificate-mode endpoint from negotiating a PSK suite + /// and inadvertently skipping certificate authentication. + pub fn dtls12_cipher_suites( + &self, + ) -> impl Iterator + '_ { + let filter = self.dtls12_cipher_suites.as_ref(); + let has_psk = self.psk.is_some(); + self.crypto_provider + .supported_cipher_suites() + .filter(move |cs| match filter { + Some(list) => list.contains(&cs.suite()), + None => true, + }) + .filter(move |cs| has_psk || !cs.suite().is_psk()) + } + + /// Allowed DTLS 1.3 cipher suites, filtered by the config's allow-list. + /// + /// Returns all provider DTLS 1.3 cipher suites when no filter is set. + /// When a filter is set via the builder's `dtls13_cipher_suites` method, + /// only suites in both the provider and the filter are returned. + pub fn dtls13_cipher_suites( + &self, + ) -> impl Iterator + '_ { + let filter = self.dtls13_cipher_suites.as_ref(); + self.crypto_provider + .dtls13_cipher_suites + .iter() + .copied() + .filter(move |cs| match filter { + Some(list) => list.contains(&cs.suite()), + None => true, + }) + } + + /// Allowed key exchange groups, filtered by the config's allow-list. + /// + /// Returns all provider-supported key exchange groups when no filter + /// is set. When a filter is set via the builder's `kx_groups` method, + /// only groups in both the provider and the filter are returned. + pub fn kx_groups(&self) -> impl Iterator + '_ { + let filter = self.kx_groups.as_ref(); + self.crypto_provider + .supported_kx_groups() + .filter(move |kx| match filter { + Some(list) => list.contains(&kx.name()), + None => true, + }) + } +} + +/// Builder for [`Config`]. See each setter for defaults. +pub struct ConfigBuilder { + mtu: usize, + max_queue_rx: usize, + max_queue_tx: usize, + require_client_certificate: bool, + use_server_cookie: bool, + flight_start_rto: Duration, + flight_retries: usize, + handshake_timeout: Duration, + crypto_provider: Option, + rng_seed: Option, + aead_encryption_limit: u64, + dtls12_cipher_suites: Option>, + dtls13_cipher_suites: Option>, + kx_groups: Option>, + psk: Option, +} + +impl ConfigBuilder { + /// Set the max transmission unit (MTU). + /// + /// The largest size UDP packets we will produce. + /// Defaults to 1150. + pub fn mtu(mut self, mtu: usize) -> Self { + self.mtu = mtu; + self + } + + /// Set the max amount of incoming packets to buffer before rejecting more input. + /// + /// Defaults to 30. + pub fn max_queue_rx(mut self, max_queue_rx: usize) -> Self { + self.max_queue_rx = max_queue_rx; + self + } + + /// Set the max amount of outgoing packets to buffer. + /// + /// Defaults to 10. + pub fn max_queue_tx(mut self, max_queue_tx: usize) -> Self { + self.max_queue_tx = max_queue_tx; + self + } + + /// Set whether to require a client certificate (for servers). + /// + /// This will cause the server to send a CertificateRequest message. + /// Makes the server fail if the client does not send a certificate. + /// Defaults to true. + /// + /// Applies only to certificate-authenticated cipher suites. For RFC 4279 + /// PSK suites the client never sends a certificate, so this flag has no + /// effect on a negotiated PSK handshake; no opt-out is required when + /// combining this builder with [`with_psk_server`](Self::with_psk_server). + pub fn require_client_certificate(mut self, require: bool) -> Self { + self.require_client_certificate = require; + self + } + + /// Set whether the server sends a cookie exchange before the handshake. + /// + /// When true (the default), the server requires a stateless cookie + /// roundtrip for DoS protection: HelloVerifyRequest in DTLS 1.2, + /// HelloRetryRequest with a cookie in DTLS 1.3. + /// + /// When false, the server proceeds directly to ServerHello without + /// a cookie exchange. + pub fn use_server_cookie(mut self, use_cookie: bool) -> Self { + self.use_server_cookie = use_cookie; + self + } + + /// Set the time of first retry. + /// + /// Every flight restarts with this value. + /// Doubled for every retry with a Âą25% jitter. + /// Defaults to 1 second. + pub fn flight_start_rto(mut self, rto: Duration) -> Self { + self.flight_start_rto = rto; + self + } + + /// Set the max number of retries per flight. + /// + /// Defaults to 4. + pub fn flight_retries(mut self, retries: usize) -> Self { + self.flight_retries = retries; + self + } + + /// Set the timeout for the entire handshake, regardless of flights. + /// + /// Defaults to 40 seconds. + pub fn handshake_timeout(mut self, timeout: Duration) -> Self { + self.handshake_timeout = timeout; + self + } + + /// Set a custom crypto provider. + /// + /// If not set, the default aws-lc-rs provider will be used, if the feature + /// flag `aws-lc-rs` is enabled. + pub fn with_crypto_provider(mut self, provider: CryptoProvider) -> Self { + self.crypto_provider = Some(provider); + self + } + + /// Set a seed for deterministic random number generation. + /// + /// When set, most non-cryptographic randomness (backoff jitter, TLS random bytes, + /// AEAD nonces, cookie secrets) will be deterministic based on this seed. + /// + /// This is useful for testing and reproducibility. + /// + /// Note: Cryptographic operations (key exchange, signatures) always use + /// secure system randomness regardless of this setting. + pub fn dangerously_set_rng_seed(mut self, seed: u64) -> Self { + self.rng_seed = Some(seed); + self + } + + /// Set the maximum number of AEAD encryptions before triggering a KeyUpdate. + /// + /// Defaults to 2^23 (8,388,608). + pub fn aead_encryption_limit(mut self, limit: u64) -> Self { + self.aead_encryption_limit = limit; + self + } + + /// Restrict which DTLS 1.2 cipher suites are offered and accepted. + /// + /// Only cipher suites present in both this list and the provider will + /// be used. Passing an empty slice disables DTLS 1.2 (as long as + /// DTLS 1.3 suites remain). + /// + /// By default all provider-supported DTLS 1.2 cipher suites are used. + pub fn dtls12_cipher_suites(mut self, suites: &[Dtls12CipherSuite]) -> Self { + self.dtls12_cipher_suites = Some(suites.to_vec()); + self + } + + /// Restrict which DTLS 1.3 cipher suites are offered and accepted. + /// + /// Only cipher suites present in both this list and the provider will + /// be used. Passing an empty slice disables DTLS 1.3 (as long as + /// DTLS 1.2 suites remain). + /// + /// By default all provider DTLS 1.3 cipher suites are used. + pub fn dtls13_cipher_suites(mut self, suites: &[Dtls13CipherSuite]) -> Self { + self.dtls13_cipher_suites = Some(suites.to_vec()); + self + } + + /// Restrict which key exchange groups are offered and accepted. + /// + /// Only groups present in both this list and the provider will be + /// used. Order determines preference (first = most preferred). + /// + /// By default all provider-supported key exchange groups are used. + pub fn kx_groups(mut self, groups: &[NamedGroup]) -> Self { + self.kx_groups = Some(groups.to_vec()); + self + } + + /// Configure PSK for a client endpoint. + /// + /// The `identity` is sent to the server during the handshake. + /// The `resolver` looks up the shared secret by identity. + pub fn with_psk_client(mut self, identity: Vec, resolver: Arc) -> Self { + self.psk = Some(Psk::Client { identity, resolver }); + self + } + + /// Configure PSK for a server endpoint. + /// + /// The optional `hint` is sent to the client in ServerKeyExchange. + /// The `resolver` looks up the shared secret by client identity. + pub fn with_psk_server( + mut self, + hint: Option>, + resolver: Arc, + ) -> Self { + self.psk = Some(Psk::Server { hint, resolver }); + self + } + + /// Build the configuration. + /// + /// This validates the crypto provider before returning the configuration. + /// Returns `Error::ConfigError` if the provider is invalid. + /// + /// The crypto provider is selected in the following priority order: + /// 1. Explicit provider set via `with_crypto_provider()` + /// 2. Default provider installed via `CryptoProvider::install_default()` + /// 3. AWS-LC provider (if `aws-lc-rs` feature is enabled) + /// 4. RustCrypto provider (if `rust-crypto` feature is enabled) + /// 5. Panic if no provider is available + pub fn build(self) -> Result { + let crypto_provider = self + .crypto_provider + .or_else(|| CryptoProvider::get_default().cloned()); + + #[cfg(feature = "aws-lc-rs")] + let crypto_provider = crypto_provider.or_else(|| Some(aws_lc_rs::default_provider())); + + #[cfg(feature = "rust-crypto")] + let crypto_provider = crypto_provider.or_else(|| Some(rust_crypto::default_provider())); + + let crypto_provider = crypto_provider.expect( + "No crypto provider available. Either set one explicitly via \ + with_crypto_provider(), install a default via CryptoProvider::install_default(), \ + or enable the 'aws-lc-rs' or 'rust-crypto' feature.", + ); + + // Always validate the crypto provider + crypto_provider.validate()?; + + // Validate MTU: must be large enough for DTLS record + handshake headers + if self.mtu < 64 { + return Err(Error::ConfigError(ConfigError::MtuTooSmall { + mtu: self.mtu as u16, + minimum: 64, + })); + } + + // Validate aead_encryption_limit: must be at least 1 + if self.aead_encryption_limit == 0 { + return Err(Error::ConfigError(ConfigError::AeadEncryptionLimitTooSmall)); + } + + // Validate cipher suite filters: at least one version must have suites. + // Mirror Config::dtls12_cipher_suites() by dropping PSK suites when no PSK + // is configured, so a PSK-only filter without a PSK resolver fails fast. + let has_psk = self.psk.is_some(); + let dtls12_suites: Vec<_> = { + let all = crypto_provider.supported_cipher_suites(); + match &self.dtls12_cipher_suites { + Some(list) => all + .filter(|cs| list.contains(&cs.suite())) + .filter(|cs| has_psk || !cs.suite().is_psk()) + .collect(), + None => all.filter(|cs| has_psk || !cs.suite().is_psk()).collect(), + } + }; + let dtls12_count = dtls12_suites.len(); + let dtls13_count = { + let all = crypto_provider.dtls13_cipher_suites.iter(); + match &self.dtls13_cipher_suites { + Some(list) => all.filter(|cs| list.contains(&cs.suite())).count(), + None => all.count(), + } + }; + if dtls12_count + dtls13_count == 0 { + return Err(Error::ConfigError( + ConfigError::NoCipherSuitesAfterFiltering, + )); + } + + // When PSK is configured, at least one negotiable DTLS 1.2 suite must be + // a PSK suite. The only PSK suite we implement today is DTLS 1.2 (0xC0A8), + // so a surviving DTLS 1.3 suite is not a fallback: Dtls::new_12_psk only + // speaks DTLS 1.2, and under AuthMode::Psk every non-PSK suite is rejected + // by CryptoContext::is_cipher_suite_compatible. + if has_psk && !dtls12_suites.iter().any(|cs| cs.suite().is_psk()) { + return Err(Error::ConfigError( + ConfigError::PskConfiguredWithoutPskCipherSuite, + )); + } + + // Skip DTLS 1.2 kx-group validation only when the surviving DTLS 1.2 + // suites are exclusively PSK — those don't negotiate an ECDHE group. + // Any cert-based DTLS 1.2 suite left in the filter still needs a + // compatible key exchange group, even when PSK is also configured. + let has_non_psk_dtls12 = dtls12_suites.iter().any(|cs| !cs.suite().is_psk()); + + // Validate kx_groups filter: each enabled version needs compatible groups + // (PSK-only DTLS 1.2 configs don't need key exchange groups) + let filtered_kx = |kx: &&'static dyn SupportedKxGroup| -> bool { + match &self.kx_groups { + Some(list) => list.contains(&kx.name()), + None => true, + } + }; + if has_non_psk_dtls12 { + let dtls12_kx_count = crypto_provider + .supported_kx_groups() + .filter(|kx| filtered_kx(kx)) + .count(); + if dtls12_kx_count == 0 { + return Err(Error::ConfigError( + ConfigError::NoDtls12KeyExchangeGroupsAfterFiltering, + )); + } + } + if dtls13_count > 0 { + let kx_count = crypto_provider + .supported_kx_groups() + .filter(|kx| filtered_kx(kx)) + .count(); + if kx_count == 0 { + return Err(Error::ConfigError( + ConfigError::NoDtls13KeyExchangeGroupsAfterFiltering, + )); + } + } + + Ok(Config { + mtu: self.mtu, + max_queue_rx: self.max_queue_rx, + max_queue_tx: self.max_queue_tx, + require_client_certificate: self.require_client_certificate, + use_server_cookie: self.use_server_cookie, + flight_start_rto: self.flight_start_rto, + flight_retries: self.flight_retries, + handshake_timeout: self.handshake_timeout, + crypto_provider, + rng_seed: self.rng_seed, + aead_encryption_limit: self.aead_encryption_limit, + dtls12_cipher_suites: self.dtls12_cipher_suites, + dtls13_cipher_suites: self.dtls13_cipher_suites, + kx_groups: self.kx_groups, + psk: self.psk, + }) + } +} + +impl Default for Config { + fn default() -> Self { + Config::builder() + .build() + .expect("Default config should always validate") + } +} + +impl fmt::Debug for Psk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Psk::Client { identity, .. } => f + .debug_struct("Psk::Client") + .field("identity", &identity) + .field("resolver", &"...") + .finish(), + Psk::Server { hint, .. } => f + .debug_struct("Psk::Server") + .field("hint", &hint) + .field("resolver", &"...") + .finish(), + } + } +} + +impl fmt::Debug for Config { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Config") + .field("mtu", &self.mtu) + .field("max_queue_rx", &self.max_queue_rx) + .field("max_queue_tx", &self.max_queue_tx) + .field( + "require_client_certificate", + &self.require_client_certificate, + ) + .field("use_server_cookie", &self.use_server_cookie) + .field("flight_start_rto", &self.flight_start_rto) + .field("flight_retries", &self.flight_retries) + .field("handshake_timeout", &self.handshake_timeout) + .field("crypto_provider", &self.crypto_provider) + .field("rng_seed", &self.rng_seed) + .field("aead_encryption_limit", &self.aead_encryption_limit) + .field("dtls12_cipher_suites", &self.dtls12_cipher_suites) + .field("dtls13_cipher_suites", &self.dtls13_cipher_suites) + .field("kx_groups", &self.kx_groups) + .field("psk", &self.psk) + .finish() + } +} + +impl fmt::Debug for ConfigBuilder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ConfigBuilder") + .field("mtu", &self.mtu) + .field("max_queue_rx", &self.max_queue_rx) + .field("max_queue_tx", &self.max_queue_tx) + .field( + "require_client_certificate", + &self.require_client_certificate, + ) + .field("use_server_cookie", &self.use_server_cookie) + .field("flight_start_rto", &self.flight_start_rto) + .field("flight_retries", &self.flight_retries) + .field("handshake_timeout", &self.handshake_timeout) + .field("crypto_provider", &self.crypto_provider) + .field("rng_seed", &self.rng_seed) + .field("aead_encryption_limit", &self.aead_encryption_limit) + .field("dtls12_cipher_suites", &self.dtls12_cipher_suites) + .field("dtls13_cipher_suites", &self.dtls13_cipher_suites) + .field("kx_groups", &self.kx_groups) + .field("psk", &self.psk) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_zero_mtu() { + match Config::builder().mtu(0).build() { + Err(Error::ConfigError(ConfigError::MtuTooSmall { mtu, minimum })) => { + assert_eq!(mtu, 0); + assert_eq!(minimum, 64); + } + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!("expected error for MTU=0"), + } + } + + #[test] + fn rejects_small_mtu() { + match Config::builder().mtu(32).build() { + Err(Error::ConfigError(ConfigError::MtuTooSmall { mtu, minimum })) => { + assert_eq!(mtu, 32); + assert_eq!(minimum, 64); + } + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!("expected error for MTU=32"), + } + } + + #[test] + fn accepts_minimum_mtu() { + Config::builder() + .mtu(64) + .build() + .expect("MTU 64 should be accepted"); + } + + #[test] + fn rejects_zero_aead_limit() { + match Config::builder().aead_encryption_limit(0).build() { + Err(Error::ConfigError(ConfigError::AeadEncryptionLimitTooSmall)) => {} + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!("expected error for aead_encryption_limit=0"), + } + } + + #[test] + fn accepts_minimum_aead_limit() { + Config::builder() + .aead_encryption_limit(1) + .build() + .expect("aead_encryption_limit 1 should be accepted"); + } + + #[test] + fn filter_dtls12_cipher_suite() { + let config = Config::builder() + .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]) + .build() + .expect("should accept single DTLS 1.2 suite"); + let suites: Vec<_> = config.dtls12_cipher_suites().map(|cs| cs.suite()).collect(); + assert_eq!(suites, &[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]); + } + + #[test] + fn filter_dtls13_cipher_suite() { + let config = Config::builder() + .dtls13_cipher_suites(&[Dtls13CipherSuite::AES_256_GCM_SHA384]) + .build() + .expect("should accept single DTLS 1.3 suite"); + let suites: Vec<_> = config.dtls13_cipher_suites().map(|cs| cs.suite()).collect(); + assert_eq!(suites, &[Dtls13CipherSuite::AES_256_GCM_SHA384]); + } + + #[test] + fn filter_kx_groups() { + let config = Config::builder() + .kx_groups(&[NamedGroup::Secp256r1]) + .build() + .expect("should accept single kx group"); + let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); + assert_eq!(groups, &[NamedGroup::Secp256r1]); + } + + #[test] + fn empty_dtls12_filter_disables_version() { + let config = Config::builder() + .dtls12_cipher_suites(&[]) + .build() + .expect("should accept empty DTLS 1.2 when 1.3 has suites"); + assert_eq!(config.dtls12_cipher_suites().count(), 0); + assert!(config.dtls13_cipher_suites().count() > 0); + } + + #[test] + fn empty_dtls13_filter_disables_version() { + let config = Config::builder() + .dtls13_cipher_suites(&[]) + .build() + .expect("should accept empty DTLS 1.3 when 1.2 has suites"); + assert!(config.dtls12_cipher_suites().count() > 0); + assert_eq!(config.dtls13_cipher_suites().count(), 0); + } + + #[test] + fn both_empty_filters_rejected() { + match Config::builder() + .dtls12_cipher_suites(&[]) + .dtls13_cipher_suites(&[]) + .build() + { + Err(Error::ConfigError(ConfigError::NoCipherSuitesAfterFiltering)) => {} + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!("expected error when both versions are empty"), + } + } + + #[test] + fn empty_kx_groups_filter_rejected() { + match Config::builder().kx_groups(&[]).build() { + Err(Error::ConfigError( + ConfigError::NoDtls12KeyExchangeGroupsAfterFiltering + | ConfigError::NoDtls13KeyExchangeGroupsAfterFiltering, + )) => {} + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!("expected error for empty kx groups"), + } + } + + #[test] + fn x25519_only_accepted_for_dtls12() { + // X25519 is supported for DTLS 1.2 and should be accepted. + let config = Config::builder() + .dtls13_cipher_suites(&[]) + .kx_groups(&[NamedGroup::X25519]) + .build() + .expect("X25519-only should be accepted for DTLS 1.2"); + let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); + assert_eq!(groups, &[NamedGroup::X25519]); + } + + #[test] + fn x25519_only_accepted_for_dtls13_only() { + // X25519-only is fine when DTLS 1.2 is disabled. + let config = Config::builder() + .dtls12_cipher_suites(&[]) + .kx_groups(&[NamedGroup::X25519]) + .build() + .expect("X25519-only should be accepted for DTLS 1.3-only config"); + let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); + assert_eq!(groups, &[NamedGroup::X25519]); + } + + #[test] + fn kx_groups_match_provider_when_unfiltered() { + let config = Config::default(); + let from_config: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); + let from_provider: Vec<_> = config + .crypto_provider() + .supported_kx_groups() + .map(|g| g.name()) + .collect(); + assert_eq!(from_config, from_provider); + } + + #[test] + fn no_filter_returns_all() { + let config = Config::default(); + // Default provider should have at least 2 DTLS 1.2 and 2 DTLS 1.3 suites + // (PSK suites are excluded without a resolver, so only non-PSK count) + assert!(config.dtls12_cipher_suites().count() >= 2); + assert!(config.dtls13_cipher_suites().count() >= 2); + assert!(config.kx_groups().count() >= 2); + } + + #[test] + fn psk_suites_excluded_without_resolver() { + let config = Config::default(); + assert!( + config.dtls12_cipher_suites().all(|cs| !cs.suite().is_psk()), + "PSK suites should be excluded when no PskResolver is configured" + ); + } + + #[test] + fn psk_suites_included_with_resolver() { + struct DummyResolver; + impl PskResolver for DummyResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + None + } + } + + let config = Config::builder() + .with_psk_server(None, Arc::new(DummyResolver)) + .build() + .expect("config with PSK resolver should build"); + assert!( + config.dtls12_cipher_suites().any(|cs| cs.suite().is_psk()), + "PSK suites should be included when a PskResolver is configured" + ); + } + + #[test] + fn psk_config_with_only_non_psk_dtls12_filter_rejected() { + struct DummyResolver; + impl PskResolver for DummyResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"key".to_vec()) + } + } + + // PSK config but the user filtered DTLS 1.2 down to a cert-only suite + // and disabled DTLS 1.3. AuthMode::Psk would reject every surviving + // suite at runtime, so build() should fail fast here. + let result = Config::builder() + .with_psk_client(b"identity".to_vec(), Arc::new(DummyResolver)) + .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]) + .dtls13_cipher_suites(&[]) + .build(); + match result { + Err(Error::ConfigError(ConfigError::PskConfiguredWithoutPskCipherSuite)) => {} + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!("expected error for PSK config with only non-PSK suites"), + } + } + + #[test] + fn psk_with_dtls13_but_no_psk_dtls12_suite_rejected() { + struct DummyResolver; + impl PskResolver for DummyResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"key".to_vec()) + } + } + + // PSK configured, DTLS 1.2 filtered to cert-only, DTLS 1.3 left enabled. + // The surviving DTLS 1.3 suite is not a fallback for Dtls::new_12_psk, + // so build() must reject this config instead of producing one that can + // never complete a PSK handshake. + let result = Config::builder() + .with_psk_client(b"identity".to_vec(), Arc::new(DummyResolver)) + .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256]) + .build(); + match result { + Err(Error::ConfigError(ConfigError::PskConfiguredWithoutPskCipherSuite)) => {} + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!( + "expected error for PSK config with only non-PSK DTLS 1.2 suites, \ + even when DTLS 1.3 is enabled" + ), + } + } + + #[test] + fn psk_with_cert_dtls12_and_empty_kx_groups_rejected() { + struct DummyResolver; + impl PskResolver for DummyResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"key".to_vec()) + } + } + + // Mixed config: PSK is set, but a cert-based DTLS 1.2 suite is also in + // the filter alongside a PSK suite. That cert suite still needs an + // ECDHE group, so kx_groups(&[]) must fail build — the fact that PSK + // is also configured does not excuse the missing groups. + let result = Config::builder() + .with_psk_server(None, Arc::new(DummyResolver)) + .dtls12_cipher_suites(&[ + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, + Dtls12CipherSuite::PSK_AES128_CCM_8, + ]) + .dtls13_cipher_suites(&[]) + .kx_groups(&[]) + .build(); + match result { + Err(Error::ConfigError(ConfigError::NoDtls12KeyExchangeGroupsAfterFiltering)) => {} + Err(other) => panic!("expected ConfigError, got: {other:?}"), + Ok(_) => panic!( + "expected error when a cert-based DTLS 1.2 suite is enabled \ + without any kx groups, even alongside PSK" + ), + } + } + + #[test] + fn psk_client_with_empty_kx_groups_builds() { + struct DummyResolver; + impl PskResolver for DummyResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"key".to_vec()) + } + } + + // PSK suites don't need ECDHE groups. A truly PSK-only endpoint (with + // the DTLS 1.2 filter narrowed to PSK suites and DTLS 1.3 disabled) + // should be able to opt out of kx_groups entirely. + Config::builder() + .with_psk_client(b"identity".to_vec(), Arc::new(DummyResolver)) + .dtls12_cipher_suites(&[Dtls12CipherSuite::PSK_AES128_CCM_8]) + .dtls13_cipher_suites(&[]) + .kx_groups(&[]) + .build() + .expect("PSK-only client with empty kx_groups should build"); + } + + #[test] + fn filter_with_explicit_provider() { + #[cfg(feature = "aws-lc-rs")] + { + let config = Config::builder() + .with_crypto_provider(aws_lc_rs::default_provider()) + .dtls12_cipher_suites(&[Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384]) + .dtls13_cipher_suites(&[Dtls13CipherSuite::AES_128_GCM_SHA256]) + .kx_groups(&[NamedGroup::X25519, NamedGroup::Secp256r1]) + .build() + .expect("should accept filtered config with explicit provider"); + let suites12: Vec<_> = config.dtls12_cipher_suites().map(|cs| cs.suite()).collect(); + assert_eq!( + suites12, + &[Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384] + ); + let suites13: Vec<_> = config.dtls13_cipher_suites().map(|cs| cs.suite()).collect(); + assert_eq!(suites13, &[Dtls13CipherSuite::AES_128_GCM_SHA256]); + let groups: Vec<_> = config.kx_groups().map(|g| g.name()).collect(); + assert_eq!(groups, &[NamedGroup::X25519, NamedGroup::Secp256r1]); + } + } +} diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/cipher_suite.rs b/third_party/dimpl/src/crypto/aws_lc_rs/cipher_suite.rs new file mode 100644 index 0000000..0d20c3c --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/cipher_suite.rs @@ -0,0 +1,458 @@ +//! Cipher suite implementations using aws-lc-rs. + +use aws_lc_rs::aead::quic::{self as aws_quic, HeaderProtectionKey}; +use aws_lc_rs::aead::{AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, UnboundKey}; +use aws_lc_rs::aead::{Aad as AwsAad, LessSafeKey, Nonce as AwsNonce}; +use aws_lc_rs::cipher::{self as aws_cipher, AES_128, AES_256, EncryptingKey, UnboundCipherKey}; + +use super::super::{Cipher, SupportedDtls12CipherSuite, SupportedDtls13CipherSuite}; +use crate::buffer::{Buf, TmpBuf}; +use crate::crypto::{Aad, Nonce}; +use crate::dtls12::message::Dtls12CipherSuite; +use crate::error::bounded_error_len; +use crate::types::{Dtls13CipherSuite, HashAlgorithm}; +use crate::{CryptoError, CryptoOperation}; + +/// AES-GCM cipher implementation using aws-lc-rs. +struct AesGcm { + key: LessSafeKey, +} + +impl std::fmt::Debug for AesGcm { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AesGcm").finish_non_exhaustive() + } +} + +impl AesGcm { + fn new(key: &[u8]) -> Result { + let algorithm = match key.len() { + 16 => &AES_128_GCM, + 32 => &AES_256_GCM, + _ => { + return Err(CryptoError::InvalidAesGcmKeySize { + actual: bounded_error_len(key.len()), + }); + } + }; + + let unbound_key = UnboundKey::new(algorithm, key) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?; + + Ok(AesGcm { + key: LessSafeKey::new(unbound_key), + }) + } +} + +impl Cipher for AesGcm { + fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + let aws_nonce = + AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; + + let aws_aad = AwsAad::from(&aad[..]); + + self.key + .seal_in_place_append_tag(aws_nonce, aws_aad, plaintext) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; + + Ok(()) + } + + fn decrypt( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + if ciphertext.len() < 16 { + return Err(CryptoError::CiphertextTooShort { + minimum: 16, + actual: ciphertext.len() as u8, + }); + } + + let aws_nonce = + AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; + + let aws_aad = AwsAad::from(&aad[..]); + + let plaintext = self + .key + .open_in_place(aws_nonce, aws_aad, ciphertext.as_mut()) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + + let plaintext_len = plaintext.len(); + ciphertext.truncate(plaintext_len); + + Ok(()) + } +} + +/// ChaCha20-Poly1305 cipher implementation using aws-lc-rs. +struct ChaCha20Poly1305Cipher { + key: LessSafeKey, +} + +impl std::fmt::Debug for ChaCha20Poly1305Cipher { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ChaCha20Poly1305Cipher") + .finish_non_exhaustive() + } +} + +impl ChaCha20Poly1305Cipher { + fn new(key: &[u8]) -> Result { + // The UnboundKey::new call also validates length, but doesnt give us + // a reasonable error message. This makes it equivalent to RustCrypto + if key.len() != 32 { + return Err(CryptoError::InvalidChacha20Poly1305KeySize { + actual: bounded_error_len(key.len()), + }); + } + let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, key) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?; + + Ok(ChaCha20Poly1305Cipher { + key: LessSafeKey::new(unbound_key), + }) + } +} + +impl Cipher for ChaCha20Poly1305Cipher { + fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + let aws_nonce = + AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; + + let aws_aad = AwsAad::from(&aad[..]); + + self.key + .seal_in_place_append_tag(aws_nonce, aws_aad, plaintext) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; + + Ok(()) + } + + fn decrypt( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + if ciphertext.len() < 16 { + return Err(CryptoError::CiphertextTooShort { + minimum: 16, + actual: ciphertext.len() as u8, + }); + } + + let aws_nonce = + AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?; + + let aws_aad = AwsAad::from(&aad[..]); + + let plaintext = self + .key + .open_in_place(aws_nonce, aws_aad, ciphertext.as_mut()) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + + let plaintext_len = plaintext.len(); + ciphertext.truncate(plaintext_len); + + Ok(()) + } +} + +/// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipher suite. +#[derive(Debug)] +struct Aes128GcmSha256; + +impl SupportedDtls12CipherSuite for Aes128GcmSha256 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 16 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } +} + +/// TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite. +#[derive(Debug)] +struct Aes256GcmSha384; + +impl SupportedDtls12CipherSuite for Aes256GcmSha384 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA384 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 32, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 16 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } +} + +/// TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 cipher suite. +#[derive(Debug)] +struct ChaCha20Poly1305Sha256; + +impl SupportedDtls12CipherSuite for ChaCha20Poly1305Sha256 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 32, 12) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 0 + } + + fn tag_len(&self) -> usize { + 16 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?)) + } +} + +/// TLS_PSK_WITH_AES_128_CCM_8 cipher suite. +#[derive(Debug)] +struct PskAes128Ccm8; + +impl SupportedDtls12CipherSuite for PskAes128Ccm8 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::PSK_AES128_CCM_8 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 8 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(crate::crypto::ccm_cipher::AesCcm8Cipher::new( + key, + )?)) + } +} + +/// Static instances of supported DTLS 1.2 cipher suites. +static AES_128_GCM_SHA256: Aes128GcmSha256 = Aes128GcmSha256; +static AES_256_GCM_SHA384: Aes256GcmSha384 = Aes256GcmSha384; +static CHACHA20_POLY1305_SHA256: ChaCha20Poly1305Sha256 = ChaCha20Poly1305Sha256; +static PSK_AES_128_CCM_8: PskAes128Ccm8 = PskAes128Ccm8; + +/// All supported DTLS 1.2 cipher suites. +pub(super) static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[ + &AES_128_GCM_SHA256, + &AES_256_GCM_SHA384, + &CHACHA20_POLY1305_SHA256, + &PSK_AES_128_CCM_8, +]; + +// ============================================================================ +// DTLS 1.3 Cipher Suites +// ============================================================================ + +/// TLS_AES_128_GCM_SHA256 cipher suite (TLS 1.3 / DTLS 1.3). +#[derive(Debug)] +struct Tls13Aes128GcmSha256; + +impl SupportedDtls13CipherSuite for Tls13Aes128GcmSha256 { + fn suite(&self) -> Dtls13CipherSuite { + Dtls13CipherSuite::AES_128_GCM_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_len(&self) -> usize { + 16 // AES-128 + } + + fn iv_len(&self) -> usize { + 12 // GCM IV + } + + fn tag_len(&self) -> usize { + 16 // GCM tag + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } + + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] { + aes_ecb_encrypt(&AES_128, sn_key, sample) + } +} + +/// TLS_AES_256_GCM_SHA384 cipher suite (TLS 1.3 / DTLS 1.3). +#[derive(Debug)] +struct Tls13Aes256GcmSha384; + +impl SupportedDtls13CipherSuite for Tls13Aes256GcmSha384 { + fn suite(&self) -> Dtls13CipherSuite { + Dtls13CipherSuite::AES_256_GCM_SHA384 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA384 + } + + fn key_len(&self) -> usize { + 32 // AES-256 + } + + fn iv_len(&self) -> usize { + 12 // GCM IV + } + + fn tag_len(&self) -> usize { + 16 // GCM tag + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } + + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] { + aes_ecb_encrypt(&AES_256, sn_key, sample) + } +} + +/// TLS_CHACHA20_POLY1305_SHA256 cipher suite (TLS 1.3 / DTLS 1.3). +#[derive(Debug)] +struct Tls13ChaCha20Poly1305Sha256; + +impl SupportedDtls13CipherSuite for Tls13ChaCha20Poly1305Sha256 { + fn suite(&self) -> Dtls13CipherSuite { + Dtls13CipherSuite::CHACHA20_POLY1305_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_len(&self) -> usize { + 32 // ChaCha20 key + } + + fn iv_len(&self) -> usize { + 12 // Poly1305 nonce + } + + fn tag_len(&self) -> usize { + 16 // Poly1305 tag + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?)) + } + + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] { + // RFC 9001 Section 5.4.4: ChaCha20 header protection + // counter = sample[0..4] (LE), nonce = sample[4..16] + // mask = ChaCha20(sn_key, counter, nonce, <5 zero bytes>) + // unwrap: sn_key length is validated by caller (32 bytes for ChaCha20) + let hp_key = HeaderProtectionKey::new(&aws_quic::CHACHA20, sn_key).unwrap(); + // unwrap: sample is exactly 16 bytes as required + let mask = hp_key.new_mask(sample).unwrap(); + let mut out = [0u8; 16]; + out[..5].copy_from_slice(&mask); + out + } +} + +/// Static instances of supported DTLS 1.3 cipher suites. +static TLS13_AES_128_GCM_SHA256: Tls13Aes128GcmSha256 = Tls13Aes128GcmSha256; +static TLS13_AES_256_GCM_SHA384: Tls13Aes256GcmSha384 = Tls13Aes256GcmSha384; +static TLS13_CHACHA20_POLY1305_SHA256: Tls13ChaCha20Poly1305Sha256 = Tls13ChaCha20Poly1305Sha256; + +/// All supported DTLS 1.3 cipher suites. +pub(super) static ALL_DTLS13_CIPHER_SUITES: &[&dyn SupportedDtls13CipherSuite] = &[ + &TLS13_AES_128_GCM_SHA256, + &TLS13_AES_256_GCM_SHA384, + &TLS13_CHACHA20_POLY1305_SHA256, +]; + +/// AES-ECB single block encryption for record number protection. +fn aes_ecb_encrypt( + algorithm: &'static aws_cipher::Algorithm, + key: &[u8], + input: &[u8; 16], +) -> [u8; 16] { + // unwrap: key length is validated by caller (matches algorithm) + let unbound = UnboundCipherKey::new(algorithm, key).unwrap(); + // unwrap: ECB key construction cannot fail for valid AES keys + let ecb_key = EncryptingKey::ecb(unbound).unwrap(); + let mut block = *input; + // unwrap: 16-byte input is exactly one AES block + ecb_key.encrypt(&mut block).unwrap(); + block +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn chacha20_poly1305_key_len_validation() { + // incorrect length (should be 32) + let result = ChaCha20Poly1305Cipher::new(&[0, 1, 2, 3, 4, 5]); + assert_eq!( + CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 }, + result.unwrap_err() + ); + } +} diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/hash.rs b/third_party/dimpl/src/crypto/aws_lc_rs/hash.rs new file mode 100644 index 0000000..5bc8953 --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/hash.rs @@ -0,0 +1,48 @@ +//! Hash implementations using aws-lc-rs. + +use aws_lc_rs::digest::{Context, SHA256, SHA384}; + +use super::super::{HashContext, HashProvider}; +use crate::buffer::Buf; +use crate::types::HashAlgorithm; + +/// Hash context implementation using aws-lc-rs. +struct AwsLcHashContext { + context: Context, +} + +impl std::fmt::Debug for AwsLcHashContext { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AwsLcHashContext").finish_non_exhaustive() + } +} + +impl HashContext for AwsLcHashContext { + fn update(&mut self, data: &[u8]) { + self.context.update(data); + } + + fn clone_and_finalize(&self, out: &mut Buf) { + let digest = self.context.clone().finish(); + out.clear(); + out.extend_from_slice(digest.as_ref()); + } +} + +/// Hash provider implementation. +#[derive(Debug)] +pub(super) struct AwsLcHashProvider; + +impl HashProvider for AwsLcHashProvider { + fn create_hash(&self, algorithm: HashAlgorithm) -> Box { + let context = match algorithm { + HashAlgorithm::SHA256 => Context::new(&SHA256), + HashAlgorithm::SHA384 => Context::new(&SHA384), + _ => panic!("Unsupported hash algorithm: {:?}", algorithm), + }; + Box::new(AwsLcHashContext { context }) + } +} + +/// Static instance of the hash provider. +pub(super) static HASH_PROVIDER: AwsLcHashProvider = AwsLcHashProvider; diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/hmac.rs b/third_party/dimpl/src/crypto/aws_lc_rs/hmac.rs new file mode 100644 index 0000000..728f019 --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/hmac.rs @@ -0,0 +1,40 @@ +//! HMAC implementation using aws-lc-rs. + +use aws_lc_rs::hmac; + +use super::super::HmacProvider; +use crate::CryptoError; +use crate::types::HashAlgorithm; + +/// Get HMAC algorithm from hash algorithm. +fn hmac_algorithm(hash: HashAlgorithm) -> Result { + match hash { + HashAlgorithm::SHA256 => Ok(hmac::HMAC_SHA256), + HashAlgorithm::SHA384 => Ok(hmac::HMAC_SHA384), + _ => Err(CryptoError::UnsupportedHmacHash(hash)), + } +} + +/// HMAC provider implementation. +#[derive(Debug)] +pub(crate) struct AwsLcHmacProvider; + +impl HmacProvider for AwsLcHmacProvider { + fn hmac( + &self, + hash: HashAlgorithm, + key: &[u8], + data: &[u8], + out: &mut [u8], + ) -> Result { + let algorithm = hmac_algorithm(hash)?; + let hmac_key = hmac::Key::new(algorithm, key); + let tag = hmac::sign(&hmac_key, data); + let len = tag.as_ref().len(); + out[..len].copy_from_slice(tag.as_ref()); + Ok(len) + } +} + +/// Static instance of the HMAC provider. +pub(crate) static HMAC_PROVIDER: AwsLcHmacProvider = AwsLcHmacProvider; diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/kx_group.rs b/third_party/dimpl/src/crypto/aws_lc_rs/kx_group.rs new file mode 100644 index 0000000..1a79cce --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/kx_group.rs @@ -0,0 +1,159 @@ +//! Key exchange group implementations using aws-lc-rs. + +use aws_lc_rs::agreement::{ECDH_P256, ECDH_P384, UnparsedPublicKey, X25519}; +use aws_lc_rs::agreement::{EphemeralPrivateKey, agree_ephemeral}; + +use super::super::{ActiveKeyExchange, SupportedKxGroup}; +use crate::buffer::Buf; +use crate::types::NamedGroup; +use crate::{CryptoError, CryptoOperation}; + +/// ECDHE key exchange implementation. +struct EcdhKeyExchange { + group: NamedGroup, + private_key: EphemeralPrivateKey, + public_key: Buf, +} + +impl std::fmt::Debug for EcdhKeyExchange { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EcdhKeyExchange") + .field("group", &self.group) + .field("public_key_len", &self.public_key.len()) + .finish_non_exhaustive() + } +} + +impl EcdhKeyExchange { + fn new(group: NamedGroup, mut buf: Buf) -> Result { + let algorithm = match group { + NamedGroup::X25519 => &X25519, + NamedGroup::Secp256r1 => &ECDH_P256, + NamedGroup::Secp384r1 => &ECDH_P384, + _ => return Err(CryptoError::UnsupportedKeyExchangeGroup(group)), + }; + + let rng = aws_lc_rs::rand::SystemRandom::new(); + let private_key = EphemeralPrivateKey::generate(algorithm, &rng) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::GenerateEphemeralKey))?; + + let pk = private_key + .compute_public_key() + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputePublicKey))?; + + buf.clear(); + buf.extend_from_slice(pk.as_ref()); + + Ok(EcdhKeyExchange { + group, + private_key, + public_key: buf, + }) + } + + fn algorithm(&self) -> &'static aws_lc_rs::agreement::Algorithm { + match self.group { + NamedGroup::X25519 => &X25519, + NamedGroup::Secp256r1 => &ECDH_P256, + NamedGroup::Secp384r1 => &ECDH_P384, + _ => unreachable!("Unsupported group"), + } + } +} + +impl ActiveKeyExchange for EcdhKeyExchange { + fn pub_key(&self) -> &[u8] { + &self.public_key + } + + fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> { + let algorithm = self.algorithm(); + let peer_key = UnparsedPublicKey::new(algorithm, peer_pub); + + // RFC 7748 §6.1: agree_ephemeral rejects non-contributory shared secrets internally + agree_ephemeral( + self.private_key, + peer_key, + "ECDH agreement failed", + |secret| { + out.clear(); + out.extend_from_slice(secret); + Ok(()) + }, + ) + .map_err(|_| CryptoError::InvalidPublicKey(self.group)) + } + + fn group(&self) -> NamedGroup { + self.group + } +} + +/// X25519 key exchange group. +#[derive(Debug)] +struct X25519Kx; + +impl SupportedKxGroup for X25519Kx { + fn name(&self) -> NamedGroup { + NamedGroup::X25519 + } + + fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { + Ok(Box::new(EcdhKeyExchange::new(NamedGroup::X25519, buf)?)) + } +} + +/// P-256 (secp256r1) key exchange group. +#[derive(Debug)] +struct P256; + +impl SupportedKxGroup for P256 { + fn name(&self) -> NamedGroup { + NamedGroup::Secp256r1 + } + + fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { + Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp256r1, buf)?)) + } +} + +/// P-384 (secp384r1) key exchange group. +#[derive(Debug)] +struct P384; + +impl SupportedKxGroup for P384 { + fn name(&self) -> NamedGroup { + NamedGroup::Secp384r1 + } + + fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { + Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp384r1, buf)?)) + } +} + +/// Static instances of supported key exchange groups. +static KX_GROUP_X25519: X25519Kx = X25519Kx; +static KX_GROUP_P256: P256 = P256; +static KX_GROUP_P384: P384 = P384; + +/// All supported key exchange groups. +pub(super) static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] = + &[&KX_GROUP_X25519, &KX_GROUP_P256, &KX_GROUP_P384]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn x25519_non_contributory_peer_key_returns_invalid_public_key() { + let exchange = X25519Kx + .start_exchange(Buf::new()) + .expect("start key exchange"); + let mut out = Buf::new(); + + assert_eq!( + exchange.complete(&[0; 32], &mut out), + Err(CryptoError::InvalidPublicKey(NamedGroup::X25519)) + ); + } +} diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/mod.rs b/third_party/dimpl/src/crypto/aws_lc_rs/mod.rs new file mode 100644 index 0000000..0a6d89c --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/mod.rs @@ -0,0 +1,120 @@ +//! AWS-LC-RS cryptographic provider implementation for dimpl. +//! +//! This module provides the default cryptographic backend for dimpl using +//! [aws-lc-rs](https://github.com/aws/aws-lc-rs), Amazon's cryptographic library +//! based on AWS-LC (a fork of BoringSSL). +//! +//! # Feature Flag +//! +//! This module is only available when the `aws-lc-rs` feature is enabled. The `aws-lc-rs` +//! feature is included in the default features, so it's enabled by default. To use +//! dimpl without this module, disable default features: +//! +//! ```toml +//! dimpl = { version = "...", default-features = false } +//! ``` +//! +//! # Usage +//! +//! The default provider is used automatically when no custom provider is specified: +//! +//! ``` +//! # #[cfg(feature = "rcgen")] +//! # fn main() { +//! use std::sync::Arc; +//! use std::time::Instant; +//! use dimpl::{Config, Dtls, certificate}; +//! +//! let cert = certificate::generate_self_signed_certificate().unwrap(); +//! // Implicitly uses aws-lc-rs default provider +//! let config = Arc::new(Config::default()); +//! let dtls = Dtls::new_12(config, cert, Instant::now()); +//! # } +//! # #[cfg(not(feature = "rcgen"))] +//! # fn main() {} +//! ``` +//! +//! Or explicitly: +//! +//! ``` +//! # #[cfg(feature = "rcgen")] +//! # fn main() { +//! use std::sync::Arc; +//! use std::time::Instant; +//! use dimpl::{Config, Dtls, certificate}; +//! use dimpl::crypto::aws_lc_rs; +//! +//! let cert = certificate::generate_self_signed_certificate().unwrap(); +//! let config = Arc::new( +//! Config::builder() +//! .with_crypto_provider(aws_lc_rs::default_provider()) +//! .build() +//! .unwrap() +//! ); +//! let dtls = Dtls::new_12(config, cert, Instant::now()); +//! # } +//! # #[cfg(not(feature = "rcgen"))] +//! # fn main() {} +//! ``` + +mod cipher_suite; +mod hash; +pub(crate) mod hmac; +mod kx_group; +mod random; +mod sign; + +use super::CryptoProvider; + +/// Get the default aws-lc-rs based crypto provider. +/// +/// This provider implements all cryptographic operations required for DTLS 1.2 +/// using the aws-lc-rs library (AWS's cryptographic library based on BoringSSL/AWS-LC). +/// +/// # Supported Cipher Suites +/// +/// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` (0xC02B) +/// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` (0xC02C) +/// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` (0xCCA9) +/// +/// # Supported Key Exchange Groups +/// +/// - `x25519` (X25519 / Curve25519) +/// - `secp256r1` (P-256, NIST Curve) +/// - `secp384r1` (P-384, NIST Curve) +/// +/// # Supported Signature Algorithms +/// +/// - ECDSA with P-256 and SHA-256 +/// - ECDSA with P-384 and SHA-384 +/// +/// # Supported Hash Algorithms +/// +/// - SHA-256 +/// - SHA-384 +/// +/// # Key Formats +/// +/// The key provider supports loading private keys in: +/// - PKCS#8 DER format (most common) +/// - SEC1 DER format (OpenSSL EC private key format) +/// - PEM encoded versions of the above +/// +/// # Random Number Generation +/// +/// Uses `SystemRandom` from aws-lc-rs for cryptographically secure random number generation. +pub fn default_provider() -> CryptoProvider { + CryptoProvider { + // Shared components + kx_groups: kx_group::ALL_KX_GROUPS, + signature_verification: &sign::SIGNATURE_VERIFIER, + key_provider: &sign::KEY_PROVIDER, + secure_random: &random::SECURE_RANDOM, + hash_provider: &hash::HASH_PROVIDER, + hmac_provider: &hmac::HMAC_PROVIDER, + // DTLS 1.2 components + cipher_suites: cipher_suite::ALL_CIPHER_SUITES, + // DTLS 1.3 components + dtls13_cipher_suites: cipher_suite::ALL_DTLS13_CIPHER_SUITES, + } +} diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/random.rs b/third_party/dimpl/src/crypto/aws_lc_rs/random.rs new file mode 100644 index 0000000..41737d7 --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/random.rs @@ -0,0 +1,20 @@ +//! Secure random number generation using aws-lc-rs. + +use super::super::SecureRandom; +use crate::{CryptoError, CryptoOperation}; + +/// Secure random number generator implementation. +#[derive(Debug)] +pub(super) struct AwsLcSecureRandom; + +impl SecureRandom for AwsLcSecureRandom { + fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> { + use aws_lc_rs::rand::SecureRandom as _; + let rng = aws_lc_rs::rand::SystemRandom::new(); + rng.fill(buf) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::FillRandom)) + } +} + +/// Static instance of the secure random generator. +pub(super) static SECURE_RANDOM: AwsLcSecureRandom = AwsLcSecureRandom; diff --git a/third_party/dimpl/src/crypto/aws_lc_rs/sign.rs b/third_party/dimpl/src/crypto/aws_lc_rs/sign.rs new file mode 100644 index 0000000..614202d --- /dev/null +++ b/third_party/dimpl/src/crypto/aws_lc_rs/sign.rs @@ -0,0 +1,295 @@ +//! Signing and key loading implementations using aws-lc-rs. + +use std::str; + +use aws_lc_rs::signature::ECDSA_P384_SHA384_ASN1_SIGNING; +use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA384_ASN1}; +use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1_SIGNING, UnparsedPublicKey}; +use aws_lc_rs::signature::{ECDSA_P384_SHA256_ASN1, ECDSA_P384_SHA384_ASN1}; +use aws_lc_rs::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm}; +use der::{Decode, Encode}; +use spki::ObjectIdentifier; +use x509_cert::Certificate as X509Certificate; + +use super::super::{KeyProvider, SignatureVerifier, SigningKey, check_verify_scheme}; +use super::super::{OID_P256, OID_P384}; +use crate::buffer::Buf; +use crate::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm}; +use crate::{CryptoError, CryptoOperation}; + +/// ECDSA signing key implementation. +struct EcdsaSigningKey { + key_pair: EcdsaKeyPair, + signing_algorithm: &'static EcdsaSigningAlgorithm, +} + +impl std::fmt::Debug for EcdsaSigningKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EcdsaSigningKey") + .field("signing_algorithm", &self.signing_algorithm) + .finish() + } +} + +impl SigningKey for EcdsaSigningKey { + fn sign( + &mut self, + data: &[u8], + hash_alg: HashAlgorithm, + buf: &mut Buf, + ) -> Result<(), CryptoError> { + let key_hash = self.hash_algorithm(); + if hash_alg != key_hash { + return Err(CryptoError::SigningKeyHashMismatch { + key_hash, + requested: hash_alg, + }); + } + let rng = aws_lc_rs::rand::SystemRandom::new(); + let signature = self + .key_pair + .sign(&rng, data) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?; + buf.clear(); + buf.extend_from_slice(signature.as_ref()); + Ok(()) + } + + fn algorithm(&self) -> SignatureAlgorithm { + SignatureAlgorithm::ECDSA + } + + fn hash_algorithm(&self) -> HashAlgorithm { + if self.signing_algorithm == &ECDSA_P256_SHA256_ASN1_SIGNING { + HashAlgorithm::SHA256 + } else if self.signing_algorithm == &ECDSA_P384_SHA384_ASN1_SIGNING { + HashAlgorithm::SHA384 + } else { + panic!("Unsupported signing algorithm") + } + } + + fn supported_hash_algorithms(&self) -> &[HashAlgorithm] { + // aws-lc-rs locks the hash at key-load time; only one is supported. + if self.signing_algorithm == &ECDSA_P256_SHA256_ASN1_SIGNING { + &[HashAlgorithm::SHA256] + } else if self.signing_algorithm == &ECDSA_P384_SHA384_ASN1_SIGNING { + &[HashAlgorithm::SHA384] + } else { + panic!("Unsupported signing algorithm") + } + } +} + +/// Key provider implementation. +#[derive(Debug)] +pub(super) struct AwsLcKeyProvider; + +impl KeyProvider for AwsLcKeyProvider { + fn load_private_key(&self, key_der: &[u8]) -> Result, CryptoError> { + // Try PKCS#8 DER format first (most common) + if let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, key_der) { + return Ok(Box::new(EcdsaSigningKey { + key_pair, + signing_algorithm: &ECDSA_P256_SHA256_ASN1_SIGNING, + })); + } + if let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_ASN1_SIGNING, key_der) { + return Ok(Box::new(EcdsaSigningKey { + key_pair, + signing_algorithm: &ECDSA_P384_SHA384_ASN1_SIGNING, + })); + } + + // Try parsing as SEC1 DER format (OpenSSL EC private key format) + if let Ok(ec_key) = sec1::EcPrivateKey::try_from(key_der) { + let private_key_len = ec_key.private_key.len(); + + let curve_oid = if let Some(params) = &ec_key.parameters { + match params { + sec1::EcParameters::NamedCurve(oid) => Some(*oid), + } + } else if private_key_len == 32 { + Some(ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")) // P-256 + } else if private_key_len == 48 { + Some(ObjectIdentifier::new_unwrap("1.3.132.0.34")) // P-384 + } else { + None + }; + + if let Some(curve_oid) = curve_oid { + let ec_alg_oid = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); + let curve_params_der = curve_oid + .to_der() + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; + let curve_params_any = der::asn1::AnyRef::try_from(curve_params_der.as_slice()) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; + + let algorithm = spki::AlgorithmIdentifierRef { + oid: ec_alg_oid, + parameters: Some(curve_params_any), + }; + + let pkcs8 = pkcs8::PrivateKeyInfo { + algorithm, + private_key: key_der, + public_key: None, + }; + + let pkcs8_der = pkcs8 + .to_der() + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; + + let p256_curve = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"); + if curve_oid == p256_curve { + if let Ok(key_pair) = + EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &pkcs8_der) + { + return Ok(Box::new(EcdsaSigningKey { + key_pair, + signing_algorithm: &ECDSA_P256_SHA256_ASN1_SIGNING, + })); + } + } + + let p384_curve = ObjectIdentifier::new_unwrap("1.3.132.0.34"); + if curve_oid == p384_curve { + if let Ok(key_pair) = + EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_ASN1_SIGNING, &pkcs8_der) + { + return Ok(Box::new(EcdsaSigningKey { + key_pair, + signing_algorithm: &ECDSA_P384_SHA384_ASN1_SIGNING, + })); + } + } + } + } + + // Check if it's a PEM encoded key + if let Ok(pem_str) = str::from_utf8(key_der) { + if pem_str.contains("-----BEGIN") { + if let Ok((_label, doc)) = pkcs8::Document::from_pem(pem_str) { + return self.load_private_key(doc.as_bytes()); + } + } + } + + Err(CryptoError::InvalidPrivateKey) + } +} + +/// Signature verifier implementation. +#[derive(Debug)] +pub(super) struct AwsLcSignatureVerifier; + +impl SignatureVerifier for AwsLcSignatureVerifier { + fn verify_signature( + &self, + cert_der: &[u8], + data: &[u8], + signature: &[u8], + hash_alg: HashAlgorithm, + sig_alg: SignatureAlgorithm, + ) -> Result<(), CryptoError> { + if sig_alg != SignatureAlgorithm::ECDSA { + return Err(CryptoError::UnsupportedSignatureAlgorithm(sig_alg)); + } + + let cert = + X509Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?; + let spki = &cert.tbs_certificate.subject_public_key_info; + + const OID_EC_PUBLIC_KEY: ObjectIdentifier = + ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); + + if spki.algorithm.oid != OID_EC_PUBLIC_KEY { + return Err(CryptoError::UnsupportedPublicKeyAlgorithm); + } + + let pubkey_bytes = spki + .subject_public_key + .as_bytes() + .ok_or(CryptoError::InvalidSubjectPublicKey)?; + + let curve_oid: ObjectIdentifier = spki + .algorithm + .parameters + .as_ref() + .ok_or(CryptoError::MissingEcCurveParameter)? + .decode_as() + .map_err(|_| CryptoError::InvalidEcCurveParameter)?; + + let group = match curve_oid { + OID_P256 => NamedGroup::Secp256r1, + OID_P384 => NamedGroup::Secp384r1, + _ => return Err(CryptoError::UnsupportedEcCurve), + }; + + check_verify_scheme(sig_alg, hash_alg, group)?; + + let algorithm: &EcdsaVerificationAlgorithm = match (group, hash_alg) { + (NamedGroup::Secp256r1, HashAlgorithm::SHA256) => &ECDSA_P256_SHA256_ASN1, + (NamedGroup::Secp256r1, HashAlgorithm::SHA384) => &ECDSA_P256_SHA384_ASN1, + (NamedGroup::Secp384r1, HashAlgorithm::SHA256) => &ECDSA_P384_SHA256_ASN1, + (NamedGroup::Secp384r1, HashAlgorithm::SHA384) => &ECDSA_P384_SHA384_ASN1, + // unreachable: check_verify_scheme already validated + _ => unreachable!(), + }; + + let public_key = UnparsedPublicKey::new(algorithm, pubkey_bytes); + public_key + .verify(data, signature) + .map_err(|_| CryptoError::SignatureVerificationFailed { + signature: sig_alg, + hash: hash_alg, + group, + }) + } +} + +/// Static instance of the key provider. +pub(super) static KEY_PROVIDER: AwsLcKeyProvider = AwsLcKeyProvider; + +/// Static instance of the signature verifier. +pub(super) static SIGNATURE_VERIFIER: AwsLcSignatureVerifier = AwsLcSignatureVerifier; + +#[cfg(all(test, feature = "rcgen"))] +mod tests { + use super::*; + use crate::certificate::generate_self_signed_certificate; + + #[test] + fn invalid_signature_returns_structured_verification_error() { + let cert = generate_self_signed_certificate().expect("generate cert"); + let mut key = KEY_PROVIDER + .load_private_key(&cert.private_key) + .expect("load private key"); + let data = b"signed data"; + let mut signature = Buf::new(); + key.sign(data, HashAlgorithm::SHA256, &mut signature) + .expect("sign data"); + + let last = signature.len() - 1; + signature[last] ^= 0x01; + + let err = SIGNATURE_VERIFIER + .verify_signature( + &cert.certificate, + data, + &signature, + HashAlgorithm::SHA256, + SignatureAlgorithm::ECDSA, + ) + .expect_err("corrupt signature should fail"); + + assert_eq!( + err, + CryptoError::SignatureVerificationFailed { + signature: SignatureAlgorithm::ECDSA, + hash: HashAlgorithm::SHA256, + group: NamedGroup::Secp256r1, + } + ); + } +} diff --git a/third_party/dimpl/src/crypto/ccm_cipher.rs b/third_party/dimpl/src/crypto/ccm_cipher.rs new file mode 100644 index 0000000..463ecd5 --- /dev/null +++ b/third_party/dimpl/src/crypto/ccm_cipher.rs @@ -0,0 +1,88 @@ +//! AES-128-CCM-8 cipher implementation using the RustCrypto `ccm` crate. +//! +//! Shared by both aws-lc-rs and rust-crypto backends since aws-lc-rs +//! does not expose CCM in its high-level API. + +use ccm::aead::AeadInPlace; +use ccm::aead::KeyInit; +use ccm::consts::{U8, U12}; + +use super::{Aad, Cipher, Nonce}; +use crate::buffer::{Buf, TmpBuf}; +use crate::error::bounded_error_len; +use crate::{CryptoError, CryptoOperation}; + +/// AES-128-CCM with 8-byte tag, 12-byte nonce. +type Aes128Ccm8 = ccm::Ccm; + +/// AES-128-CCM-8 cipher for TLS_PSK_WITH_AES_128_CCM_8. +pub struct AesCcm8Cipher { + cipher: Box, +} + +impl std::fmt::Debug for AesCcm8Cipher { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AesCcm8Cipher").finish_non_exhaustive() + } +} + +impl AesCcm8Cipher { + pub fn new(key: &[u8]) -> Result { + if key.len() != 16 { + return Err(CryptoError::InvalidAes128Ccm8KeySize { + actual: bounded_error_len(key.len()), + }); + } + let cipher = Aes128Ccm8::new_from_slice(key) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?; + Ok(AesCcm8Cipher { + cipher: Box::new(cipher), + }) + } +} + +impl Cipher for AesCcm8Cipher { + fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + let ccm_nonce = ccm::aead::generic_array::GenericArray::from_slice(&nonce[..12]); + let tag = self + .cipher + .encrypt_in_place_detached(ccm_nonce, &aad[..], plaintext.as_mut()) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; + + // Append the 8-byte tag + plaintext.extend_from_slice(&tag); + + Ok(()) + } + + fn decrypt( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + if ciphertext.len() < 8 { + return Err(CryptoError::CiphertextTooShort { + minimum: 8, + actual: ciphertext.len() as u8, + }); + } + + let ccm_nonce = ccm::aead::generic_array::GenericArray::from_slice(&nonce[..12]); + + // Split off the 8-byte tag from the end + let data_len = ciphertext.len() - 8; + let mut tag_bytes = [0u8; 8]; + tag_bytes.copy_from_slice(&ciphertext.as_ref()[data_len..]); + let tag = ccm::aead::generic_array::GenericArray::from(tag_bytes); + + // Truncate to just the ciphertext (without tag) + ciphertext.truncate(data_len); + + self.cipher + .decrypt_in_place_detached(ccm_nonce, &aad[..], ciphertext.as_mut(), &tag) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + + Ok(()) + } +} diff --git a/third_party/dimpl/src/crypto/dtls_aead.rs b/third_party/dimpl/src/crypto/dtls_aead.rs new file mode 100644 index 0000000..f9a1866 --- /dev/null +++ b/third_party/dimpl/src/crypto/dtls_aead.rs @@ -0,0 +1,207 @@ +//! DTLS AEAD record formatting types and constants. +//! +//! This module contains types and constants specific to DTLS AEAD record formatting, +//! separate from the pluggable crypto provider abstraction. + +use arrayvec::ArrayVec; + +use crate::types::{ContentType, Sequence}; + +/// Explicit nonce length for DTLS AEAD records. +/// +/// The explicit nonce is transmitted with each record. +#[cfg(test)] +pub(crate) const DTLS_EXPLICIT_NONCE_LEN: usize = 8; + +/// GCM authentication tag length. +/// +/// The tag is appended to the ciphertext. +#[cfg(test)] +pub(crate) const GCM_TAG_LEN: usize = 16; + +/// Overhead per DTLS 1.2 AES-GCM record (explicit nonce + tag). +/// +/// This equals 24 bytes for DTLS AES-GCM. +#[cfg(test)] +pub(crate) const DTLS_AEAD_OVERHEAD: usize = DTLS_EXPLICIT_NONCE_LEN + GCM_TAG_LEN; // 24 + +/// Compute AAD length from plaintext length for DTLS 1.2 AES-GCM records. +#[inline] +#[cfg(test)] +pub fn aad_len_from_plaintext_len(plaintext_len: u16) -> u16 { + plaintext_len +} + +/// Compute fragment length from plaintext length for DTLS 1.2 AES-GCM records. +/// fragment_len = explicit_nonce(8) + ciphertext(plaintext_len + 16 tag) +#[inline] +#[cfg(test)] +pub fn fragment_len_from_plaintext_len(plaintext_len: usize) -> usize { + DTLS_EXPLICIT_NONCE_LEN + plaintext_len + GCM_TAG_LEN +} + +/// Compute plaintext length from fragment length for DTLS 1.2 AES-GCM records. +/// Returns None if the fragment is smaller than the mandatory AEAD overhead. +#[inline] +#[cfg(test)] +pub fn plaintext_len_from_fragment_len(fragment_len: usize) -> Option { + fragment_len.checked_sub(DTLS_AEAD_OVERHEAD) +} + +/// Fixed IV portion for DTLS AEAD. +/// +/// DTLS 1.2 uses: +/// - AES-GCM: 4-byte fixed IV + 8-byte explicit nonce (per record) +/// - ChaCha20-Poly1305: 12-byte fixed IV + 0-byte explicit nonce +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Iv { + bytes: [u8; 12], + len: u8, +} + +impl Iv { + pub(crate) fn new(iv: &[u8]) -> Self { + assert!( + iv.len() <= 12, + "invalid IV length: expected <= 12, got {}", + iv.len() + ); + let mut bytes = [0u8; 12]; + bytes[..iv.len()].copy_from_slice(iv); + Self { + bytes, + len: iv.len() as u8, + } + } + + pub(crate) fn len(&self) -> usize { + self.len as usize + } + + pub(crate) fn as_slice(&self) -> &[u8] { + &self.bytes[..self.len()] + } + + /// Returns the full 12-byte backing array. + /// + /// Only valid for 12-byte IVs (ChaCha20-Poly1305). For 4-byte IVs + /// (AES-GCM), use [`as_slice`] instead. + pub(crate) fn as_12_bytes(&self) -> &[u8; 12] { + assert_eq!( + self.len(), + 12, + "as_12_bytes called on {}-byte IV", + self.len() + ); + &self.bytes + } +} + +/// Full AEAD nonce (fixed IV + explicit nonce). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Nonce(pub [u8; 12]); + +impl Nonce { + /// Create a new AEAD nonce by combining fixed IV and explicit nonce (DTLS 1.2). + pub(crate) fn new(iv: Iv, explicit_nonce: &[u8]) -> Self { + assert_eq!( + iv.len() + explicit_nonce.len(), + 12, + "invalid DTLS 1.2 nonce parts: iv_len={}, explicit_nonce_len={}", + iv.len(), + explicit_nonce.len() + ); + let mut nonce = [0u8; 12]; + let iv_len = iv.len(); + nonce[..iv_len].copy_from_slice(iv.as_slice()); + nonce[iv_len..].copy_from_slice(explicit_nonce); + Self(nonce) + } + + /// Create a nonce by XORing the IV with the padded sequence number. + /// + /// Used by both DTLS 1.2 (ChaCha20-Poly1305) and DTLS 1.3: + /// nonce = iv XOR pad_left(sequence_number, 12) + /// See RFC 8446 Section 5.3 / RFC 7905. + pub(crate) fn xor(iv: &[u8; 12], seq: u64) -> Self { + let mut nonce = *iv; + let seq_bytes = seq.to_be_bytes(); // 8 bytes + // XOR the last 8 bytes of the 12-byte IV with the sequence number + for i in 0..8 { + nonce[4 + i] ^= seq_bytes[i]; + } + Self(nonce) + } +} + +/// Additional Authenticated Data for DTLS records. +/// +/// Variable-length to support both DTLS 1.2 (13 bytes) and DTLS 1.3 (3-5 bytes). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Aad(pub ArrayVec); + +impl Aad { + /// Create Additional Authenticated Data for a DTLS 1.2 record. + pub(crate) fn new_dtls12(content_type: ContentType, sequence: Sequence, length: u16) -> Self { + let mut aad = ArrayVec::new(); + + // First set the full 8-byte sequence number + let seq_bytes = sequence.sequence_number.to_be_bytes(); + aad.try_extend_from_slice(&seq_bytes).unwrap(); + + // Overwrite the first 2 bytes with epoch + let epoch_bytes = sequence.epoch.to_be_bytes(); + aad[0] = epoch_bytes[0]; + aad[1] = epoch_bytes[1]; + + // Content type at index 8 + aad.push(content_type.as_u8()); + + // Protocol version bytes (major:minor) at indexes 9-10 + aad.push(0xfe); // DTLS 1.2 major version + aad.push(0xfd); // DTLS 1.2 minor version + + // Payload length (2 bytes) at indexes 11-12 + aad.try_extend_from_slice(&length.to_be_bytes()).unwrap(); + + Aad(aad) + } + + /// Create Additional Authenticated Data for a DTLS 1.3 record. + /// + /// The AAD is the raw unified header bytes (3-5 bytes). + pub(crate) fn new_dtls13(header_bytes: &[u8]) -> Self { + let mut aad = ArrayVec::new(); + // unwrap: header_bytes is at most 5 bytes, well within capacity 13 + aad.try_extend_from_slice(header_bytes).unwrap(); + Aad(aad) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aead_constants_and_length_helpers() { + assert_eq!(DTLS_EXPLICIT_NONCE_LEN, 8); + assert_eq!(GCM_TAG_LEN, 16); + assert_eq!(DTLS_AEAD_OVERHEAD, 24); + + for &pt_len in &[0usize, 1, 37, 512, 1350, 16384] { + let aad_len = aad_len_from_plaintext_len(pt_len as u16); + assert_eq!(aad_len as usize, pt_len); + + let frag_len = fragment_len_from_plaintext_len(pt_len); + assert_eq!(frag_len, DTLS_EXPLICIT_NONCE_LEN + pt_len + GCM_TAG_LEN); + + let roundtrip = + plaintext_len_from_fragment_len(frag_len).expect("frag_len >= overhead"); + assert_eq!(roundtrip, pt_len); + } + + assert!(plaintext_len_from_fragment_len(0).is_none()); + assert!(plaintext_len_from_fragment_len(3).is_none()); + assert!(plaintext_len_from_fragment_len(DTLS_AEAD_OVERHEAD - 1).is_none()); + } +} diff --git a/third_party/dimpl/src/crypto/keying.rs b/third_party/dimpl/src/crypto/keying.rs new file mode 100644 index 0000000..b53ebb8 --- /dev/null +++ b/third_party/dimpl/src/crypto/keying.rs @@ -0,0 +1,71 @@ +//! SRTP keying material types and profiles used by DTLS-SRTP. +use std::ops::Deref; + +/// Keying material used as master key for SRTP. +pub struct KeyingMaterial(Vec); + +impl KeyingMaterial { + /// Create a new wrapper for DTLS-SRTP keying material bytes. + pub fn new(m: &[u8]) -> Self { + KeyingMaterial(m.to_vec()) + } +} + +impl Deref for KeyingMaterial { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::fmt::Debug for KeyingMaterial { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "KeyingMaterial") + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(non_camel_case_types)] +#[non_exhaustive] +/// Supported SRTP protection profiles (RFC 5764). +pub enum SrtpProfile { + /// SRTP_AES128_CM_HMAC_SHA1_80 (RFC 5764) + AES128_CM_SHA1_80, + /// AEAD_AES_128_GCM (RFC 7714) + AEAD_AES_128_GCM, + /// AEAD_AES_256_GCM (RFC 7714) + AEAD_AES_256_GCM, +} + +impl SrtpProfile { + /// All supported profiles ordered by preference. + pub const ALL: &'static [SrtpProfile] = &[ + SrtpProfile::AEAD_AES_256_GCM, + SrtpProfile::AEAD_AES_128_GCM, + SrtpProfile::AES128_CM_SHA1_80, + ]; + + /// The length of keying material to extract from the DTLS session in bytes. + #[rustfmt::skip] + pub fn keying_material_len(&self) -> usize { + match self { + // MASTER_KEY_LEN * 2 + MASTER_SALT * 2 + // TODO: This is a duplication of info that is held in srtp.rs, because we + // don't want a dependency in that direction. + SrtpProfile::AES128_CM_SHA1_80 => 16 * 2 + 14 * 2, + SrtpProfile::AEAD_AES_128_GCM => 16 * 2 + 12 * 2, + SrtpProfile::AEAD_AES_256_GCM => 32 * 2 + 12 * 2, + } + } +} + +impl std::fmt::Display for SrtpProfile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SrtpProfile::AES128_CM_SHA1_80 => write!(f, "SRTP_AES128_CM_SHA1_80"), + SrtpProfile::AEAD_AES_128_GCM => write!(f, "SRTP_AEAD_AES_128_GCM"), + SrtpProfile::AEAD_AES_256_GCM => write!(f, "SRTP_AEAD_AES_256_GCM"), + } + } +} diff --git a/third_party/dimpl/src/crypto/mod.rs b/third_party/dimpl/src/crypto/mod.rs new file mode 100644 index 0000000..68ee710 --- /dev/null +++ b/third_party/dimpl/src/crypto/mod.rs @@ -0,0 +1,62 @@ +//! Cryptographic primitives and helpers used by the DTLS engine. + +use std::ops::Deref; + +// Internal module imports +mod keying; + +// Provider traits and implementations +#[cfg(feature = "aws-lc-rs")] +pub mod aws_lc_rs; + +#[cfg(feature = "rust-crypto")] +pub mod rust_crypto; + +#[cfg(any(feature = "aws-lc-rs", feature = "rust-crypto"))] +pub(crate) mod ccm_cipher; + +mod dtls_aead; +pub mod prf_hkdf; +mod provider; +mod validation; + +pub use keying::{KeyingMaterial, SrtpProfile}; + +// Re-export AEAD types needed for Cipher trait implementations (public API) +pub use dtls_aead::{Aad, Nonce}; + +// Re-export internal AEAD constants/types for crate-internal use +pub(crate) use dtls_aead::Iv; + +// Re-export buffer types for provider trait implementations +pub use crate::buffer::{Buf, TmpBuf}; + +// Re-export all provider traits and types (similar to rustls structure) +// This allows users to do: use dimpl::crypto::{CryptoProvider, SupportedDtls12CipherSuite, ...}; +pub use provider::{ + ActiveKeyExchange, Cipher, CryptoProvider, CryptoSafe, HashContext, HashProvider, HmacProvider, + KeyProvider, SecureRandom, SignatureVerifier, SigningKey, SupportedDtls12CipherSuite, + SupportedDtls13CipherSuite, SupportedKxGroup, check_verify_scheme, +}; +#[cfg(feature = "_crypto-common")] +pub use provider::{OID_P256, OID_P384, cert_named_group}; + +// Re-export shared types for provider trait implementations +pub use crate::dtls12::message::Dtls12CipherSuite; +pub use crate::types::{ + Dtls13CipherSuite, HashAlgorithm, NamedGroup, SignatureAlgorithm, SignatureScheme, +}; + +impl Deref for Aad { + type Target = [u8]; + fn deref(&self) -> &Self::Target { + &self.0[..] + } +} + +impl Deref for Nonce { + type Target = [u8]; + fn deref(&self) -> &Self::Target { + &self.0 + } +} diff --git a/third_party/dimpl/src/crypto/prf_hkdf.rs b/third_party/dimpl/src/crypto/prf_hkdf.rs new file mode 100644 index 0000000..81eb22d --- /dev/null +++ b/third_party/dimpl/src/crypto/prf_hkdf.rs @@ -0,0 +1,538 @@ +//! PRF and HKDF key derivation built on top of [`HmacProvider`]. +//! +//! Both TLS 1.2 PRF and TLS 1.3 HKDF are pure compositions of HMAC calls. +//! This module provides generic implementations so that crypto backends only +//! need to implement [`HmacProvider`] — no separate PRF or HKDF providers. + +use crate::CryptoError; +use crate::buffer::Buf; +use crate::types::HashAlgorithm; + +use super::HmacProvider; + +/// Maximum HMAC output size we support (SHA-384 = 48 bytes). +const MAX_HASH_LEN: usize = 48; + +// ============================================================================ +// TLS 1.2 PRF (RFC 5246 Section 5) +// ============================================================================ + +/// TLS 1.2 PRF: `PRF(secret, label, seed)` writing `output_len` bytes to `out`. +/// +/// Uses `scratch` for temporary concatenation of label+seed. +#[allow(clippy::too_many_arguments)] +pub fn prf_tls12( + hmac: &dyn HmacProvider, + secret: &[u8], + label: &str, + seed: &[u8], + out: &mut Buf, + output_len: usize, + scratch: &mut Buf, + hash: HashAlgorithm, +) -> Result<(), CryptoError> { + let mut hmac_a = [0u8; MAX_HASH_LEN]; + + // Build label + seed + scratch.clear(); + scratch.extend_from_slice(label.as_bytes()); + scratch.extend_from_slice(seed); + let label_seed = scratch.as_ref(); + + // A(1) = HMAC(secret, label_seed) + let hash_len = hmac.hmac(hash, secret, label_seed, &mut hmac_a)?; + + // Build payload = A(i) || label || seed + scratch.clear(); + scratch.extend_from_slice(&hmac_a[..hash_len]); + scratch.extend_from_slice(label.as_bytes()); + scratch.extend_from_slice(seed); + let payload = scratch.as_mut(); + + out.clear(); + while out.len() < output_len { + // P(i) = HMAC(secret, A(i) || label || seed) + let mut hmac_block = [0u8; MAX_HASH_LEN]; + let block_len = hmac.hmac(hash, secret, payload, &mut hmac_block)?; + + let remaining = output_len - out.len(); + let to_copy = remaining.min(block_len); + out.extend_from_slice(&hmac_block[..to_copy]); + + if out.len() < output_len { + // A(i+1) = HMAC(secret, A(i)) + hmac.hmac(hash, secret, &payload[..hash_len], &mut hmac_a)?; + payload[..hash_len].copy_from_slice(&hmac_a[..hash_len]); + } + } + + Ok(()) +} + +// ============================================================================ +// HKDF (RFC 5869) +// ============================================================================ + +/// HKDF-Extract: `PRK = HMAC-Hash(salt, IKM)`. +pub fn hkdf_extract( + hmac: &dyn HmacProvider, + hash: HashAlgorithm, + salt: &[u8], + ikm: &[u8], + out: &mut Buf, +) -> Result<(), CryptoError> { + out.clear(); + + let hash_len = hash.output_len(); + let zero_salt: Vec; + let actual_salt = if salt.is_empty() { + zero_salt = vec![0u8; hash_len]; + &zero_salt[..] + } else { + salt + }; + + let mut prk = [0u8; MAX_HASH_LEN]; + let prk_len = hmac.hmac(hash, actual_salt, ikm, &mut prk)?; + out.extend_from_slice(&prk[..prk_len]); + Ok(()) +} + +/// HKDF-Expand: expand `prk` to `output_len` bytes. +pub fn hkdf_expand( + hmac: &dyn HmacProvider, + hash: HashAlgorithm, + prk: &[u8], + info: &[u8], + out: &mut Buf, + output_len: usize, +) -> Result<(), CryptoError> { + let hash_len = hash.output_len(); + let n = output_len.div_ceil(hash_len); + if n > 255 { + return Err(CryptoError::HkdfOutputTooLong); + } + + let mut t_prev = [0u8; MAX_HASH_LEN]; + let mut t_prev_len = 0usize; + + out.clear(); + for i in 1..=n { + let mut input = Vec::with_capacity(t_prev_len + info.len() + 1); + input.extend_from_slice(&t_prev[..t_prev_len]); + input.extend_from_slice(info); + input.push(i as u8); + + t_prev_len = hmac.hmac(hash, prk, &input, &mut t_prev)?; + + let remaining = output_len - out.len(); + let to_copy = remaining.min(t_prev_len); + out.extend_from_slice(&t_prev[..to_copy]); + } + + Ok(()) +} + +/// HKDF-Expand-Label for TLS 1.3 (RFC 8446 Section 7.1). +/// +/// Uses the `"tls13 "` prefix. +pub fn hkdf_expand_label( + hmac: &dyn HmacProvider, + hash: HashAlgorithm, + secret: &[u8], + label: &[u8], + context: &[u8], + out: &mut Buf, + output_len: usize, +) -> Result<(), CryptoError> { + let info = build_hkdf_label(b"tls13 ", label, context, output_len)?; + hkdf_expand(hmac, hash, secret, &info, out, output_len) +} + +/// HKDF-Expand-Label for DTLS 1.3 (RFC 9147). +/// +/// Uses the `"dtls13"` prefix (no trailing space). +pub fn hkdf_expand_label_dtls13( + hmac: &dyn HmacProvider, + hash: HashAlgorithm, + secret: &[u8], + label: &[u8], + context: &[u8], + out: &mut Buf, + output_len: usize, +) -> Result<(), CryptoError> { + let info = build_hkdf_label(b"dtls13", label, context, output_len)?; + hkdf_expand(hmac, hash, secret, &info, out, output_len) +} + +/// Build the HkdfLabel structure. +/// +/// ```text +/// struct { +/// uint16 length; +/// opaque label<6..255> = prefix + Label; +/// opaque context<0..255> = Context; +/// } HkdfLabel; +/// ``` +fn build_hkdf_label( + prefix: &[u8], + label: &[u8], + context: &[u8], + output_len: usize, +) -> Result, CryptoError> { + let full_label_len = prefix.len() + label.len(); + + if full_label_len > 255 { + return Err(CryptoError::HkdfLabelTooLong); + } + if context.len() > 255 { + return Err(CryptoError::HkdfContextTooLong); + } + if output_len > 65535 { + return Err(CryptoError::HkdfOutputLengthTooLarge); + } + + let info_len = 2 + 1 + full_label_len + 1 + context.len(); + let mut info = Vec::with_capacity(info_len); + + // uint16 length + info.extend_from_slice(&(output_len as u16).to_be_bytes()); + // opaque label + info.push(full_label_len as u8); + info.extend_from_slice(prefix); + info.extend_from_slice(label); + // opaque context + info.push(context.len() as u8); + info.extend_from_slice(context); + + Ok(info) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex_to_vec(hex: &str) -> Vec { + let hex = hex.replace([' ', '\n'], ""); + let mut v = Vec::new(); + for i in 0..hex.len() / 2 { + // unwrap: test-only hex parsing + let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap(); + v.push(byte); + } + v + } + + fn slice_to_hex(data: &[u8]) -> String { + let mut s = String::new(); + for byte in data.iter() { + s.push_str(&format!("{:02x}", byte)); + } + s + } + + /// Convert an ASCII hex array into a byte array at compile time. + macro_rules! hex_as_bytes { + ($input:expr) => {{ + const fn from_hex_char(c: u8) -> u8 { + match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + b'A'..=b'F' => c - b'A' + 10, + _ => panic!("Invalid hex character"), + } + } + + const INPUT: &[u8] = $input; + const LEN: usize = INPUT.len(); + const OUTPUT_LEN: usize = LEN / 2; + + const fn convert() -> [u8; OUTPUT_LEN] { + assert!(LEN % 2 == 0, "Hex string length must be even"); + + let mut out = [0u8; OUTPUT_LEN]; + let mut i = 0; + while i < LEN { + out[i / 2] = (from_hex_char(INPUT[i]) << 4) | from_hex_char(INPUT[i + 1]); + i += 2; + } + out + } + + convert() + }}; + } + + /// We need a concrete HmacProvider for tests. Use the default feature-gated one. + fn hmac_provider() -> &'static dyn HmacProvider { + #[cfg(feature = "aws-lc-rs")] + { + &crate::crypto::aws_lc_rs::hmac::HMAC_PROVIDER + } + #[cfg(all(not(feature = "aws-lc-rs"), feature = "rust-crypto"))] + { + &crate::crypto::rust_crypto::hmac::HMAC_PROVIDER + } + } + + // ======================================================================== + // HMAC-SHA-256 Test Vectors from RFC 4231 + // ======================================================================== + + #[test] + fn hmac_sha256_test_case_1() { + let key = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + let data = b"Hi There"; + let expected = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; + + let result = hmac_provider().hmac_sha256(&key, data).unwrap(); + assert_eq!(slice_to_hex(&result), expected); + } + + #[test] + fn hmac_sha256_test_case_2() { + let key = b"Jefe"; + let data = b"what do ya want for nothing?"; + let expected = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"; + + let result = hmac_provider().hmac_sha256(key, data).unwrap(); + assert_eq!(slice_to_hex(&result), expected); + } + + #[test] + fn hmac_sha256_test_case_3() { + let key = hex_to_vec("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + let data = hex_to_vec( + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\ + dddddddddddddddddddddddddddddddddddd", + ); + let expected = "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"; + + let result = hmac_provider().hmac_sha256(&key, &data).unwrap(); + assert_eq!(slice_to_hex(&result), expected); + } + + #[test] + fn hmac_sha256_test_case_4() { + let key = hex_to_vec("0102030405060708090a0b0c0d0e0f10111213141516171819"); + let data = hex_to_vec( + "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd\ + cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", + ); + let expected = "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"; + + let result = hmac_provider().hmac_sha256(&key, &data).unwrap(); + assert_eq!(slice_to_hex(&result), expected); + } + + #[test] + fn hmac_sha256_test_case_6() { + // Test with a key larger than block size (> 64 bytes) + let key = vec![0xaa; 131]; + let data = b"Test Using Larger Than Block-Size Key - Hash Key First"; + let expected = "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"; + + let result = hmac_provider().hmac_sha256(&key, data).unwrap(); + assert_eq!(slice_to_hex(&result), expected); + } + + #[test] + fn hmac_sha256_test_case_7() { + // Test with a key larger than block size and large data + let key = vec![0xaa; 131]; + let data = + b"This is a test using a larger than block-size key and a larger than block-size \ + data. The key needs to be hashed before being used by the HMAC algorithm."; + let expected = "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"; + + let result = hmac_provider().hmac_sha256(&key, data).unwrap(); + assert_eq!(slice_to_hex(&result), expected); + } + + // ======================================================================== + // TLS 1.2 PRF + // ======================================================================== + + #[test] + fn prf_tls12_sha256() { + // Test vector from https://github.com/xomexh/TLS-PRF + let mut output = Buf::new(); + let mut scratch = Buf::new(); + prf_tls12( + hmac_provider(), + &hex_as_bytes!(b"9bbe436ba940f017b17652849a71db35"), + "test label", + &hex_as_bytes!(b"a0ba9f936cda311827a6f796ffd5198c"), + &mut output, + 100, + &mut scratch, + HashAlgorithm::SHA256, + ) + .unwrap(); + assert_eq!( + output.as_ref(), + &hex_as_bytes!( + b"e3f229ba727be17b8d122620557cd453c2aab21d\ + 07c3d495329b52d4e61edb5a6b301791e90d35c9\ + c9a46b4e14baf9af0fa022f7077def17abfd3797\ + c0564bab4fbc91666e9def9b97fce34f796789ba\ + a48082d122ee42c5a72e5a5110fff70187347b66" + ) + ); + } + + // ======================================================================== + // HKDF Test Vectors from RFC 5869 + // ======================================================================== + + #[test] + fn hkdf_sha256_rfc5869_case1() { + // Test Case 1 - Basic test case with SHA-256 + let ikm = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + let salt = hex_to_vec("000102030405060708090a0b0c"); + let info = hex_to_vec("f0f1f2f3f4f5f6f7f8f9"); + let expected_prk = "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"; + let expected_okm = "3cb25f25faacd57a90434f64d0362f2a\ + 2d2d0a90cf1a5a4c5db02d56ecc4c5bf\ + 34007208d5b887185865"; + + let h = hmac_provider(); + + let mut prk = Buf::new(); + hkdf_extract(h, HashAlgorithm::SHA256, &salt, &ikm, &mut prk).unwrap(); + assert_eq!(slice_to_hex(prk.as_ref()), expected_prk); + + let mut okm = Buf::new(); + hkdf_expand(h, HashAlgorithm::SHA256, prk.as_ref(), &info, &mut okm, 42).unwrap(); + assert_eq!(slice_to_hex(okm.as_ref()), expected_okm); + } + + #[test] + fn hkdf_sha256_rfc5869_case2() { + // Test Case 2 - Longer inputs/outputs with SHA-256 + let ikm = hex_to_vec( + "000102030405060708090a0b0c0d0e0f\ + 101112131415161718191a1b1c1d1e1f\ + 202122232425262728292a2b2c2d2e2f\ + 303132333435363738393a3b3c3d3e3f\ + 404142434445464748494a4b4c4d4e4f", + ); + let salt = hex_to_vec( + "606162636465666768696a6b6c6d6e6f\ + 707172737475767778797a7b7c7d7e7f\ + 808182838485868788898a8b8c8d8e8f\ + 909192939495969798999a9b9c9d9e9f\ + a0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + ); + let info = hex_to_vec( + "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf\ + c0c1c2c3c4c5c6c7c8c9cacbcccdcecf\ + d0d1d2d3d4d5d6d7d8d9dadbdcdddedf\ + e0e1e2e3e4e5e6e7e8e9eaebecedeeef\ + f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", + ); + let expected_prk = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244"; + let expected_okm = "b11e398dc80327a1c8e7f78c596a4934\ + 4f012eda2d4efad8a050cc4c19afa97c\ + 59045a99cac7827271cb41c65e590e09\ + da3275600c2f09b8367793a9aca3db71\ + cc30c58179ec3e87c14c01d5c1f3434f\ + 1d87"; + + let h = hmac_provider(); + + let mut prk = Buf::new(); + hkdf_extract(h, HashAlgorithm::SHA256, &salt, &ikm, &mut prk).unwrap(); + assert_eq!(slice_to_hex(prk.as_ref()), expected_prk); + + let mut okm = Buf::new(); + hkdf_expand(h, HashAlgorithm::SHA256, prk.as_ref(), &info, &mut okm, 82).unwrap(); + assert_eq!(slice_to_hex(okm.as_ref()), expected_okm); + } + + #[test] + fn hkdf_sha256_rfc5869_case3() { + // Test Case 3 - Zero-length salt and info with SHA-256 + let ikm = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + let salt = vec![]; + let info = vec![]; + let expected_prk = "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04"; + let expected_okm = "8da4e775a563c18f715f802a063c5a31\ + b8a11f5c5ee1879ec3454e5f3c738d2d\ + 9d201395faa4b61a96c8"; + + let h = hmac_provider(); + + let mut prk = Buf::new(); + hkdf_extract(h, HashAlgorithm::SHA256, &salt, &ikm, &mut prk).unwrap(); + assert_eq!(slice_to_hex(prk.as_ref()), expected_prk); + + let mut okm = Buf::new(); + hkdf_expand(h, HashAlgorithm::SHA256, prk.as_ref(), &info, &mut okm, 42).unwrap(); + assert_eq!(slice_to_hex(okm.as_ref()), expected_okm); + } + + // ======================================================================== + // HKDF-Expand-Label + // ======================================================================== + + #[test] + fn hkdf_expand_label_basic() { + let h = hmac_provider(); + let secret = [0u8; 32]; + let mut out = Buf::new(); + + hkdf_expand_label(h, HashAlgorithm::SHA256, &secret, b"key", &[], &mut out, 16).unwrap(); + assert_eq!(out.len(), 16); + + hkdf_expand_label( + h, + HashAlgorithm::SHA256, + &secret, + b"iv", + &[1, 2, 3, 4], + &mut out, + 12, + ) + .unwrap(); + assert_eq!(out.len(), 12); + } + + #[test] + fn hkdf_expand_label_dtls13_basic() { + let h = hmac_provider(); + let secret = [0u8; 32]; + let mut out = Buf::new(); + + hkdf_expand_label_dtls13(h, HashAlgorithm::SHA256, &secret, b"key", &[], &mut out, 16) + .unwrap(); + assert_eq!(out.len(), 16); + + // TLS 1.3 and DTLS 1.3 with same inputs should produce different outputs + let mut tls_out = Buf::new(); + let mut dtls_out = Buf::new(); + + hkdf_expand_label( + h, + HashAlgorithm::SHA256, + &secret, + b"key", + &[], + &mut tls_out, + 16, + ) + .unwrap(); + hkdf_expand_label_dtls13( + h, + HashAlgorithm::SHA256, + &secret, + b"key", + &[], + &mut dtls_out, + 16, + ) + .unwrap(); + + assert_ne!(tls_out.as_ref(), dtls_out.as_ref()); + } +} diff --git a/third_party/dimpl/src/crypto/provider.rs b/third_party/dimpl/src/crypto/provider.rs new file mode 100644 index 0000000..a4f0af0 --- /dev/null +++ b/third_party/dimpl/src/crypto/provider.rs @@ -0,0 +1,665 @@ +//! Cryptographic provider traits for pluggable crypto backends. +//! +//! This module defines the trait-based interface for cryptographic operations +//! in dimpl, allowing users to provide custom crypto implementations. +//! +//! # Overview +//! +//! The crypto provider system is inspired by rustls's design and uses a component-based +//! approach where the [`CryptoProvider`] struct holds static references to various +//! trait objects, each representing a specific cryptographic capability. +//! +//! # Architecture +//! +//! The provider system is organized into these main components: +//! +//! - **Cipher Suites** ([`SupportedDtls12CipherSuite`]): Factory for AEAD ciphers +//! - **Key Exchange Groups** ([`SupportedKxGroup`]): Factory for ECDHE key exchanges +//! - **Signature Verification** ([`SignatureVerifier`]): Verify signatures in certificates +//! - **Key Provider** ([`KeyProvider`]): Parse and load private keys +//! - **Secure Random** ([`SecureRandom`]): Cryptographically secure RNG +//! - **Hash Provider** ([`HashProvider`]): Factory for hash contexts +//! - **HMAC Provider** ([`HmacProvider`]): Compute HMAC signatures (also drives PRF and HKDF) +//! +//! # Using a Custom Provider +//! +//! To use a custom crypto provider, create one and pass it to the [`Config`](crate::Config): +//! +//! ``` +//! # #[cfg(all(feature = "aws-lc-rs", feature = "rcgen"))] +//! # fn main() { +//! use std::sync::Arc; +//! use std::time::Instant; +//! use dimpl::{Config, Dtls, certificate}; +//! use dimpl::crypto::aws_lc_rs; +//! +//! let cert = certificate::generate_self_signed_certificate().unwrap(); +//! // Use the default aws-lc-rs provider (implicit) +//! let config = Arc::new(Config::default()); +//! +//! // Or explicitly set the provider +//! let config = Arc::new( +//! Config::builder() +//! .with_crypto_provider(aws_lc_rs::default_provider()) +//! .build() +//! .unwrap() +//! ); +//! +//! // Or use your own custom provider +//! // let config = Arc::new( +//! // Config::builder() +//! // .with_crypto_provider(my_custom_provider()) +//! // .build() +//! // .unwrap() +//! // ); +//! +//! let dtls = Dtls::new_12(config, cert, Instant::now()); +//! # } +//! # #[cfg(not(all(feature = "aws-lc-rs", feature = "rcgen")))] +//! # fn main() {} +//! ``` +//! +//! # Implementing a Custom Provider +//! +//! To implement a custom provider, you need to: +//! +//! 1. Implement the required traits for your crypto backend +//! 2. Create static instances of your implementations +//! 3. Build a [`CryptoProvider`] struct with references to those statics +//! +//! ## Example: Custom Cipher Suite +//! +//! ``` +//! use dimpl::CryptoError; +//! use dimpl::crypto::{SupportedDtls12CipherSuite, Cipher, Dtls12CipherSuite, HashAlgorithm}; +//! use dimpl::crypto::{Buf, TmpBuf}; +//! use dimpl::crypto::{Aad, Nonce}; +//! +//! #[derive(Debug)] +//! struct MyCipher; +//! +//! impl MyCipher { +//! fn new(_key: &[u8]) -> Result { +//! Ok(Self) +//! } +//! } +//! +//! impl Cipher for MyCipher { +//! fn encrypt(&mut self, _: &mut Buf, _: Aad, _: Nonce) -> Result<(), CryptoError> { +//! Ok(()) +//! } +//! fn decrypt(&mut self, _: &mut TmpBuf, _: Aad, _: Nonce) -> Result<(), CryptoError> { +//! Ok(()) +//! } +//! } +//! +//! #[derive(Debug)] +//! struct MyDtls12CipherSuite; +//! +//! impl SupportedDtls12CipherSuite for MyDtls12CipherSuite { +//! fn suite(&self) -> Dtls12CipherSuite { +//! Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 +//! } +//! +//! fn hash_algorithm(&self) -> HashAlgorithm { +//! HashAlgorithm::SHA256 +//! } +//! +//! fn key_lengths(&self) -> (usize, usize, usize) { +//! (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) +//! } +//! +//! fn explicit_nonce_len(&self) -> usize { +//! 8 // AES-GCM: 8-byte explicit nonce per record +//! } +//! +//! fn tag_len(&self) -> usize { +//! 16 // 128-bit authentication tag +//! } +//! +//! fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { +//! // Create your cipher implementation here +//! Ok(Box::new(MyCipher::new(key)?)) +//! } +//! } +//! +//! static MY_CIPHER_SUITE: MyDtls12CipherSuite = MyDtls12CipherSuite; +//! static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[&MY_CIPHER_SUITE]; +//! ``` +//! +//! # Requirements +//! +//! For DTLS 1.2, implementations must support: +//! +//! - **Cipher suites**: ECDHE_ECDSA with AES-128-GCM, AES-256-GCM, or CHACHA20_POLY1305 +//! - **Key exchange**: ECDHE with X25519, P-256, or P-384 curves +//! - **Signatures**: ECDSA with P-256/SHA-256 or P-384/SHA-384 +//! - **Hash**: SHA-256 and SHA-384 +//! - **HMAC**: HMAC-SHA256 and HMAC-SHA384 (used for PRF, HKDF, and cookies) +//! +//! # Thread Safety +//! +//! All provider traits require `Send + Sync + UnwindSafe + RefUnwindSafe` to ensure +//! safe usage across threads and panic boundaries. + +use std::fmt::Debug; +use std::panic::{RefUnwindSafe, UnwindSafe}; +use std::sync::OnceLock; + +use crate::buffer::{Buf, TmpBuf}; +use crate::crypto::{Aad, Nonce}; +use crate::dtls12::message::Dtls12CipherSuite; +use crate::types::{Dtls13CipherSuite, HashAlgorithm, NamedGroup, SignatureAlgorithm}; +use crate::{CertificateError, CryptoError}; + +/// OID for the P-256 elliptic curve (secp256r1 / prime256v1). +#[cfg(feature = "_crypto-common")] +pub const OID_P256: spki::ObjectIdentifier = + spki::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"); + +/// OID for the P-384 elliptic curve (secp384r1). +#[cfg(feature = "_crypto-common")] +pub const OID_P384: spki::ObjectIdentifier = spki::ObjectIdentifier::new_unwrap("1.3.132.0.34"); + +// ============================================================================ +// Marker Trait +// ============================================================================ + +/// Marker trait for types that are safe to use in crypto provider components. +/// +/// This trait combines the common bounds required for crypto provider trait objects: +/// - [`Send`] + [`Sync`]: Thread-safe +/// - [`Debug`]: Support debugging +/// - [`UnwindSafe`] + [`RefUnwindSafe`]: Panic-safe +/// +/// This trait is automatically implemented for all types that satisfy these bounds. +pub trait CryptoSafe: Send + Sync + Debug + UnwindSafe + RefUnwindSafe {} + +/// Blanket implementation: any type satisfying the bounds implements [`CryptoSafe`]. +impl CryptoSafe for T {} + +// ============================================================================ +// Instance Traits (Level 2 - created by factories) +// ============================================================================ + +/// AEAD cipher for in-place encryption/decryption. +pub trait Cipher: CryptoSafe { + /// Encrypt plaintext in-place, appending authentication tag. + fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError>; + + /// Decrypt ciphertext in-place, verifying and removing authentication tag. + fn decrypt( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError>; +} + +/// Stateful hash context for incremental hashing. +pub trait HashContext: CryptoSafe { + /// Update the hash with new data. + fn update(&mut self, data: &[u8]); + + /// Clone the context and finalize it, writing the hash to `out`. + /// The original context can continue to be updated. + fn clone_and_finalize(&self, out: &mut Buf); +} + +/// Signing key for generating digital signatures. +pub trait SigningKey: CryptoSafe { + /// Sign data using the specified hash algorithm and return the signature. + fn sign( + &mut self, + data: &[u8], + hash_alg: HashAlgorithm, + out: &mut Buf, + ) -> Result<(), CryptoError>; + + /// Signature algorithm used by this key. + fn algorithm(&self) -> SignatureAlgorithm; + + /// Default hash algorithm for this key. + fn hash_algorithm(&self) -> HashAlgorithm; + + /// Hash algorithms this key can sign with. + /// + /// Used during negotiation to intersect with the peer's offered + /// algorithms. Backends that lock the hash at key-load time (e.g. + /// aws-lc-rs) return only the locked hash; backends that support + /// arbitrary prehash signing (e.g. RustCrypto) may return several. + fn supported_hash_algorithms(&self) -> &[HashAlgorithm]; +} + +/// Active key exchange instance (ephemeral keypair for one handshake). +pub trait ActiveKeyExchange: CryptoSafe { + /// Get the public key for this exchange. + fn pub_key(&self) -> &[u8]; + + /// Complete exchange with peer's public key, returning shared secret. + fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError>; + + /// Get the named group for this exchange. + fn group(&self) -> NamedGroup; +} + +// ============================================================================ +// Factory Traits (Level 1 - used by CryptoProvider) +// ============================================================================ + +/// Cipher suite support (factory for Cipher instances). +pub trait SupportedDtls12CipherSuite: CryptoSafe { + /// The cipher suite this supports. + fn suite(&self) -> Dtls12CipherSuite; + + /// Hash algorithm used by this suite. + fn hash_algorithm(&self) -> HashAlgorithm; + + /// Key material lengths: (mac_key_len, enc_key_len, fixed_iv_len). + fn key_lengths(&self) -> (usize, usize, usize); + + /// Length in bytes of the per-record explicit nonce (carried in the record body). + /// + /// AES-GCM suites carry an 8-byte explicit nonce; ChaCha20-Poly1305 carries none. + fn explicit_nonce_len(&self) -> usize; + + /// AEAD authentication tag length in bytes. + fn tag_len(&self) -> usize; + + /// Minimum length, in bytes, of a protected record's encrypted fragment. + /// + /// For AEAD suites this equals explicit nonce + authentication tag; a CBC + /// suite would override this to `IV + MAC + 1` (one padding byte). Records + /// shorter than this cannot be valid regardless of cipher mode and are + /// rejected at the record boundary. + fn min_protected_fragment_len(&self) -> usize { + self.explicit_nonce_len() + self.tag_len() + } + + /// Create a cipher instance with the given key. + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError>; +} + +/// Key exchange group support (factory for ActiveKeyExchange). +pub trait SupportedKxGroup: CryptoSafe { + /// Named group for this key exchange group. + fn name(&self) -> NamedGroup; + + /// Start a new key exchange, generating ephemeral keypair. + /// The provided `buf` will be used to store the public key. + fn start_exchange(&self, buf: Buf) -> Result, CryptoError>; +} + +/// Signature verification against certificates. +pub trait SignatureVerifier: CryptoSafe { + /// Verify a signature on data using a DER-encoded X.509 certificate. + fn verify_signature( + &self, + cert_der: &[u8], + data: &[u8], + signature: &[u8], + hash_alg: HashAlgorithm, + sig_alg: SignatureAlgorithm, + ) -> Result<(), CryptoError>; +} + +/// Allow-list of supported (signature, hash, curve) combinations for +/// DTLS 1.2 signature verification. +/// +/// In DTLS 1.2 the hash algorithm and the certificate's curve are +/// independent choices, so all cross-combinations are valid. +/// +/// Signature | Hash | Curve +/// -----------+---------+----------- +/// ECDSA | SHA-256 | P-256 +/// ECDSA | SHA-256 | P-384 +/// ECDSA | SHA-384 | P-256 +/// ECDSA | SHA-384 | P-384 +const SUPPORTED_VERIFY_SCHEMES: &[(SignatureAlgorithm, HashAlgorithm, NamedGroup)] = &[ + ( + SignatureAlgorithm::ECDSA, + HashAlgorithm::SHA256, + NamedGroup::Secp256r1, + ), + ( + SignatureAlgorithm::ECDSA, + HashAlgorithm::SHA256, + NamedGroup::Secp384r1, + ), + ( + SignatureAlgorithm::ECDSA, + HashAlgorithm::SHA384, + NamedGroup::Secp256r1, + ), + ( + SignatureAlgorithm::ECDSA, + HashAlgorithm::SHA384, + NamedGroup::Secp384r1, + ), +]; + +/// Check that a (signature, hash, curve) combination is in the allow-list. +pub fn check_verify_scheme( + sig_alg: SignatureAlgorithm, + hash_alg: HashAlgorithm, + group: NamedGroup, +) -> Result<(), CryptoError> { + if SUPPORTED_VERIFY_SCHEMES + .iter() + .any(|(s, h, g)| *s == sig_alg && *h == hash_alg && *g == group) + { + Ok(()) + } else { + Err(CryptoError::UnsupportedSignatureVerification { + signature: sig_alg, + hash: hash_alg, + group, + }) + } +} + +/// Extract the EC curve ([`NamedGroup`]) from a DER-encoded X.509 certificate. +/// +/// Used by DTLS 1.3 to verify that the [`SignatureScheme`](crate::types::SignatureScheme) +/// in `CertificateVerify` is consistent with the peer's certificate key. +#[cfg(feature = "_crypto-common")] +pub fn cert_named_group(cert_der: &[u8]) -> Result { + use der::Decode; + use spki::ObjectIdentifier; + use x509_cert::Certificate as X509Certificate; + + let cert = X509Certificate::from_der(cert_der).map_err(|_| CertificateError::ParseFailed)?; + let spki = &cert.tbs_certificate.subject_public_key_info; + + let curve_oid: ObjectIdentifier = spki + .algorithm + .parameters + .as_ref() + .ok_or(CertificateError::MissingEcCurveParameter)? + .decode_as() + .map_err(|_| CertificateError::InvalidEcCurveParameter)?; + + match curve_oid { + OID_P256 => Ok(NamedGroup::Secp256r1), + OID_P384 => Ok(NamedGroup::Secp384r1), + _ => Err(CertificateError::UnsupportedEcCurve), + } +} + +/// Private key parser (factory for SigningKey). +pub trait KeyProvider: CryptoSafe { + /// Parse and load a private key from DER/PEM bytes. + fn load_private_key(&self, key_der: &[u8]) -> Result, CryptoError>; +} + +/// Secure random number generator. +pub trait SecureRandom: CryptoSafe { + /// Fill buffer with cryptographically secure random bytes. + fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError>; +} + +/// Hash provider (factory for HashContext). +pub trait HashProvider: CryptoSafe { + /// Create a new hash context for the specified algorithm. + fn create_hash(&self, algorithm: HashAlgorithm) -> Box; +} + +/// HMAC provider for computing HMAC signatures. +pub trait HmacProvider: CryptoSafe { + /// Compute HMAC-SHA256(key, data) and return the result. + fn hmac_sha256(&self, key: &[u8], data: &[u8]) -> Result<[u8; 32], CryptoError> { + let mut out = [0u8; 32]; + self.hmac(HashAlgorithm::SHA256, key, data, &mut out)?; + Ok(out) + } + + /// Compute HMAC for the given hash algorithm, writing the result to `out`. + /// + /// Returns the number of bytes written. + fn hmac( + &self, + hash: HashAlgorithm, + key: &[u8], + data: &[u8], + out: &mut [u8], + ) -> Result; +} + +// ============================================================================ +// DTLS 1.3 Factory Traits +// ============================================================================ + +/// Cipher suite support for DTLS 1.3 (factory for Cipher instances). +/// +/// Unlike DTLS 1.2 cipher suites, TLS 1.3 cipher suites only specify the +/// AEAD algorithm and hash function. Key exchange is negotiated separately. +pub trait SupportedDtls13CipherSuite: CryptoSafe { + /// The cipher suite this supports. + fn suite(&self) -> Dtls13CipherSuite; + + /// Hash algorithm used by this suite. + fn hash_algorithm(&self) -> HashAlgorithm; + + /// AEAD key length in bytes. + fn key_len(&self) -> usize; + + /// AEAD nonce/IV length in bytes. + fn iv_len(&self) -> usize; + + /// AEAD tag length in bytes. + fn tag_len(&self) -> usize; + + /// Minimum length, in bytes, of a protected record's encrypted fragment. + /// DTLS 1.3 has no explicit nonce in the record, so this equals + /// [`Self::tag_len`]. Records shorter than this cannot hold a valid + /// ciphertext + tag and are rejected at the record boundary. + fn min_protected_fragment_len(&self) -> usize { + self.tag_len() + } + + /// Create a cipher instance with the given key. + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError>; + + /// Compute a mask for record number encryption (RFC 9147 Section 4.2.3). + /// + /// The mask is XORed over the sequence number bytes in the header. + /// `sample` is the first 16 bytes of the ciphertext. + /// + /// For AES-based suites: `mask = AES-ECB(sn_key, sample)`. + /// + /// For ChaCha20-based suites (RFC 9001 Section 5.4.4): + /// `counter = sample[0..4]` (LE u32), `nonce = sample[4..16]`, + /// `mask = ChaCha20(sn_key, counter, nonce, )`. + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16]; +} + +// ============================================================================ +// Core Provider Struct +// ============================================================================ + +/// Cryptographic provider for DTLS operations. +/// +/// This struct holds references to all cryptographic components needed +/// for DTLS. Users can provide custom implementations of each component +/// to replace the default aws-lc-rs-based provider. +/// +/// # Version-Specific Components +/// +/// Shared components like `kx_groups`, `signature_verification`, `key_provider`, +/// `secure_random`, `hash_provider`, and `hmac_provider` are used by both versions. +/// PRF (TLS 1.2) and HKDF (TLS 1.3) key derivation are built generically on top +/// of `hmac_provider` — see the [`prf_hkdf`](super::prf_hkdf) module. +/// +/// # Design +/// +/// The provider uses static trait object references (`&'static dyn Trait`) which +/// provides zero runtime overhead for trait dispatch. This design is inspired by +/// rustls's CryptoProvider and ensures efficient crypto operations. +/// +/// # Example +/// +/// ``` +/// # #[cfg(feature = "aws-lc-rs")] +/// # fn main() { +/// use dimpl::crypto::{CryptoProvider, aws_lc_rs}; +/// +/// // Use the default provider +/// let provider = aws_lc_rs::default_provider(); +/// +/// // Or build a custom one (using defaults for demonstration) +/// let custom_provider = CryptoProvider { +/// // Shared components +/// kx_groups: provider.kx_groups, +/// signature_verification: provider.signature_verification, +/// key_provider: provider.key_provider, +/// secure_random: provider.secure_random, +/// hash_provider: provider.hash_provider, +/// hmac_provider: provider.hmac_provider, +/// // DTLS 1.2 components +/// cipher_suites: provider.cipher_suites, +/// // DTLS 1.3 components +/// dtls13_cipher_suites: provider.dtls13_cipher_suites, +/// }; +/// # } +/// # #[cfg(not(feature = "aws-lc-rs"))] +/// # fn main() {} +/// ``` +#[derive(Debug, Clone)] +pub struct CryptoProvider { + // ========================================================================= + // Shared components (used by both DTLS 1.2 and DTLS 1.3) + // ========================================================================= + /// Supported key exchange groups (P-256, P-384, X25519). + /// + /// Used for ECDHE key exchange in both DTLS versions. + pub kx_groups: &'static [&'static dyn SupportedKxGroup], + + /// Signature verification for certificates. + pub signature_verification: &'static dyn SignatureVerifier, + + /// Key provider for parsing private keys. + pub key_provider: &'static dyn KeyProvider, + + /// Secure random number generator. + pub secure_random: &'static dyn SecureRandom, + + /// Hash provider for handshake hashing. + pub hash_provider: &'static dyn HashProvider, + + /// HMAC provider for computing HMAC signatures. + pub hmac_provider: &'static dyn HmacProvider, + + // ========================================================================= + // DTLS 1.2 specific components + // ========================================================================= + /// Supported DTLS 1.2 cipher suites (for negotiation). + /// + /// These cipher suites bundle key exchange, authentication, encryption, + /// and MAC algorithms together (e.g., TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). + pub cipher_suites: &'static [&'static dyn SupportedDtls12CipherSuite], + + // ========================================================================= + // DTLS 1.3 specific components + // ========================================================================= + /// Supported DTLS 1.3 cipher suites (for negotiation). + /// + /// TLS 1.3 cipher suites only specify the AEAD and hash algorithms + /// (e.g., TLS_AES_128_GCM_SHA256). Key exchange is negotiated separately. + pub dtls13_cipher_suites: &'static [&'static dyn SupportedDtls13CipherSuite], +} + +/// Static storage for the default crypto provider. +/// +/// This is set by `install_default()` and retrieved by `get_default()`. +static DEFAULT: OnceLock = OnceLock::new(); + +impl CryptoProvider { + /// Install a default crypto provider for the process. + /// + /// This sets a global default provider that will be used by + /// [`Config::builder()`](crate::Config::builder) + /// when no explicit provider is specified. This is useful for applications that want + /// to override the default provider per process. + /// + /// # Panics + /// + /// Panics if called more than once. The default provider can only be set once per process. + /// + /// # Example + /// + /// ``` + /// # #[cfg(feature = "aws-lc-rs")] + /// # fn main() { + /// use dimpl::crypto::{CryptoProvider, aws_lc_rs}; + /// + /// // Install a default provider (can only be called once per process) + /// CryptoProvider::install_default(aws_lc_rs::default_provider()); + /// # } + /// # #[cfg(not(feature = "aws-lc-rs"))] + /// # fn main() {} + /// ``` + pub fn install_default(provider: CryptoProvider) { + DEFAULT + .set(provider) + .expect("CryptoProvider::install_default() called more than once"); + } + + /// Get the default crypto provider, if one has been installed. + /// + /// Returns `Some(&provider)` if a default provider has been installed via + /// [`Self::install_default()`], or `None` if no default provider is available. + /// + /// This method does not panic. Use [`Config::builder()`](crate::Config::builder) which will handle + /// the fallback logic automatically. + /// + /// # Example + /// + /// ``` + /// use dimpl::crypto::CryptoProvider; + /// + /// if let Some(provider) = CryptoProvider::get_default() { + /// // Use the installed default provider + /// } + /// ``` + pub fn get_default() -> Option<&'static CryptoProvider> { + DEFAULT.get() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg(feature = "rcgen")] + fn cert_named_group_p256() { + use rcgen::{CertificateParams, KeyPair, PKCS_ECDSA_P256_SHA256}; + + let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap(); + let params = CertificateParams::new(Vec::::new()).unwrap(); + let cert = params.self_signed(&key_pair).unwrap(); + + let group = cert_named_group(cert.der()).unwrap(); + assert_eq!(group, NamedGroup::Secp256r1); + } + + #[test] + #[cfg(feature = "rcgen")] + fn cert_named_group_p384() { + use rcgen::{CertificateParams, KeyPair, PKCS_ECDSA_P384_SHA384}; + + let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P384_SHA384).unwrap(); + let params = CertificateParams::new(Vec::::new()).unwrap(); + let cert = params.self_signed(&key_pair).unwrap(); + + let group = cert_named_group(cert.der()).unwrap(); + assert_eq!(group, NamedGroup::Secp384r1); + } + + #[test] + #[cfg(feature = "rcgen")] + fn cert_named_group_invalid_der() { + let result = cert_named_group(&[0x00, 0x01, 0x02]); + assert!(result.is_err()); + } +} diff --git a/third_party/dimpl/src/crypto/rust_crypto/cipher_suite.rs b/third_party/dimpl/src/crypto/rust_crypto/cipher_suite.rs new file mode 100644 index 0000000..7c48282 --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/cipher_suite.rs @@ -0,0 +1,482 @@ +//! Cipher suite implementations using RustCrypto. +use aes_gcm::aead::AeadInPlace; +use aes_gcm::aes::cipher::{BlockEncrypt, KeyInit as BlockKeyInit}; +use aes_gcm::aes::{Aes128, Aes256}; +use aes_gcm::{Aes128Gcm, Aes256Gcm, Key}; +use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek}; +use chacha20poly1305::ChaCha20Poly1305 as ChaCha20Poly1305Aead; + +use super::super::{Cipher, SupportedDtls12CipherSuite, SupportedDtls13CipherSuite}; +use crate::buffer::{Buf, TmpBuf}; +use crate::crypto::{Aad, Nonce}; +use crate::dtls12::message::Dtls12CipherSuite; +use crate::error::bounded_error_len; +use crate::types::{Dtls13CipherSuite, HashAlgorithm}; +use crate::{CryptoError, CryptoOperation}; + +/// AES-GCM cipher implementation using RustCrypto. +enum AesGcm { + Aes128(Box), + Aes256(Box), +} + +impl std::fmt::Debug for AesGcm { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + AesGcm::Aes128(_) => f.debug_tuple("AesGcm::Aes128").finish(), + AesGcm::Aes256(_) => f.debug_tuple("AesGcm::Aes256").finish(), + } + } +} + +impl AesGcm { + fn new(key: &[u8]) -> Result { + match key.len() { + 16 => { + let key = Key::::from_slice(key); + Ok(AesGcm::Aes128(Box::new(Aes128Gcm::new(key)))) + } + 32 => { + let key = Key::::from_slice(key); + Ok(AesGcm::Aes256(Box::new(Aes256Gcm::new(key)))) + } + _ => Err(CryptoError::InvalidAesGcmKeySize { + actual: bounded_error_len(key.len()), + }), + } + } +} + +impl Cipher for AesGcm { + fn encrypt(&mut self, data: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + // Create nonce from the provided nonce bytes + let nonce_array: [u8; 12] = nonce[..12] + .try_into() + .map_err(|_| CryptoError::InvalidNonce)?; + + match self { + AesGcm::Aes128(cipher) => { + // Create nonce from fixed-size array - AesNonce is GenericArray + use generic_array::{GenericArray, typenum::U12}; + let aes_nonce = GenericArray::::clone_from_slice(&nonce_array); + cipher + .encrypt_in_place(&aes_nonce, &aad, data) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; + } + AesGcm::Aes256(cipher) => { + // Create nonce from fixed-size array - AesNonce is GenericArray + use generic_array::{GenericArray, typenum::U12}; + let aes_nonce = GenericArray::::clone_from_slice(&nonce_array); + cipher + .encrypt_in_place(&aes_nonce, &aad, data) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; + } + } + + Ok(()) + } + + fn decrypt( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + if ciphertext.len() < 16 { + return Err(CryptoError::CiphertextTooShort { + minimum: 16, + actual: ciphertext.len() as u8, + }); + } + + // Create nonce from the provided nonce bytes + let nonce_array: [u8; 12] = nonce[..12] + .try_into() + .map_err(|_| CryptoError::InvalidNonce)?; + + match self { + AesGcm::Aes128(cipher) => { + // Create nonce from fixed-size array - AesNonce is GenericArray + use generic_array::{GenericArray, typenum::U12}; + let aes_nonce = GenericArray::::clone_from_slice(&nonce_array); + cipher + .decrypt_in_place(&aes_nonce, &aad, ciphertext) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + } + AesGcm::Aes256(cipher) => { + // Create nonce from fixed-size array - AesNonce is GenericArray + use generic_array::{GenericArray, typenum::U12}; + let aes_nonce = GenericArray::::clone_from_slice(&nonce_array); + cipher + .decrypt_in_place(&aes_nonce, &aad, ciphertext) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + } + } + + // decrypt_in_place already removes the tag and shortens the buffer + // No need to truncate further + + Ok(()) + } +} + +/// ChaCha20-Poly1305 cipher implementation using RustCrypto. +struct ChaCha20Poly1305Cipher { + cipher: Box, +} + +impl std::fmt::Debug for ChaCha20Poly1305Cipher { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ChaCha20Poly1305Cipher") + .finish_non_exhaustive() + } +} + +impl ChaCha20Poly1305Cipher { + fn new(key: &[u8]) -> Result { + use chacha20poly1305::KeyInit; + if key.len() != 32 { + return Err(CryptoError::InvalidChacha20Poly1305KeySize { + actual: bounded_error_len(key.len()), + }); + } + let key = chacha20poly1305::Key::from_slice(key); + Ok(ChaCha20Poly1305Cipher { + cipher: Box::new(ChaCha20Poly1305Aead::new(key)), + }) + } +} + +impl Cipher for ChaCha20Poly1305Cipher { + fn encrypt(&mut self, data: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> { + let nonce_array: [u8; 12] = nonce[..12] + .try_into() + .map_err(|_| CryptoError::InvalidNonce)?; + + use generic_array::{GenericArray, typenum::U12}; + let chacha_nonce = GenericArray::::clone_from_slice(&nonce_array); + self.cipher + .encrypt_in_place(&chacha_nonce, &aad, data) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?; + + Ok(()) + } + + fn decrypt( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + if ciphertext.len() < 16 { + return Err(CryptoError::CiphertextTooShort { + minimum: 16, + actual: ciphertext.len() as u8, + }); + } + + let nonce_array: [u8; 12] = nonce[..12] + .try_into() + .map_err(|_| CryptoError::InvalidNonce)?; + + use generic_array::{GenericArray, typenum::U12}; + let chacha_nonce = GenericArray::::clone_from_slice(&nonce_array); + self.cipher + .decrypt_in_place(&chacha_nonce, &aad, ciphertext) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?; + + Ok(()) + } +} + +/// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipher suite. +#[derive(Debug)] +struct Aes128GcmSha256; + +impl SupportedDtls12CipherSuite for Aes128GcmSha256 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 16 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } +} + +/// TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite. +#[derive(Debug)] +struct Aes256GcmSha384; + +impl SupportedDtls12CipherSuite for Aes256GcmSha384 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA384 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 32, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 16 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } +} + +/// TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 cipher suite. +#[derive(Debug)] +struct ChaCha20Poly1305Sha256; + +impl SupportedDtls12CipherSuite for ChaCha20Poly1305Sha256 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 32, 12) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 0 + } + + fn tag_len(&self) -> usize { + 16 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?)) + } +} + +/// TLS_PSK_WITH_AES_128_CCM_8 cipher suite. +#[derive(Debug)] +struct PskAes128Ccm8; + +impl SupportedDtls12CipherSuite for PskAes128Ccm8 { + fn suite(&self) -> Dtls12CipherSuite { + Dtls12CipherSuite::PSK_AES128_CCM_8 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_lengths(&self) -> (usize, usize, usize) { + (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len) + } + + fn explicit_nonce_len(&self) -> usize { + 8 + } + + fn tag_len(&self) -> usize { + 8 + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(crate::crypto::ccm_cipher::AesCcm8Cipher::new( + key, + )?)) + } +} + +/// Static instances of supported DTLS 1.2 cipher suites. +static AES_128_GCM_SHA256: Aes128GcmSha256 = Aes128GcmSha256; +static AES_256_GCM_SHA384: Aes256GcmSha384 = Aes256GcmSha384; +static CHACHA20_POLY1305_SHA256: ChaCha20Poly1305Sha256 = ChaCha20Poly1305Sha256; +static PSK_AES_128_CCM_8: PskAes128Ccm8 = PskAes128Ccm8; + +/// All supported DTLS 1.2 cipher suites. +pub(super) static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[ + &AES_128_GCM_SHA256, + &AES_256_GCM_SHA384, + &CHACHA20_POLY1305_SHA256, + &PSK_AES_128_CCM_8, +]; + +// ============================================================================ +// DTLS 1.3 Cipher Suites +// ============================================================================ + +/// TLS_AES_128_GCM_SHA256 cipher suite (TLS 1.3 / DTLS 1.3). +#[derive(Debug)] +struct Tls13Aes128GcmSha256; + +impl SupportedDtls13CipherSuite for Tls13Aes128GcmSha256 { + fn suite(&self) -> Dtls13CipherSuite { + Dtls13CipherSuite::AES_128_GCM_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_len(&self) -> usize { + 16 // AES-128 + } + + fn iv_len(&self) -> usize { + 12 // GCM IV + } + + fn tag_len(&self) -> usize { + 16 // GCM tag + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } + + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] { + // unwrap: sn_key length matches AES-128 key size + let cipher = Aes128::new_from_slice(sn_key).unwrap(); + let mut block = aes_gcm::aes::Block::clone_from_slice(sample); + cipher.encrypt_block(&mut block); + block.into() + } +} + +/// TLS_AES_256_GCM_SHA384 cipher suite (TLS 1.3 / DTLS 1.3). +#[derive(Debug)] +struct Tls13Aes256GcmSha384; + +impl SupportedDtls13CipherSuite for Tls13Aes256GcmSha384 { + fn suite(&self) -> Dtls13CipherSuite { + Dtls13CipherSuite::AES_256_GCM_SHA384 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA384 + } + + fn key_len(&self) -> usize { + 32 // AES-256 + } + + fn iv_len(&self) -> usize { + 12 // GCM IV + } + + fn tag_len(&self) -> usize { + 16 // GCM tag + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(AesGcm::new(key)?)) + } + + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] { + // unwrap: sn_key length matches AES-256 key size + let cipher = Aes256::new_from_slice(sn_key).unwrap(); + let mut block = aes_gcm::aes::Block::clone_from_slice(sample); + cipher.encrypt_block(&mut block); + block.into() + } +} + +/// TLS_CHACHA20_POLY1305_SHA256 cipher suite (TLS 1.3 / DTLS 1.3). +#[derive(Debug)] +struct Tls13ChaCha20Poly1305Sha256; + +impl SupportedDtls13CipherSuite for Tls13ChaCha20Poly1305Sha256 { + fn suite(&self) -> Dtls13CipherSuite { + Dtls13CipherSuite::CHACHA20_POLY1305_SHA256 + } + + fn hash_algorithm(&self) -> HashAlgorithm { + HashAlgorithm::SHA256 + } + + fn key_len(&self) -> usize { + 32 // ChaCha20 key + } + + fn iv_len(&self) -> usize { + 12 // Poly1305 nonce + } + + fn tag_len(&self) -> usize { + 16 // Poly1305 tag + } + + fn create_cipher(&self, key: &[u8]) -> Result, CryptoError> { + Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?)) + } + + fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] { + // RFC 9001 Section 5.4.4: ChaCha20 header protection + // counter = sample[0..4] (LE u32), nonce = sample[4..16] + // mask = first 5 bytes of ChaCha20 keystream at given counter + let counter = u32::from_le_bytes(sample[0..4].try_into().unwrap()); + let nonce: [u8; 12] = sample[4..16].try_into().unwrap(); + + let key = chacha20::Key::from_slice(sn_key); + let nonce = chacha20::Nonce::from_slice(&nonce); + + let mut cipher = chacha20::ChaCha20::new(key, nonce); + // Seek to the correct block counter position (each block = 64 bytes) + cipher.seek(counter as u64 * 64); + + let mut out = [0u8; 16]; + cipher.apply_keystream(&mut out); + out + } +} + +/// Static instances of supported DTLS 1.3 cipher suites. +static TLS13_AES_128_GCM_SHA256: Tls13Aes128GcmSha256 = Tls13Aes128GcmSha256; +static TLS13_AES_256_GCM_SHA384: Tls13Aes256GcmSha384 = Tls13Aes256GcmSha384; +static TLS13_CHACHA20_POLY1305_SHA256: Tls13ChaCha20Poly1305Sha256 = Tls13ChaCha20Poly1305Sha256; + +/// All supported DTLS 1.3 cipher suites. +pub(super) static ALL_DTLS13_CIPHER_SUITES: &[&dyn SupportedDtls13CipherSuite] = &[ + &TLS13_AES_128_GCM_SHA256, + &TLS13_AES_256_GCM_SHA384, + &TLS13_CHACHA20_POLY1305_SHA256, +]; + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn chacha20_poly1305_key_len_validation() { + // incorrect length (should be 32) + let result = ChaCha20Poly1305Cipher::new(&[0, 1, 2, 3, 4, 5]); + assert_eq!( + CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 }, + result.unwrap_err() + ); + } +} diff --git a/third_party/dimpl/src/crypto/rust_crypto/hash.rs b/third_party/dimpl/src/crypto/rust_crypto/hash.rs new file mode 100644 index 0000000..db473f5 --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/hash.rs @@ -0,0 +1,69 @@ +//! Hash implementations using RustCrypto. + +use sha2::{Digest, Sha256, Sha384}; + +use super::super::{HashContext, HashProvider}; +use crate::buffer::Buf; +use crate::types::HashAlgorithm; + +/// Hash context implementation using RustCrypto. +enum RustCryptoHashContext { + Sha256(Sha256), + Sha384(Sha384), +} + +impl std::fmt::Debug for RustCryptoHashContext { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RustCryptoHashContext::Sha256(_) => { + f.debug_tuple("RustCryptoHashContext::Sha256").finish() + } + RustCryptoHashContext::Sha384(_) => { + f.debug_tuple("RustCryptoHashContext::Sha384").finish() + } + } + } +} + +impl HashContext for RustCryptoHashContext { + fn update(&mut self, data: &[u8]) { + match self { + RustCryptoHashContext::Sha256(ctx) => ctx.update(data), + RustCryptoHashContext::Sha384(ctx) => ctx.update(data), + } + } + + fn clone_and_finalize(&self, out: &mut Buf) { + match self { + RustCryptoHashContext::Sha256(ctx) => { + let cloned = ctx.clone(); + let digest = cloned.finalize(); + out.clear(); + out.extend_from_slice(&digest); + } + RustCryptoHashContext::Sha384(ctx) => { + let cloned = ctx.clone(); + let digest = cloned.finalize(); + out.clear(); + out.extend_from_slice(&digest); + } + } + } +} + +/// Hash provider implementation. +#[derive(Debug)] +pub(super) struct RustCryptoHashProvider; + +impl HashProvider for RustCryptoHashProvider { + fn create_hash(&self, algorithm: HashAlgorithm) -> Box { + match algorithm { + HashAlgorithm::SHA256 => Box::new(RustCryptoHashContext::Sha256(Sha256::new())), + HashAlgorithm::SHA384 => Box::new(RustCryptoHashContext::Sha384(Sha384::new())), + _ => panic!("Unsupported hash algorithm: {:?}", algorithm), + } + } +} + +/// Static instance of the hash provider. +pub(super) static HASH_PROVIDER: RustCryptoHashProvider = RustCryptoHashProvider; diff --git a/third_party/dimpl/src/crypto/rust_crypto/hmac.rs b/third_party/dimpl/src/crypto/rust_crypto/hmac.rs new file mode 100644 index 0000000..516060d --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/hmac.rs @@ -0,0 +1,47 @@ +//! HMAC implementation using RustCrypto. + +use hmac::{Hmac, Mac}; +use sha2::{Sha256, Sha384}; + +use super::super::HmacProvider; +use crate::types::HashAlgorithm; +use crate::{CryptoError, CryptoOperation}; + +/// HMAC provider implementation. +#[derive(Debug)] +pub(crate) struct RustCryptoHmacProvider; + +impl HmacProvider for RustCryptoHmacProvider { + fn hmac( + &self, + hash: HashAlgorithm, + key: &[u8], + data: &[u8], + out: &mut [u8], + ) -> Result { + match hash { + HashAlgorithm::SHA256 => { + let mut mac = Hmac::::new_from_slice(key) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputeHmac))?; + mac.update(data); + let result = mac.finalize().into_bytes(); + let len = result.len(); + out[..len].copy_from_slice(&result); + Ok(len) + } + HashAlgorithm::SHA384 => { + let mut mac = Hmac::::new_from_slice(key) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputeHmac))?; + mac.update(data); + let result = mac.finalize().into_bytes(); + let len = result.len(); + out[..len].copy_from_slice(&result); + Ok(len) + } + _ => Err(CryptoError::UnsupportedHmacHash(hash)), + } + } +} + +/// Static instance of the HMAC provider. +pub(crate) static HMAC_PROVIDER: RustCryptoHmacProvider = RustCryptoHmacProvider; diff --git a/third_party/dimpl/src/crypto/rust_crypto/kx_group.rs b/third_party/dimpl/src/crypto/rust_crypto/kx_group.rs new file mode 100644 index 0000000..6593b0d --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/kx_group.rs @@ -0,0 +1,209 @@ +//! Key exchange group implementations using RustCrypto. + +use p256::{PublicKey as P256PublicKey, ecdh::EphemeralSecret}; +use p384::{PublicKey as P384PublicKey, ecdh::EphemeralSecret as P384EphemeralSecret}; + +use super::super::{ActiveKeyExchange, SupportedKxGroup}; +use crate::CryptoError; +use crate::buffer::Buf; +use crate::types::NamedGroup; + +/// ECDHE key exchange implementation. +enum EcdhKeyExchange { + X25519 { + secret: x25519_dalek::EphemeralSecret, + public_key: Buf, + }, + P256 { + secret: EphemeralSecret, + public_key: Buf, + }, + P384 { + secret: P384EphemeralSecret, + public_key: Buf, + }, +} + +impl std::fmt::Debug for EcdhKeyExchange { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + EcdhKeyExchange::X25519 { public_key, .. } => f + .debug_struct("EcdhKeyExchange::X25519") + .field("public_key_len", &public_key.len()) + .finish_non_exhaustive(), + EcdhKeyExchange::P256 { public_key, .. } => f + .debug_struct("EcdhKeyExchange::P256") + .field("public_key_len", &public_key.len()) + .finish_non_exhaustive(), + EcdhKeyExchange::P384 { public_key, .. } => f + .debug_struct("EcdhKeyExchange::P384") + .field("public_key_len", &public_key.len()) + .finish_non_exhaustive(), + } + } +} + +impl EcdhKeyExchange { + fn new(group: NamedGroup, mut buf: Buf) -> Result { + match group { + NamedGroup::X25519 => { + use rand_core::OsRng; + let secret = x25519_dalek::EphemeralSecret::random_from_rng(OsRng); + let public_key_obj = x25519_dalek::PublicKey::from(&secret); + buf.clear(); + buf.extend_from_slice(public_key_obj.as_bytes()); + Ok(EcdhKeyExchange::X25519 { + secret, + public_key: buf, + }) + } + NamedGroup::Secp256r1 => { + use rand_core::OsRng; + let secret = EphemeralSecret::random(&mut OsRng); + let public_key_obj = P256PublicKey::from(&secret); + let public_key_bytes = public_key_obj.to_sec1_bytes(); + buf.clear(); + buf.extend_from_slice(&public_key_bytes); + Ok(EcdhKeyExchange::P256 { + secret, + public_key: buf, + }) + } + NamedGroup::Secp384r1 => { + use rand_core::OsRng; + let secret = P384EphemeralSecret::random(&mut OsRng); + let public_key_obj = P384PublicKey::from(&secret); + let public_key_bytes = public_key_obj.to_sec1_bytes(); + buf.clear(); + buf.extend_from_slice(&public_key_bytes); + Ok(EcdhKeyExchange::P384 { + secret, + public_key: buf, + }) + } + _ => Err(CryptoError::UnsupportedKeyExchangeGroup(group)), + } + } +} + +impl ActiveKeyExchange for EcdhKeyExchange { + fn pub_key(&self) -> &[u8] { + match self { + EcdhKeyExchange::X25519 { public_key, .. } => public_key, + EcdhKeyExchange::P256 { public_key, .. } => public_key, + EcdhKeyExchange::P384 { public_key, .. } => public_key, + } + } + + fn complete(self: Box, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> { + match *self { + EcdhKeyExchange::X25519 { secret, .. } => { + let peer_bytes: [u8; 32] = peer_pub + .try_into() + .map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::X25519))?; + let peer_key = x25519_dalek::PublicKey::from(peer_bytes); + let shared_secret = secret.diffie_hellman(&peer_key); + // RFC 7748 §6.1: check the shared secret is not zero (low-order point) + if !shared_secret.was_contributory() { + return Err(CryptoError::InvalidPublicKey(NamedGroup::X25519)); + } + out.clear(); + out.extend_from_slice(shared_secret.as_bytes()); + Ok(()) + } + EcdhKeyExchange::P256 { secret, .. } => { + let peer_key = P256PublicKey::from_sec1_bytes(peer_pub) + .map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp256r1))?; + let shared_secret = secret.diffie_hellman(&peer_key); + out.clear(); + out.extend_from_slice(shared_secret.raw_secret_bytes().as_slice()); + Ok(()) + } + EcdhKeyExchange::P384 { secret, .. } => { + let peer_key = P384PublicKey::from_sec1_bytes(peer_pub) + .map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp384r1))?; + let shared_secret = secret.diffie_hellman(&peer_key); + out.clear(); + out.extend_from_slice(shared_secret.raw_secret_bytes().as_slice()); + Ok(()) + } + } + } + + fn group(&self) -> NamedGroup { + match self { + EcdhKeyExchange::X25519 { .. } => NamedGroup::X25519, + EcdhKeyExchange::P256 { .. } => NamedGroup::Secp256r1, + EcdhKeyExchange::P384 { .. } => NamedGroup::Secp384r1, + } + } +} + +/// X25519 key exchange group. +#[derive(Debug)] +struct X25519Kx; + +impl SupportedKxGroup for X25519Kx { + fn name(&self) -> NamedGroup { + NamedGroup::X25519 + } + + fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { + Ok(Box::new(EcdhKeyExchange::new(NamedGroup::X25519, buf)?)) + } +} + +/// P-256 (secp256r1) key exchange group. +#[derive(Debug)] +struct P256; + +impl SupportedKxGroup for P256 { + fn name(&self) -> NamedGroup { + NamedGroup::Secp256r1 + } + + fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { + Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp256r1, buf)?)) + } +} + +/// P-384 (secp384r1) key exchange group. +#[derive(Debug)] +struct P384; + +impl SupportedKxGroup for P384 { + fn name(&self) -> NamedGroup { + NamedGroup::Secp384r1 + } + + fn start_exchange(&self, buf: Buf) -> Result, CryptoError> { + Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp384r1, buf)?)) + } +} + +/// Static instances of supported key exchange groups. +static KX_GROUP_X25519: X25519Kx = X25519Kx; +static KX_GROUP_P256: P256 = P256; +static KX_GROUP_P384: P384 = P384; + +/// All supported key exchange groups. +pub(super) static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] = + &[&KX_GROUP_X25519, &KX_GROUP_P256, &KX_GROUP_P384]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn x25519_non_contributory_peer_key_returns_invalid_public_key() { + let exchange = X25519Kx + .start_exchange(Buf::new()) + .expect("start key exchange"); + let mut out = Buf::new(); + + assert_eq!( + exchange.complete(&[0; 32], &mut out), + Err(CryptoError::InvalidPublicKey(NamedGroup::X25519)) + ); + } +} diff --git a/third_party/dimpl/src/crypto/rust_crypto/mod.rs b/third_party/dimpl/src/crypto/rust_crypto/mod.rs new file mode 100644 index 0000000..ebab858 --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/mod.rs @@ -0,0 +1,102 @@ +//! RustCrypto cryptographic provider implementation for dimpl. +//! +//! This module provides a pure Rust cryptographic backend for dimpl using +//! crates from the [RustCrypto](https://github.com/RustCrypto) organization. +//! +//! # Feature Flag +//! +//! This module is only available when the `rust-crypto` feature is enabled. The `rust-crypto` +//! feature is included in the default features, so it's enabled by default. To use +//! dimpl without this module, disable default features: +//! +//! ```toml +//! dimpl = { version = "...", default-features = false } +//! ``` +//! +//! # Usage +//! +//! The rust-crypto provider is used automatically as a fallback when aws-lc-rs is not available +//! or when explicitly specified: +//! +//! ``` +//! # #[cfg(feature = "rcgen")] +//! # fn main() { +//! use std::sync::Arc; +//! use std::time::Instant; +//! use dimpl::{Config, Dtls, certificate}; +//! use dimpl::crypto::rust_crypto; +//! +//! let cert = certificate::generate_self_signed_certificate().unwrap(); +//! let config = Arc::new( +//! Config::builder() +//! .with_crypto_provider(rust_crypto::default_provider()) +//! .build() +//! .unwrap() +//! ); +//! let dtls = Dtls::new_12(config, cert, Instant::now()); +//! # } +//! # #[cfg(not(feature = "rcgen"))] +//! # fn main() {} +//! ``` + +mod cipher_suite; +mod hash; +pub(crate) mod hmac; +mod kx_group; +mod random; +mod sign; + +use super::CryptoProvider; + +/// Get the default RustCrypto-based crypto provider. +/// +/// This provider implements all cryptographic operations required for DTLS 1.2 +/// using pure Rust crates from the RustCrypto organization. +/// +/// # Supported Cipher Suites +/// +/// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` (0xC02B) +/// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` (0xC02C) +/// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` (0xCCA9) +/// +/// # Supported Key Exchange Groups +/// +/// - `x25519` (X25519 / Curve25519) +/// - `secp256r1` (P-256, NIST Curve) +/// - `secp384r1` (P-384, NIST Curve) +/// +/// # Supported Signature Algorithms +/// +/// - ECDSA with P-256 and SHA-256 +/// - ECDSA with P-384 and SHA-384 +/// +/// # Supported Hash Algorithms +/// +/// - SHA-256 +/// - SHA-384 +/// +/// # Key Formats +/// +/// The key provider supports loading private keys in: +/// - PKCS#8 DER format (most common) +/// - SEC1 DER format (OpenSSL EC private key format) +/// - PEM encoded versions of the above +/// +/// # Random Number Generation +/// +/// Uses `OsRng` from the `rand` crate for cryptographically secure random number generation. +pub fn default_provider() -> CryptoProvider { + CryptoProvider { + // Shared components + kx_groups: kx_group::ALL_KX_GROUPS, + signature_verification: &sign::SIGNATURE_VERIFIER, + key_provider: &sign::KEY_PROVIDER, + secure_random: &random::SECURE_RANDOM, + hash_provider: &hash::HASH_PROVIDER, + hmac_provider: &hmac::HMAC_PROVIDER, + // DTLS 1.2 components + cipher_suites: cipher_suite::ALL_CIPHER_SUITES, + // DTLS 1.3 components + dtls13_cipher_suites: cipher_suite::ALL_DTLS13_CIPHER_SUITES, + } +} diff --git a/third_party/dimpl/src/crypto/rust_crypto/random.rs b/third_party/dimpl/src/crypto/rust_crypto/random.rs new file mode 100644 index 0000000..de9cd7e --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/random.rs @@ -0,0 +1,20 @@ +//! Secure random number generation using RustCrypto. + +use super::super::SecureRandom; +use crate::CryptoError; + +/// Secure random number generator implementation. +#[derive(Debug)] +pub(super) struct RustCryptoSecureRandom; + +impl SecureRandom for RustCryptoSecureRandom { + fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> { + use rand_core::OsRng; + use rand_core::RngCore; + OsRng.fill_bytes(buf); + Ok(()) + } +} + +/// Static instance of the secure random generator. +pub(super) static SECURE_RANDOM: RustCryptoSecureRandom = RustCryptoSecureRandom; diff --git a/third_party/dimpl/src/crypto/rust_crypto/sign.rs b/third_party/dimpl/src/crypto/rust_crypto/sign.rs new file mode 100644 index 0000000..1bf8008 --- /dev/null +++ b/third_party/dimpl/src/crypto/rust_crypto/sign.rs @@ -0,0 +1,329 @@ +//! Signing and key loading implementations using RustCrypto. + +use std::str; + +use der::{Decode, Encode}; +use ecdsa::{Signature, SigningKey, VerifyingKey}; +use p256::NistP256; +use p384::NistP384; +use pkcs8::DecodePrivateKey; +use spki::ObjectIdentifier; +use x509_cert::Certificate as X509Certificate; + +use super::super::check_verify_scheme; +use super::super::{KeyProvider, SignatureVerifier, SigningKey as SigningKeyTrait}; +use super::super::{OID_P256, OID_P384}; +use crate::buffer::Buf; +use crate::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm}; +use crate::{CryptoError, CryptoOperation}; + +/// ECDSA signing key implementation. +enum EcdsaSigningKey { + P256(SigningKey), + P384(SigningKey), +} + +impl std::fmt::Debug for EcdsaSigningKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + EcdsaSigningKey::P256(_) => f.debug_tuple("EcdsaSigningKey::P256").finish(), + EcdsaSigningKey::P384(_) => f.debug_tuple("EcdsaSigningKey::P384").finish(), + } + } +} + +impl SigningKeyTrait for EcdsaSigningKey { + fn sign( + &mut self, + data: &[u8], + hash_alg: HashAlgorithm, + out: &mut Buf, + ) -> Result<(), CryptoError> { + use ecdsa::signature::hazmat::PrehashSigner; + use sha2::Digest; + + match self { + EcdsaSigningKey::P256(key) => { + let signature: Signature = match hash_alg { + HashAlgorithm::SHA256 => { + let hash = sha2::Sha256::digest(data); + key.sign_prehash(&hash) + } + HashAlgorithm::SHA384 => { + let hash = sha2::Sha384::digest(data); + key.sign_prehash(&hash) + } + _ => { + return Err(CryptoError::SigningKeyUnsupportedHash { + group: NamedGroup::Secp256r1, + hash: hash_alg, + }); + } + } + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?; + out.clear(); + out.extend_from_slice(signature.to_der().as_bytes()); + Ok(()) + } + EcdsaSigningKey::P384(key) => { + let signature: Signature = match hash_alg { + HashAlgorithm::SHA256 => { + let hash = sha2::Sha256::digest(data); + key.sign_prehash(&hash) + } + HashAlgorithm::SHA384 => { + let hash = sha2::Sha384::digest(data); + key.sign_prehash(&hash) + } + _ => { + return Err(CryptoError::SigningKeyUnsupportedHash { + group: NamedGroup::Secp384r1, + hash: hash_alg, + }); + } + } + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?; + out.clear(); + out.extend_from_slice(signature.to_der().as_bytes()); + Ok(()) + } + } + } + + fn algorithm(&self) -> SignatureAlgorithm { + SignatureAlgorithm::ECDSA + } + + fn hash_algorithm(&self) -> HashAlgorithm { + match self { + EcdsaSigningKey::P256(_) => HashAlgorithm::SHA256, + EcdsaSigningKey::P384(_) => HashAlgorithm::SHA384, + } + } + + fn supported_hash_algorithms(&self) -> &[HashAlgorithm] { + // PrehashSigner accepts any hash digest, so both work for either curve. + &[HashAlgorithm::SHA256, HashAlgorithm::SHA384] + } +} + +/// Key provider implementation. +#[derive(Debug)] +pub(super) struct RustCryptoKeyProvider; + +impl KeyProvider for RustCryptoKeyProvider { + fn load_private_key(&self, key_der: &[u8]) -> Result, CryptoError> { + // Try PKCS#8 DER format first (most common) + if let Ok(key) = SigningKey::::from_pkcs8_der(key_der) { + return Ok(Box::new(EcdsaSigningKey::P256(key))); + } + if let Ok(key) = SigningKey::::from_pkcs8_der(key_der) { + return Ok(Box::new(EcdsaSigningKey::P384(key))); + } + + // Try parsing as SEC1 DER format (OpenSSL EC private key format) + if let Ok(ec_key) = sec1::EcPrivateKey::try_from(key_der) { + let private_key_len = ec_key.private_key.len(); + + let curve_oid = if let Some(params) = &ec_key.parameters { + match params { + sec1::EcParameters::NamedCurve(oid) => Some(*oid), + } + } else if private_key_len == 32 { + Some(ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")) // P-256 + } else if private_key_len == 48 { + Some(ObjectIdentifier::new_unwrap("1.3.132.0.34")) // P-384 + } else { + None + }; + + if let Some(curve_oid) = curve_oid { + let ec_alg_oid = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); + let curve_params_der = curve_oid + .to_der() + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; + let curve_params_any = der::asn1::AnyRef::try_from(curve_params_der.as_slice()) + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; + + let algorithm = spki::AlgorithmIdentifierRef { + oid: ec_alg_oid, + parameters: Some(curve_params_any), + }; + + let pkcs8 = pkcs8::PrivateKeyInfo { + algorithm, + private_key: key_der, + public_key: None, + }; + + let pkcs8_der = pkcs8 + .to_der() + .map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?; + + let p256_curve = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"); + if curve_oid == p256_curve { + if let Ok(key) = SigningKey::::from_pkcs8_der(pkcs8_der.as_slice()) { + return Ok(Box::new(EcdsaSigningKey::P256(key))); + } + } + + let p384_curve = ObjectIdentifier::new_unwrap("1.3.132.0.34"); + if curve_oid == p384_curve { + if let Ok(key) = SigningKey::::from_pkcs8_der(pkcs8_der.as_slice()) { + return Ok(Box::new(EcdsaSigningKey::P384(key))); + } + } + } + } + + // Check if it's a PEM encoded key + if let Ok(pem_str) = str::from_utf8(key_der) { + if pem_str.contains("-----BEGIN") { + if let Ok((_label, doc)) = pkcs8::Document::from_pem(pem_str) { + return self.load_private_key(doc.as_bytes()); + } + } + } + + Err(CryptoError::InvalidPrivateKey) + } +} + +/// Signature verifier implementation. +#[derive(Debug)] +pub(super) struct RustCryptoSignatureVerifier; + +impl SignatureVerifier for RustCryptoSignatureVerifier { + fn verify_signature( + &self, + cert_der: &[u8], + data: &[u8], + signature: &[u8], + hash_alg: HashAlgorithm, + sig_alg: SignatureAlgorithm, + ) -> Result<(), CryptoError> { + if sig_alg != SignatureAlgorithm::ECDSA { + return Err(CryptoError::UnsupportedSignatureAlgorithm(sig_alg)); + } + + let cert = + X509Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?; + let spki = &cert.tbs_certificate.subject_public_key_info; + + const OID_EC_PUBLIC_KEY: ObjectIdentifier = + ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); + + if spki.algorithm.oid != OID_EC_PUBLIC_KEY { + return Err(CryptoError::UnsupportedPublicKeyAlgorithm); + } + + let pubkey_bytes = spki + .subject_public_key + .as_bytes() + .ok_or(CryptoError::InvalidSubjectPublicKey)?; + + let curve_oid: ObjectIdentifier = spki + .algorithm + .parameters + .as_ref() + .ok_or(CryptoError::MissingEcCurveParameter)? + .decode_as() + .map_err(|_| CryptoError::InvalidEcCurveParameter)?; + + let group = match curve_oid { + OID_P256 => NamedGroup::Secp256r1, + OID_P384 => NamedGroup::Secp384r1, + _ => return Err(CryptoError::UnsupportedEcCurve), + }; + + check_verify_scheme(sig_alg, hash_alg, group)?; + + use ecdsa::signature::hazmat::PrehashVerifier; + use sha2::Digest; + + // Hash the data before verification (PrehashVerifier expects a hash digest) + let hash: Box<[u8]> = match hash_alg { + HashAlgorithm::SHA256 => Box::from(sha2::Sha256::digest(data).as_slice()), + HashAlgorithm::SHA384 => Box::from(sha2::Sha384::digest(data).as_slice()), + // unreachable: check_verify_scheme already validated + _ => unreachable!(), + }; + + match group { + NamedGroup::Secp256r1 => { + let verifying_key = VerifyingKey::::from_sec1_bytes(pubkey_bytes) + .map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp256r1))?; + let sig = Signature::::from_der(signature) + .map_err(|_| CryptoError::InvalidSignatureFormat)?; + verifying_key.verify_prehash(&hash, &sig).map_err(|_| { + CryptoError::SignatureVerificationFailed { + signature: sig_alg, + hash: hash_alg, + group, + } + }) + } + NamedGroup::Secp384r1 => { + let verifying_key = VerifyingKey::::from_sec1_bytes(pubkey_bytes) + .map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp384r1))?; + let sig = Signature::::from_der(signature) + .map_err(|_| CryptoError::InvalidSignatureFormat)?; + verifying_key.verify_prehash(&hash, &sig).map_err(|_| { + CryptoError::SignatureVerificationFailed { + signature: sig_alg, + hash: hash_alg, + group, + } + }) + } + // unreachable: OID match above only produces Secp256r1/Secp384r1 + _ => unreachable!(), + } + } +} + +/// Static instance of the key provider. +pub(super) static KEY_PROVIDER: RustCryptoKeyProvider = RustCryptoKeyProvider; + +/// Static instance of the signature verifier. +pub(super) static SIGNATURE_VERIFIER: RustCryptoSignatureVerifier = RustCryptoSignatureVerifier; + +#[cfg(all(test, feature = "rcgen"))] +mod tests { + use super::*; + use crate::certificate::generate_self_signed_certificate; + + #[test] + fn invalid_signature_returns_structured_verification_error() { + let cert = generate_self_signed_certificate().expect("generate cert"); + let mut key = KEY_PROVIDER + .load_private_key(&cert.private_key) + .expect("load private key"); + let data = b"signed data"; + let mut signature = Buf::new(); + key.sign(data, HashAlgorithm::SHA256, &mut signature) + .expect("sign data"); + + let last = signature.len() - 1; + signature[last] ^= 0x01; + + let err = SIGNATURE_VERIFIER + .verify_signature( + &cert.certificate, + data, + &signature, + HashAlgorithm::SHA256, + SignatureAlgorithm::ECDSA, + ) + .expect_err("corrupt signature should fail"); + + assert_eq!( + err, + CryptoError::SignatureVerificationFailed { + signature: SignatureAlgorithm::ECDSA, + hash: HashAlgorithm::SHA256, + group: NamedGroup::Secp256r1, + } + ); + } +} diff --git a/third_party/dimpl/src/crypto/validation/mod.rs b/third_party/dimpl/src/crypto/validation/mod.rs new file mode 100644 index 0000000..3b19acc --- /dev/null +++ b/third_party/dimpl/src/crypto/validation/mod.rs @@ -0,0 +1,761 @@ +//! Validation and filtering for crypto providers. +//! +//! This module defines the validation rules for crypto providers used with dimpl, +//! based on the documented support in lib.rs. + +use arrayvec::ArrayVec; + +use super::{Aad, CryptoProvider, Nonce, SupportedDtls12CipherSuite, SupportedKxGroup}; +use crate::buffer::{Buf, TmpBuf}; +use crate::types::{Dtls13CipherSuite, HashAlgorithm, NamedGroup, SignatureAlgorithm}; +use crate::{ConfigError, CryptoProviderValidationError, Error}; + +fn provider_error(error: CryptoProviderValidationError) -> Error { + Error::ConfigError(ConfigError::CryptoProvider(error)) +} + +impl CryptoProvider { + /// Returns an iterator over validated cipher suites supported by dimpl. + /// + /// Only cipher suites documented in lib.rs are returned: + /// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` + /// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` + /// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` + pub fn supported_cipher_suites( + &self, + ) -> impl Iterator { + self.cipher_suites + .iter() + .copied() + .filter(|cs| cs.suite().is_supported()) + } + + /// Returns an iterator over validated key exchange groups supported by dimpl. + /// + /// Only key exchange groups documented in lib.rs are returned: + /// - X25519 + /// - P-256 (secp256r1) + /// - P-384 (secp384r1) + pub fn supported_kx_groups(&self) -> impl Iterator { + self.kx_groups.iter().copied().filter(|kx| { + matches!( + kx.name(), + NamedGroup::X25519 | NamedGroup::Secp256r1 | NamedGroup::Secp384r1 + ) + }) + } + + /// + /// Combines provider filtering with signature algorithm compatibility. + pub fn supported_cipher_suites_for_signature_algorithm( + &self, + sig_alg: SignatureAlgorithm, + ) -> impl Iterator { + self.supported_cipher_suites() + .filter(move |cs| cs.suite().signature_algorithm() == Some(sig_alg)) + } + + /// Check if provider supports ECDH-based cipher suites. + /// + /// Returns true if any supported cipher suite uses ECDH key exchange. + pub fn has_ecdh(&self) -> bool { + self.supported_cipher_suites() + .any(|cs| cs.suite().has_ecc()) + } + + /// Validates the provider configuration for use with dimpl. + /// + /// This ensures the provider meets dimpl's requirements: + /// - At least one supported cipher suite + /// - ECDH cipher suites have matching key exchange groups + /// - Hash providers support required algorithms + /// - HMAC provider supports required operations + /// + /// Returns `Error::ConfigError` if validation fails. + pub fn validate(&self) -> Result<(), Error> { + self.validate_cipher_suites()?; + self.validate_kx_groups()?; + let validated_hashes = self.validate_hash_providers()?; + self.validate_prf(&validated_hashes)?; + self.validate_signature_verifier(&validated_hashes)?; + self.validate_hmac_provider()?; + self.validate_dtls13_cipher_suites()?; + self.validate_dtls13_aead()?; + self.validate_dtls13_encrypt_sn()?; + self.validate_kx_exchange()?; + Ok(()) + } + + /// Validate that at least one cipher suite is supported. + fn validate_cipher_suites(&self) -> Result<(), Error> { + let cipher_count = self.supported_cipher_suites().count(); + if cipher_count == 0 { + return Err(provider_error( + CryptoProviderValidationError::NoCipherSuites, + )); + } + Ok(()) + } + + /// Validate that ECDH cipher suites have matching key exchange groups. + fn validate_kx_groups(&self) -> Result<(), Error> { + if self.has_ecdh() { + let kx_count = self.supported_kx_groups().count(); + if kx_count == 0 { + return Err(provider_error( + CryptoProviderValidationError::EcdhCipherSuitesWithoutKeyExchangeGroups, + )); + } + } + Ok(()) + } + + /// Validate that hash providers support required algorithms. + /// Returns the list of validated hash algorithms. + fn validate_hash_providers(&self) -> Result, Error> { + // Collect unique hash algorithms from supported cipher suites + let required_hashes: Vec = self + .cipher_suites + .iter() + .map(|cs| cs.suite().hash_algorithm()) + .collect(); + + // Test each required hash algorithm with known test vectors + for hash_alg in &required_hashes { + let mut hasher = self.hash_provider.create_hash(*hash_alg); + + // Test with empty input - use known hash values + hasher.update(&[]); + let mut result = Buf::new(); + hasher.clone_and_finalize(&mut result); + + let maybe_expected = HASH_TEST_VECTORS + .iter() + .find(|(h, _)| *h == *hash_alg) + .map(|(_, v)| v); + + let Some(expected) = maybe_expected else { + return Err(provider_error( + CryptoProviderValidationError::MissingHashTestVector(*hash_alg), + )); + }; + + if result.as_ref() != *expected { + return Err(provider_error( + CryptoProviderValidationError::HashProviderIncorrect(*hash_alg), + )); + } + } + + Ok(required_hashes) + } + + /// Validate that PRF (via HMAC) works for every supported hash algorithm. + fn validate_prf(&self, validated_hashes: &[HashAlgorithm]) -> Result<(), Error> { + let secret = b"test_secret"; + let label = "test label"; + let seed = b"test_seed"; + let output_len = 32; + + for &hash_alg in validated_hashes { + let mut result = Buf::new(); + let mut scratch = Buf::new(); + super::prf_hkdf::prf_tls12( + self.hmac_provider, + secret, + label, + seed, + &mut result, + output_len, + &mut scratch, + hash_alg, + ) + .map_err(|e| { + provider_error(CryptoProviderValidationError::PrfFailed { + hash: hash_alg, + source: e, + }) + })?; + + let maybe_expected = PRF_TEST_VECTORS + .iter() + .find(|(h, _)| *h == hash_alg) + .map(|(_, v)| v); + + let Some(expected) = maybe_expected else { + return Err(provider_error( + CryptoProviderValidationError::MissingPrfTestVector(hash_alg), + )); + }; + + if result.as_ref() != *expected { + return Err(provider_error(CryptoProviderValidationError::PrfIncorrect( + hash_alg, + ))); + } + } + + Ok(()) + } + + /// Validate that signature verifier works for every supported cipher suite. + fn validate_signature_verifier( + &self, + _validated_hashes: &[HashAlgorithm], + ) -> Result<(), Error> { + // Test signature verification for each supported cipher suite + for cs in self.supported_cipher_suites() { + let hash_alg = cs.suite().hash_algorithm(); + let sig_alg = match cs.suite().signature_algorithm() { + Some(alg) => alg, + // PSK suites have no signature — skip validation + None => continue, + }; + + let (cert_der, signature, test_data) = match (hash_alg, sig_alg) { + (HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA) => ( + VALIDATION_P256_CERT, + VALIDATION_P256_SHA256_SIG, + VALIDATION_TEST_DATA, + ), + (HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA) => ( + VALIDATION_P384_CERT, + VALIDATION_P384_SHA384_SIG, + VALIDATION_TEST_DATA, + ), + _ => { + return Err(provider_error( + CryptoProviderValidationError::NoSignatureValidationVector { + hash: hash_alg, + signature: sig_alg, + }, + )); + } + }; + + // Verify the signature + self.signature_verification + .verify_signature(cert_der, test_data, signature, hash_alg, sig_alg) + .map_err(|e| { + provider_error(CryptoProviderValidationError::SignatureVerificationFailed { + hash: hash_alg, + signature: sig_alg, + source: e, + }) + })?; + } + + Ok(()) + } + + /// Validate that DTLS 1.3 cipher suites and HKDF provider are configured. + fn validate_dtls13_cipher_suites(&self) -> Result<(), Error> { + if self.dtls13_cipher_suites.is_empty() { + return Err(provider_error( + CryptoProviderValidationError::NoDtls13CipherSuites, + )); + } + + // Verify HKDF (via HMAC) works for each DTLS 1.3 cipher suite's hash algorithm + for cs in self.dtls13_cipher_suites { + let hash = cs.suite().hash_algorithm(); + let hash_len = hash.output_len(); + let zeros = [0u8; 48]; + let zeros = &zeros[..hash_len]; + let mut out = Buf::new(); + super::prf_hkdf::hkdf_extract(self.hmac_provider, hash, zeros, zeros, &mut out) + .map_err(|e| { + provider_error(CryptoProviderValidationError::HkdfFailed { + suite: cs.suite(), + source: e, + }) + })?; + if out.is_empty() { + return Err(provider_error( + CryptoProviderValidationError::HkdfEmptyOutput(cs.suite()), + )); + } + } + + Ok(()) + } + + /// Validate AEAD encrypt/decrypt for each DTLS 1.3 cipher suite. + fn validate_dtls13_aead(&self) -> Result<(), Error> { + for cs in self.dtls13_cipher_suites { + let suite = cs.suite(); + let tv = AEAD_TEST_VECTORS + .iter() + .find(|tv| tv.suite == suite) + .ok_or_else(|| { + provider_error(CryptoProviderValidationError::NoAeadTestVector(suite)) + })?; + + let nonce = Nonce(tv.nonce); + let mut aad_vec = ArrayVec::new(); + // unwrap: AAD is at most 12 bytes, well within capacity 13 + aad_vec.try_extend_from_slice(tv.aad).unwrap(); + let aad = Aad(aad_vec); + + // Encrypt + let mut cipher = cs.create_cipher(tv.key).map_err(|e| { + provider_error(CryptoProviderValidationError::AeadCreateFailed { suite, source: e }) + })?; + let mut buf = Buf::new(); + buf.extend_from_slice(tv.plaintext); + cipher.encrypt(&mut buf, aad.clone(), nonce).map_err(|e| { + provider_error(CryptoProviderValidationError::AeadEncryptFailed { + suite, + source: e, + }) + })?; + if buf.as_ref() != tv.ciphertext_tag { + return Err(provider_error( + CryptoProviderValidationError::AeadEncryptWrongOutput(suite), + )); + } + + // Decrypt with a fresh cipher instance + let mut cipher = cs.create_cipher(tv.key).map_err(|e| { + provider_error(CryptoProviderValidationError::AeadCreateFailed { suite, source: e }) + })?; + let mut ct = Vec::from(tv.ciphertext_tag); + let mut tmp = TmpBuf::new(&mut ct); + cipher.decrypt(&mut tmp, aad, nonce).map_err(|e| { + provider_error(CryptoProviderValidationError::AeadDecryptFailed { + suite, + source: e, + }) + })?; + if tmp.as_ref() != tv.plaintext { + return Err(provider_error( + CryptoProviderValidationError::AeadDecryptWrongOutput(suite), + )); + } + } + Ok(()) + } + + /// Validate record number encryption for each DTLS 1.3 cipher suite. + fn validate_dtls13_encrypt_sn(&self) -> Result<(), Error> { + for cs in self.dtls13_cipher_suites { + let suite = cs.suite(); + let tv = SN_TEST_VECTORS + .iter() + .find(|tv| tv.suite == suite) + .ok_or_else(|| { + provider_error( + CryptoProviderValidationError::NoRecordNumberEncryptionTestVector(suite), + ) + })?; + + let mask = cs.encrypt_sn(tv.sn_key, &tv.sample); + if mask[..tv.check_len] != tv.expected_mask[..tv.check_len] { + return Err(provider_error( + CryptoProviderValidationError::RecordNumberEncryptionWrongMask(suite), + )); + } + } + Ok(()) + } + + /// Validate key exchange round-trip for each supported group. + fn validate_kx_exchange(&self) -> Result<(), Error> { + for kx in self.supported_kx_groups() { + let group = kx.name(); + + let alice = kx.start_exchange(Buf::new()).map_err(|e| { + provider_error(CryptoProviderValidationError::KeyExchangeStartFailed { + group, + source: e, + }) + })?; + let bob = kx.start_exchange(Buf::new()).map_err(|e| { + provider_error(CryptoProviderValidationError::KeyExchangeStartFailed { + group, + source: e, + }) + })?; + + let alice_pub = alice.pub_key().to_vec(); + let bob_pub = bob.pub_key().to_vec(); + + let mut alice_secret = Buf::new(); + alice.complete(&bob_pub, &mut alice_secret).map_err(|e| { + provider_error(CryptoProviderValidationError::KeyExchangeCompleteFailed { + group, + source: e, + }) + })?; + + let mut bob_secret = Buf::new(); + bob.complete(&alice_pub, &mut bob_secret).map_err(|e| { + provider_error(CryptoProviderValidationError::KeyExchangeCompleteFailed { + group, + source: e, + }) + })?; + + if alice_secret.as_ref() != bob_secret.as_ref() { + return Err(provider_error( + CryptoProviderValidationError::KeyExchangeMismatchedSharedSecret(group), + )); + } + } + Ok(()) + } + + /// Validate that HMAC provider supports required operations. + /// + /// We require HMAC-SHA256 for DTLS cookie computation. + fn validate_hmac_provider(&self) -> Result<(), Error> { + // Test HMAC-SHA256 with known test vector (RFC 2104 test case) + // HMAC-SHA256(key="key", data="The quick brown fox jumps over the lazy dog") + let key = b"key"; + let data = b"The quick brown fox jumps over the lazy dog"; + + let result = self + .hmac_provider + .hmac_sha256(key, data) + .map_err(|e| provider_error(CryptoProviderValidationError::HmacFailed(e)))?; + + // Verify against known HMAC-SHA256 test vector + if result.as_slice() != HMAC_SHA256_TEST_VECTOR { + return Err(provider_error(CryptoProviderValidationError::HmacIncorrect)); + } + + Ok(()) + } +} + +const HASH_TEST_VECTORS: &[(HashAlgorithm, &[u8])] = &[ + ( + HashAlgorithm::SHA256, + &[ + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, + 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, + 0x78, 0x52, 0xb8, 0x55, + ], + ), + ( + HashAlgorithm::SHA384, + &[ + 0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, + 0xe3, 0x6a, 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, + 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, + 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b, + ], + ), +]; + +// Test vectors for TLS 1.2 PRF +// Generated using: PRF(secret="test_secret", label="test label", seed="test_seed", output_len=32) +const PRF_TEST_VECTORS: &[(HashAlgorithm, &[u8])] = &[ + ( + HashAlgorithm::SHA256, + &[ + 0xc7, 0x49, 0xce, 0xdf, 0xad, 0xaf, 0x3d, 0xf1, 0x18, 0x2c, 0xa2, 0x25, 0xab, 0xe9, + 0x4e, 0x0c, 0x19, 0xc3, 0x81, 0x49, 0x57, 0xbd, 0xdc, 0x28, 0x55, 0x78, 0x73, 0xdb, + 0xb7, 0x9f, 0xce, 0x29, + ], + ), + ( + HashAlgorithm::SHA384, + &[ + 0x74, 0x9a, 0xf3, 0x03, 0x23, 0x9e, 0x3f, 0x65, 0x4e, 0x9a, 0xd1, 0xb1, 0xd1, 0x22, + 0x31, 0x02, 0x1a, 0xd2, 0x17, 0x26, 0x04, 0x75, 0x21, 0xf4, 0x66, 0xad, 0xcd, 0x37, + 0x2b, 0xe4, 0x7e, 0x8b, + ], + ), +]; + +// Test vector for HMAC-SHA256 +// HMAC-SHA256(key="key", data="The quick brown fox jumps over the lazy dog") +// Computed using standard HMAC-SHA256 implementation +const HMAC_SHA256_TEST_VECTOR: &[u8] = &[ + 0xf7, 0xbc, 0x83, 0xf4, 0x30, 0x53, 0x84, 0x24, 0xb1, 0x32, 0x98, 0xe6, 0xaa, 0x6f, 0xb1, 0x43, + 0xef, 0x4d, 0x59, 0xa1, 0x49, 0x46, 0x17, 0x59, 0x97, 0x47, 0x9d, 0xbc, 0x2d, 0x1a, 0x3c, 0xd8, +]; + +// Test certificates and signatures for signature verification validation +const VALIDATION_TEST_DATA: &[u8] = include_bytes!("test_data.bin"); +const VALIDATION_P256_CERT: &[u8] = include_bytes!("p256_cert.der"); +const VALIDATION_P256_SHA256_SIG: &[u8] = include_bytes!("p256_sha256_sig.der"); +const VALIDATION_P384_CERT: &[u8] = include_bytes!("p384_cert.der"); +const VALIDATION_P384_SHA384_SIG: &[u8] = include_bytes!("p384_sha384_sig.der"); + +// AEAD test vectors for DTLS 1.3 cipher suites +struct AeadTestVector { + suite: Dtls13CipherSuite, + key: &'static [u8], + nonce: [u8; 12], + plaintext: &'static [u8], + aad: &'static [u8], + ciphertext_tag: &'static [u8], // ciphertext || tag +} + +// NIST SP 800-38D Test Case 3 plaintext (shared by AES-128 and AES-256) +const GCM_PLAINTEXT: &[u8] = &[ + 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, + 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, + 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, + 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55, +]; + +const AEAD_TEST_VECTORS: &[AeadTestVector] = &[ + // NIST SP 800-38D Test Case 3: AES-128-GCM, empty AAD + AeadTestVector { + suite: Dtls13CipherSuite::AES_128_GCM_SHA256, + key: &[ + 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, + 0x83, 0x08, + ], + nonce: [ + 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88, + ], + plaintext: GCM_PLAINTEXT, + aad: &[], + ciphertext_tag: &[ + // Ciphertext + 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, + 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, + 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, + 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, + 0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85, // Tag + 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6, 0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, + 0xfa, 0xb4, + ], + }, + // NIST SP 800-38D Test Case 15: AES-256-GCM, empty AAD + AeadTestVector { + suite: Dtls13CipherSuite::AES_256_GCM_SHA384, + key: &[ + 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, + 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, + 0x67, 0x30, 0x83, 0x08, + ], + nonce: [ + 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88, + ], + plaintext: GCM_PLAINTEXT, + aad: &[], + ciphertext_tag: &[ + // Ciphertext + 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, + 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, + 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, + 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, + 0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad, // Tag + 0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd, 0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3, + 0xcc, 0x6c, + ], + }, + // RFC 7539 §2.8.2: ChaCha20-Poly1305 + AeadTestVector { + suite: Dtls13CipherSuite::CHACHA20_POLY1305_SHA256, + key: &[ + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, + 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, + 0x9c, 0x9d, 0x9e, 0x9f, + ], + nonce: [ + 0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + ], + plaintext: &[ + // "Ladies and Gentlemen of the class of '99: If I could offer you + // only one tip for the future, sunscreen would be it." + 0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, + 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, + 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, + 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, + 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, + 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, + 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, + 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, + 0x74, 0x2e, + ], + aad: &[ + 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + ], + ciphertext_tag: &[ + // Ciphertext + 0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, + 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, + 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, + 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0x0a, 0x9e, 0x06, 0x0b, 0x29, + 0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, + 0x8b, 0x8c, 0x98, 0x03, 0xae, 0xe3, 0x28, 0x09, 0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, + 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, + 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, + 0x61, 0x16, // Tag + 0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, + 0x06, 0x91, + ], + }, +]; + +// Record number encryption (encrypt_sn) test vectors +struct SnTestVector { + suite: Dtls13CipherSuite, + sn_key: &'static [u8], + sample: [u8; 16], + expected_mask: [u8; 16], + check_len: usize, // number of leading bytes to verify +} + +const SN_TEST_VECTORS: &[SnTestVector] = &[ + // NIST FIPS 197 Appendix B: AES-128-ECB + SnTestVector { + suite: Dtls13CipherSuite::AES_128_GCM_SHA256, + sn_key: &[ + 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, + 0x4f, 0x3c, + ], + sample: [ + 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, + 0x07, 0x34, + ], + expected_mask: [ + 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, + 0x0b, 0x32, + ], + check_len: 16, + }, + // NIST FIPS 197 Appendix C.3: AES-256-ECB + SnTestVector { + suite: Dtls13CipherSuite::AES_256_GCM_SHA384, + sn_key: &[ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, + 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, + ], + sample: [ + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, + 0xee, 0xff, + ], + expected_mask: [ + 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, + 0x60, 0x89, + ], + check_len: 16, + }, + // RFC 9001 §A.5: ChaCha20 header protection + // Only first 5 bytes are checked (aws-lc-rs zeros bytes 5-15, rust_crypto fills all 16) + SnTestVector { + suite: Dtls13CipherSuite::CHACHA20_POLY1305_SHA256, + sn_key: &[ + 0x25, 0xa2, 0x82, 0xb9, 0xe8, 0x2f, 0x06, 0xf2, 0x1f, 0x48, 0x89, 0x17, 0xa4, 0xfc, + 0x8f, 0x1b, 0x73, 0x57, 0x36, 0x85, 0x60, 0x85, 0x97, 0xd0, 0xef, 0xcb, 0x07, 0x6b, + 0x0a, 0xb7, 0xa7, 0xa4, + ], + sample: [ + 0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57, 0x5d, 0x79, 0x99, 0xc2, 0x5a, + 0x5b, 0xfb, + ], + expected_mask: [ + 0xae, 0xfe, 0xfe, 0x7d, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, + ], + check_len: 5, + }, +]; + +#[cfg(test)] +#[cfg(feature = "aws-lc-rs")] +mod tests_aws_lc_rs { + use super::*; + use crate::crypto::aws_lc_rs; + use crate::dtls12::message::Dtls12CipherSuite; + + #[test] + fn test_default_provider_validates() { + let provider = aws_lc_rs::default_provider(); + assert!(provider.validate().is_ok()); + } + + #[test] + fn test_default_provider_has_cipher_suites() { + let provider = aws_lc_rs::default_provider(); + let count = provider.supported_cipher_suites().count(); + // ECDHE: AES-128, AES-256, ChaCha20 + // PSK: CCM-8 + assert_eq!(count, 4); + } + + #[test] + fn test_default_provider_has_kx_groups() { + let provider = aws_lc_rs::default_provider(); + let count = provider.supported_kx_groups().count(); + assert_eq!(count, 3); // X25519, P-256, and P-384 + } + + #[test] + fn test_default_provider_has_ecdh() { + let provider = aws_lc_rs::default_provider(); + assert!(provider.has_ecdh()); + } + + #[test] + fn test_supported_cipher_suites_for_signature_algorithm() { + let provider = aws_lc_rs::default_provider(); + let ecdsa_suites: Vec<_> = provider + .supported_cipher_suites_for_signature_algorithm(SignatureAlgorithm::ECDSA) + .map(|cs| cs.suite()) + .collect(); + + assert_eq!(ecdsa_suites.len(), 3); + assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256)); + assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384)); + assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256)); + } +} + +#[cfg(test)] +#[cfg(feature = "rust-crypto")] +mod tests_rust_crypto { + use super::*; + use crate::crypto::rust_crypto; + use crate::dtls12::message::Dtls12CipherSuite; + + #[test] + fn test_default_provider_validates() { + let provider = rust_crypto::default_provider(); + assert!(provider.validate().is_ok()); + } + + #[test] + fn test_default_provider_has_cipher_suites() { + let provider = rust_crypto::default_provider(); + let count = provider.supported_cipher_suites().count(); + // ECDHE: AES-128, AES-256, ChaCha20 + // PSK: CCM-8 + assert_eq!(count, 4); + } + + #[test] + fn test_default_provider_has_kx_groups() { + let provider = rust_crypto::default_provider(); + let count = provider.supported_kx_groups().count(); + assert_eq!(count, 3); // X25519, P-256, and P-384 + } + + #[test] + fn test_default_provider_has_ecdh() { + let provider = rust_crypto::default_provider(); + assert!(provider.has_ecdh()); + } + + #[test] + fn test_supported_cipher_suites_for_signature_algorithm() { + let provider = rust_crypto::default_provider(); + let ecdsa_suites: Vec<_> = provider + .supported_cipher_suites_for_signature_algorithm(SignatureAlgorithm::ECDSA) + .map(|cs| cs.suite()) + .collect(); + + assert_eq!(ecdsa_suites.len(), 3); + assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256)); + assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384)); + assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256)); + } +} diff --git a/third_party/dimpl/src/crypto/validation/p256_cert.der b/third_party/dimpl/src/crypto/validation/p256_cert.der new file mode 100644 index 0000000..7d1eba5 Binary files /dev/null and b/third_party/dimpl/src/crypto/validation/p256_cert.der differ diff --git a/third_party/dimpl/src/crypto/validation/p256_sha256_sig.der b/third_party/dimpl/src/crypto/validation/p256_sha256_sig.der new file mode 100644 index 0000000..269044c Binary files /dev/null and b/third_party/dimpl/src/crypto/validation/p256_sha256_sig.der differ diff --git a/third_party/dimpl/src/crypto/validation/p384_cert.der b/third_party/dimpl/src/crypto/validation/p384_cert.der new file mode 100644 index 0000000..ca1be6a Binary files /dev/null and b/third_party/dimpl/src/crypto/validation/p384_cert.der differ diff --git a/third_party/dimpl/src/crypto/validation/p384_sha384_sig.der b/third_party/dimpl/src/crypto/validation/p384_sha384_sig.der new file mode 100644 index 0000000..fb455bd --- /dev/null +++ b/third_party/dimpl/src/crypto/validation/p384_sha384_sig.der @@ -0,0 +1 @@ +0d0uįhIļģÛŗI‚Ôā)<ŨŊĐŧō#ŧēšzuš•Ö|™)¤ũ ëhĻĪÛØã^djŌE08{ Aõ™ôŲ ŅėíéŊĖíđėš]˛™eĻ=î(HēzDl‚ĸĢ„J hķ \ No newline at end of file diff --git a/third_party/dimpl/src/crypto/validation/test_data.bin b/third_party/dimpl/src/crypto/validation/test_data.bin new file mode 100644 index 0000000..b21064a --- /dev/null +++ b/third_party/dimpl/src/crypto/validation/test_data.bin @@ -0,0 +1 @@ +test data for signature validation \ No newline at end of file diff --git a/third_party/dimpl/src/dtls12/client.rs b/third_party/dimpl/src/dtls12/client.rs new file mode 100644 index 0000000..4ec92a6 --- /dev/null +++ b/third_party/dimpl/src/dtls12/client.rs @@ -0,0 +1,1479 @@ +// DTLS Client Handshake Flow: +// +// 1. Client sends ClientHello +// 2. Server may respond with HelloVerifyRequest containing a cookie +// - If so, Client sends another ClientHello with the cookie +// 3. Server sends ServerHello, Certificate, ServerKeyExchange, +// CertificateRequest (optional), ServerHelloDone +// 4. Client sends Certificate (if requested), ClientKeyExchange, +// CertificateVerify (if client cert present), ChangeCipherSpec, Finished +// 5. Server sends ChangeCipherSpec, Finished +// 6. Handshake complete, application data can flow +// +// This implementation is a Sans-IO DTLS client. + +use std::collections::VecDeque; +use std::time::Instant; + +use arrayvec::ArrayVec; +use subtle::ConstantTimeEq; + +use crate::buffer::{Buf, ToBuf}; +use crate::crypto::SrtpProfile; +use crate::dtls12::Server; +use crate::dtls12::context::AuthMode; +use crate::dtls12::engine::Engine; +use crate::dtls12::message::{Body, CipherSuiteVec, ClientHello, ClientKeyExchange}; +use crate::dtls12::message::{ClientPskKeys, ServerKeyExchangeParams}; +use crate::dtls12::message::{CompressionMethod, ContentType, Cookie}; +use crate::dtls12::message::{DigitallySigned, Dtls12CipherSuite}; +use crate::dtls12::message::{ExtensionType, KeyExchangeAlgorithm, MessageType, ProtocolVersion}; +use crate::dtls12::message::{Random, SessionId, SignatureAndHashAlgorithm, UseSrtpExtension}; +use crate::{Config, DtlsCertificate, Error, InternalError, KeyingMaterial, Output}; + +/// DTLS client +pub struct Client { + /// Current client state. + state: State, + + /// Engine in common between server and client. + engine: Engine, + + /// Random unique data (with gmt timestamp). Used for signature checks. + random: Option, + + /// SessionId is set by the server and only sent by the client if we + /// are reusing a session (key renegotiation). + session_id: Option, + + /// Cookie is sent by the server in the optional HelloVerifyRequest. + /// It might remain null if there is no HelloVerifyRequest. + cookie: Option, + + /// Storage for extension data + extension_data: Buf, + + /// The negotiated SRTP profile (if any) + negotiated_srtp_profile: Option, + + /// Server random. Set by ServerHello. + server_random: Option, + + /// Server certificates + server_certificates: Vec, + + /// Buffer for defragmenting handshakes + defragment_buffer: Buf, + + /// Whether we requested a CertificateVerify + certificate_verify: bool, + + /// Captured session hash for Extended Master Secret (RFC 7627) + /// This is captured after ServerHelloDone to include the correct handshake messages + captured_session_hash: Option, + + /// The last now we seen + last_now: Instant, + + /// Local events + local_events: VecDeque, + + /// Data that is sent before we are connected. + queued_data: Vec, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum LocalEvent { + PeerCert, + Connected, + KeyingMaterial(ArrayVec, SrtpProfile), +} + +impl Client { + pub(crate) fn new_with_engine(mut engine: Engine, now: Instant) -> Client { + engine.set_client(true); + + Client { + state: State::SendClientHello, + engine, + random: None, + session_id: None, + cookie: None, + extension_data: Buf::new(), + negotiated_srtp_profile: None, + server_random: None, + server_certificates: Vec::with_capacity(3), + defragment_buffer: Buf::new(), + certificate_verify: false, + captured_session_hash: None, + last_now: now, + local_events: VecDeque::new(), + queued_data: Vec::new(), + } + } + + /// Create a client from a hybrid ClientHello probe (DTLS 1.2 fork). + /// + /// Accepts the hybrid's random and DTLS-framed handshake bytes so that: + /// - The with-cookie ClientHello uses the same random (HMAC cookie verification). + /// - The transcript contains the initial ClientHello (needed when the + /// server skips HelloVerifyRequest and sends ServerHello directly). + /// + /// If the server does send HVR, `reset_client_for_hello_verify_request` + /// clears the transcript anyway, so the injected bytes are harmless. + pub(crate) fn new_from_hybrid( + random: Random, + handshake_fragment: &[u8], + config: std::sync::Arc, + certificate: DtlsCertificate, + now: Instant, + ) -> Result { + assert!( + !certificate.certificate.is_empty(), + "Client certificate cannot be empty" + ); + // unwrap: malformed private_key bytes are a programmer error from the + // caller who constructed DtlsCertificate; panic matches the prior + // CryptoContext::new behavior which also panicked on empty/invalid + // key material. + let private_key = config + .crypto_provider() + .key_provider + .load_private_key(&certificate.private_key) + .expect("Failed to parse client private key"); + let auth = AuthMode::Certificate { + certificate: certificate.certificate, + private_key, + }; + let mut engine = Engine::new(config, auth); + engine.set_client(true); + // The hybrid ClientHello was sent with message_seq=0 outside this + // engine. Advance the counter so the with-cookie CH gets message_seq=1 + // per RFC 6347 §4.2.2. + engine.set_next_handshake_seq_no(1); + // Inject the hybrid CH into the transcript so it matches the server's + // transcript when the server skips HelloVerifyRequest. + engine.transcript.extend_from_slice(handshake_fragment); + // Advance epoch-0 record sequence past the hybrid CH record. + engine.advance_epoch_0_sequence(); + + let mut client = Client { + state: State::AwaitHelloVerifyRequest, + engine, + random: Some(random), + session_id: None, + cookie: None, + extension_data: Buf::new(), + negotiated_srtp_profile: None, + server_random: None, + server_certificates: Vec::with_capacity(3), + defragment_buffer: Buf::new(), + certificate_verify: false, + captured_session_hash: None, + last_now: now, + local_events: VecDeque::new(), + queued_data: Vec::new(), + }; + client.handle_timeout(now)?; + Ok(client) + } + + pub fn into_server(self) -> Server { + Server::new_with_engine(self.engine, self.last_now) + } + + pub(crate) fn state_name(&self) -> &'static str { + self.state.name() + } + + pub fn is_closing(&self) -> bool { + self.state == State::Closed && !self.is_closed() + } + + pub fn is_closed(&self) -> bool { + self.state == State::Closed + && self.local_events.is_empty() + && !self.engine.has_pending_close_output() + } + + pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { + match self + .engine + .parse_packet(packet) + .and_then(|_| self.make_progress()) + { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { + if let Some(event) = self.local_events.pop_front() { + return event.into_output(buf, &self.server_certificates); + } + self.engine.poll_output(buf, self.last_now) + } + + /// Explicitly start the handshake process by sending a ClientHello + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + self.last_now = now; + if self.random.is_none() { + self.random = Some(Random::new_with_time(now, &mut self.engine.rng)); + } + self.engine.handle_timeout(now)?; + match self.make_progress() { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + /// Send application data when the client is in the Running state + /// + /// This should only be called when the client is in the Running state, + /// after the handshake is complete. + pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { + if self.state == State::Closed { + return Err(Error::ConnectionClosed); + } + + if self.state != State::AwaitApplicationData { + self.queued_data.push(data.to_buf()); + return Ok(()); + } + + // Use the engine's create_record to send application data + // The encryption is now handled in the engine + self.engine + .create_record(ContentType::ApplicationData, 1, false, |body| { + body.extend_from_slice(data); + })?; + + Ok(()) + } + + /// Initiate graceful shutdown by sending a `close_notify` alert. + pub fn close(&mut self) -> Result<(), Error> { + if self.state == State::Closed { + return Ok(()); + } + if self.state != State::AwaitApplicationData { + self.engine.abort(); + self.state = State::Closed; + return Ok(()); + } + self.engine + .create_record(ContentType::Alert, 1, false, |body| { + body.push(1); // level: warning + body.push(0); // description: close_notify + })?; + self.state = State::Closed; + Ok(()) + } + + fn make_progress(&mut self) -> Result<(), InternalError> { + loop { + let prev_state = self.state; + + let new_state = prev_state.make_progress(self)?; + if prev_state != new_state { + self.state = new_state; + trace!("{:?} -> {:?}", prev_state, new_state); + } else { + break; + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + SendClientHello, + AwaitHelloVerifyRequest, + AwaitServerHello, + AwaitCertificate, + AwaitServerKeyExchange, + AwaitCertificateRequest, + AwaitServerHelloDone, + SendCertificate, + SendClientKeyExchange, + SendCertificateVerify, + SendChangeCipherSpec, + SendFinished, + AwaitChangeCipherSpec, + AwaitNewSessionTicket, + AwaitFinished, + AwaitApplicationData, + Closed, +} + +impl State { + fn name(&self) -> &'static str { + match self { + State::SendClientHello => "SendClientHello", + State::AwaitHelloVerifyRequest => "AwaitHelloVerifyRequest", + State::AwaitServerHello => "AwaitServerHello", + State::AwaitCertificate => "AwaitCertificate", + State::AwaitServerKeyExchange => "AwaitServerKeyExchange", + State::AwaitCertificateRequest => "AwaitCertificateRequest", + State::AwaitServerHelloDone => "AwaitServerHelloDone", + State::SendCertificate => "SendCertificate", + State::SendClientKeyExchange => "SendClientKeyExchange", + State::SendCertificateVerify => "SendCertificateVerify", + State::SendChangeCipherSpec => "SendChangeCipherSpec", + State::SendFinished => "SendFinished", + State::AwaitChangeCipherSpec => "AwaitChangeCipherSpec", + State::AwaitNewSessionTicket => "AwaitNewSessionTicket", + State::AwaitFinished => "AwaitFinished", + State::AwaitApplicationData => "AwaitApplicationData", + State::Closed => "Closed", + } + } + + fn make_progress(self, client: &mut Client) -> Result { + match self { + State::SendClientHello => self.send_client_hello(client), + State::AwaitHelloVerifyRequest => self.await_hello_verify_request(client), + State::AwaitServerHello => self.await_server_hello(client), + State::AwaitCertificate => self.await_certificate(client), + State::AwaitServerKeyExchange => self.await_server_key_exchange(client), + State::AwaitCertificateRequest => self.await_certificate_request(client), + State::AwaitServerHelloDone => self.await_server_hello_done(client), + State::SendCertificate => self.send_certificate(client), + State::SendClientKeyExchange => self.send_client_key_exchange(client), + State::SendCertificateVerify => self.send_certificate_verify(client), + State::SendChangeCipherSpec => self.send_change_cipher_spec(client), + State::SendFinished => self.send_finished(client), + State::AwaitChangeCipherSpec => self.await_change_cipher_spec(client), + State::AwaitNewSessionTicket => self.await_new_session_ticket(client), + State::AwaitFinished => self.await_finished(client), + State::AwaitApplicationData => self.await_application_data(client), + State::Closed => Ok(self), + } + } + + fn send_client_hello(self, client: &mut Client) -> Result { + let session_id = client.session_id.unwrap_or_else(SessionId::empty); + let cookie = client.cookie.unwrap_or_else(Cookie::empty); + // unwrap: is ok because we set the random in handle_timeout + let random = client.random.unwrap(); + + // Determine flight number: 1 for initial CH, 3 for retransmit with cookie + let flight_no = if client.cookie.is_none() { 1 } else { 3 }; + client.engine.flight_begin(flight_no); + + client + .engine + .create_handshake(MessageType::ClientHello, |body, engine| { + handshake_create_client_hello( + body, + engine, + cookie, + random, + session_id, + &mut client.extension_data, + ) + })?; + + let can_hello_verify = client.cookie.is_none(); + + if can_hello_verify { + Ok(Self::AwaitHelloVerifyRequest) + } else { + Ok(Self::AwaitServerHello) + } + } + + fn await_hello_verify_request(self, client: &mut Client) -> Result { + let has_hello = client + .engine + .has_complete_handshake(MessageType::ServerHello); + + // Got ServerHello, skip HelloVerifyRequest + if has_hello { + return Ok(Self::AwaitServerHello); + } + + let maybe = client.engine.next_handshake( + MessageType::HelloVerifyRequest, + &mut client.defragment_buffer, + )?; + + let Some(handshake) = maybe else { + // Stay in this state + return Ok(self); + }; + + let Body::HelloVerifyRequest(h) = handshake.body else { + unreachable!() + }; + + // RFC 6347 4.2.1: The server_version field in the HelloVerifyRequest message MUST be set to DTLS 1.0 + // https://datatracker.ietf.org/doc/html/rfc6347#section-4.2.1 + if h.server_version != ProtocolVersion::DTLS1_2 + && h.server_version != ProtocolVersion::DTLS1_0 + { + return Err(Error::SecurityError( + crate::SecurityError::UnsupportedHelloVerifyRequestVersion(h.server_version), + ) + .into()); + } + + debug!( + "Received HelloVerifyRequest with cookie length: {}", + h.cookie.len() + ); + + // Set cookie for next ClientHello + client.cookie = Some(h.cookie); + + // HelloVerifyRequest exchange must not be part of the handshake transcript. + // Per RFC 6347 §4.2.2, the next ClientHello (with cookie) has message_seq=1. + trace!("Resetting handshake state after HelloVerifyRequest"); + client.engine.reset_client_for_hello_verify_request(); + + // Redo ClientHello, now with cookie. + Ok(Self::SendClientHello) + } + + fn await_server_hello(self, client: &mut Client) -> Result { + let maybe = client + .engine + .next_handshake(MessageType::ServerHello, &mut client.defragment_buffer)?; + + let Some(handshake) = maybe else { + // Stay in same state + return Ok(self); + }; + + let Body::ServerHello(server_hello) = &handshake.body else { + unreachable!() + }; + + debug!( + "Received ServerHello with cipher suite: {:?}", + server_hello.cipher_suite + ); + + // Enforce DTLS version + if server_hello.server_version != ProtocolVersion::DTLS1_2 { + return Err( + Error::SecurityError(crate::SecurityError::UnsupportedServerVersion( + server_hello.server_version, + )) + .into(), + ); + } + + // Enforce Null compression only + if server_hello.compression_method != CompressionMethod::Null { + return Err( + Error::SecurityError(crate::SecurityError::UnsupportedServerCompression( + server_hello.compression_method, + )) + .into(), + ); + } + + // Enforce cipher suite is known and allowed + let cs = server_hello.cipher_suite; + if cs.is_unknown() { + return Err((Error::SecurityError( + crate::SecurityError::ServerSelectedUnknownCipherSuite, + )) + .into()); + } + + // Enforce cipher suite is compatible with our private key and allowed by config + let is_compatible = client + .engine + .crypto_context() + .is_cipher_suite_compatible(cs); + + if !is_compatible { + return Err(Error::SecurityError( + crate::SecurityError::ServerSelectedIncompatibleCipherSuite(cs), + ) + .into()); + } + + if !client.engine.is_cipher_suite_allowed(cs) { + return Err(Error::SecurityError( + crate::SecurityError::ServerSelectedDisallowedCipherSuite(cs), + ) + .into()); + } + + // Note: we keep offered suites local; we don't enforce echo here + client.engine.set_cipher_suite(cs); + client.session_id = Some(server_hello.session_id); + client.server_random = Some(server_hello.random); + + let mut extended_master_secret = false; + + // Check for use_srtp and extended_master_secret extensions + let Some(extensions) = &server_hello.extensions else { + return Err((Error::IncompleteServerHello).into()); + }; + + for extension in extensions { + if extension.extension_type == ExtensionType::UseSrtp { + // Parse the use_srtp extension to get the selected profile + let extension_data = extension.extension_data(&client.defragment_buffer); + let (_, use_srtp) = + UseSrtpExtension::parse(extension_data).map_err(InternalError::from)?; + // Store the first profile as our negotiated profile + if !use_srtp.profiles.is_empty() { + client.negotiated_srtp_profile = Some(use_srtp.profiles[0].into()); + trace!( + "ServerHello UseSRTP extension processed; selected profile: {:?}", + client.negotiated_srtp_profile + ); + } + } + + // We are to use extended master secret + if extension.extension_type == ExtensionType::ExtendedMasterSecret { + extended_master_secret = true; + trace!("Server negotiated Extended Master Secret"); + } + } + + // Without extended master secret, in DTLS1.2 a security attack + // reusing the same master secret is possible. + if !extended_master_secret { + return Err(Error::SecurityError( + crate::SecurityError::ExtendedMasterSecretNotNegotiated, + ) + .into()); + } + + if let Some(profile) = client.negotiated_srtp_profile { + debug!("Negotiated SRTP profile: {:?}", profile); + } + trace!("Extended Master Secret enabled"); + + // PSK suites skip Certificate; go directly to ServerKeyExchange + if cs.is_psk() { + Ok(Self::AwaitServerKeyExchange) + } else { + Ok(Self::AwaitCertificate) + } + } + + fn await_certificate(self, client: &mut Client) -> Result { + let maybe = client + .engine + .next_handshake(MessageType::Certificate, &mut client.defragment_buffer)?; + + let Some(ref handshake) = maybe else { + // Stay in same state + return Ok(self); + }; + + let Body::Certificate(certificate) = &handshake.body else { + unreachable!() + }; + + if certificate.certificate_list.is_empty() { + return Err((Error::CertificateError( + crate::CertificateError::NoServerCertificateReceived, + )) + .into()); + } + + debug!( + "Received Certificate message with {} certificate(s)", + certificate.certificate_list.len() + ); + + // Extract certificate ranges before dropping handshake + let cert_ranges: ArrayVec<_, 32> = certificate + .certificate_list + .iter() + .map(|cert| cert.0.clone()) + .collect(); + + drop(maybe); + + // Convert ASN.1 certificates to byte arrays + for (i, range) in cert_ranges.iter().enumerate() { + let cert_data = &client.defragment_buffer[range.clone()]; + trace!("Certificate #{} size: {} bytes", i + 1, cert_data.len()); + client.server_certificates.push(cert_data.to_buf()); + } + + Ok(Self::AwaitServerKeyExchange) + } + + fn await_server_key_exchange(self, client: &mut Client) -> Result { + let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + if cipher_suite.is_psk() { + self.await_server_key_exchange_psk(client) + } else { + self.await_server_key_exchange_ecdhe(client) + } + } + + fn await_server_key_exchange_ecdhe(self, client: &mut Client) -> Result { + let maybe = client.engine.next_handshake( + MessageType::ServerKeyExchange, + &mut client.defragment_buffer, + )?; + + if maybe.is_none() { + // Stay in same state + return Ok(self); + }; + + // Extract all ranges/data we need before accessing buffer + let (signature_range, signature_algorithm, curve_type, named_group, public_key_range) = { + let handshake = maybe.as_ref().unwrap(); + let Body::ServerKeyExchange(server_key_exchange) = &handshake.body else { + unreachable!() + }; + + let Some(d_signed) = server_key_exchange.signature() else { + // We do not support anonymous key exchange + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::ServerKeyExchangeWithoutSignature, + ) + .into()); + }; + + let signature_range = d_signed.signature_range.clone(); + let signature_algorithm = d_signed.algorithm; + + // Extract ECDH params ranges + let (curve_type, named_group, public_key_range) = match &server_key_exchange.params { + ServerKeyExchangeParams::Ecdh(ecdh) => ( + ecdh.curve_type, + ecdh.named_group, + ecdh.public_key_range.clone(), + ), + ServerKeyExchangeParams::Psk(_) => { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::PskServerKeyExchangeInEcdhePath, + ) + .into()); + } + }; + + ( + signature_range, + signature_algorithm, + curve_type, + named_group, + public_key_range, + ) + }; + + // unwrap: is ok because we verify the order of the flight + let client_random = client.random.unwrap(); + let server_random = client.server_random.unwrap(); + + // Drop maybe to release the buffer borrow + drop(maybe); + + // Now we can access the buffer to get the actual bytes + let signature_bytes = &client.defragment_buffer[signature_range]; + let public_key_vec = &client.defragment_buffer[public_key_range]; + + // Build signed_data = client_random || server_random || SKE params (without signature) + let mut signed_data = Buf::new(); + client_random.serialize(&mut signed_data); + server_random.serialize(&mut signed_data); + // Manually serialize SKE params + signed_data.push(curve_type.as_u8()); + signed_data.extend_from_slice(&named_group.as_u16().to_be_bytes()); + signed_data.push(public_key_vec.len() as u8); + signed_data.extend_from_slice(public_key_vec); + + let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + // Ensure the server's (hash, signature) pair was offered by the client + let offered = SignatureAndHashAlgorithm::supported().contains(&signature_algorithm); + if !offered { + return Err(Error::CryptoError( + crate::CryptoError::SignatureAlgorithmNotOfferedByClient, + ) + .into()); + } + + // Ensure the signature algorithm is compatible with the cipher suite + if let Some(expected_sig) = cipher_suite.signature_algorithm() { + if signature_algorithm.signature != expected_sig { + return Err( + Error::CryptoError(crate::CryptoError::SignatureAlgorithmMismatch { + expected: expected_sig, + actual: signature_algorithm.signature, + }) + .into(), + ); + } + } + + // unwrap: is ok because we verify the order of the flight + let cert_der = client.server_certificates.first().unwrap(); + + // Create a temporary DigitallySigned for verification (we only need the algorithm) + let temp_signed = DigitallySigned { + algorithm: signature_algorithm, + signature_range: 0..signature_bytes.len(), + }; + + client + .engine + .crypto_context_mut() + .verify_signature(&signed_data, &temp_signed, signature_bytes, cert_der) + .map_err(Error::CryptoError)?; + + trace!( + "ServerKeyExchange signature verified: {:?}", + signature_algorithm + ); + + // Process the server key exchange parameters + // We already have the curve and public key extracted + let mut kx_buf = client.engine.pop_buffer(); + client + .engine + .crypto_context_mut() + .process_ecdh_params(named_group, public_key_vec, &mut kx_buf) + .map_err(Error::CryptoError)?; + client.engine.push_buffer(kx_buf); + + Ok(Self::AwaitCertificateRequest) + } + + /// PSK ServerKeyExchange carries only an optional identity hint (no signature). + /// Per RFC 4279 §2, ServerKeyExchange is omitted when the server has no hint. + fn await_server_key_exchange_psk(self, client: &mut Client) -> Result { + // If the server skipped ServerKeyExchange (no hint), go straight to ServerHelloDone + let has_done = client + .engine + .has_complete_handshake(MessageType::ServerHelloDone); + if has_done { + return Ok(Self::AwaitServerHelloDone); + } + + let maybe = client.engine.next_handshake( + MessageType::ServerKeyExchange, + &mut client.defragment_buffer, + )?; + + let Some(handshake) = maybe else { + return Ok(self); + }; + + let Body::ServerKeyExchange(ske) = &handshake.body else { + unreachable!() + }; + + // PSK ServerKeyExchange contains only an identity hint per RFC 4279 §2 + // (no curve_type or named_group — those are ECDHE-only parameters). + let hint_range = match &ske.params { + ServerKeyExchangeParams::Psk(psk) => psk.hint_range.clone(), + _ => { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::EcdheServerKeyExchangeInPskPath, + ) + .into()); + } + }; + + drop(handshake); + + let hint = &client.defragment_buffer[hint_range]; + trace!("PSK identity hint ({} bytes)", hint.len()); + // Hint is informational only; we don't use it for PSK lookup currently + + // PSK has no CertificateRequest + Ok(Self::AwaitServerHelloDone) + } + + fn await_certificate_request(self, client: &mut Client) -> Result { + let has_done = client + .engine + .has_complete_handshake(MessageType::ServerHelloDone); + + if has_done { + return Ok(Self::AwaitServerHelloDone); + } + + let maybe = client.engine.next_handshake( + MessageType::CertificateRequest, + &mut client.defragment_buffer, + )?; + + let Some(handshake) = maybe else { + // stay in same state + return Ok(self); + }; + + let Body::CertificateRequest(cr) = &handshake.body else { + unreachable!() + }; + + // Check that the hash algorithm that is default fo the PrivateKey in use + // is one of the supported by the CertificateRequest + // unwrap: CertificateRequest only received for certificate-based suites + let hash_algorithm = client + .engine + .crypto_context() + .private_key_default_hash_algorithm() + .unwrap(); + + if !cr.supports_hash_algorithm(hash_algorithm) { + return Err(Error::CertificateError( + crate::CertificateError::UnsupportedHashAlgorithm(hash_algorithm), + ) + .into()); + } + + debug!( + "Server supports CertificateVerify hash algorithm: {:?}", + hash_algorithm + ); + + debug!("Received CertificateRequest; enabling client authentication path"); + client.certificate_verify = true; + + Ok(Self::AwaitServerHelloDone) + } + + fn await_server_hello_done(self, client: &mut Client) -> Result { + let maybe = client + .engine + .next_handshake(MessageType::ServerHelloDone, &mut client.defragment_buffer)?; + + let Some(handshake) = maybe else { + // stay in same state + return Ok(self); + }; + + let Body::ServerHelloDone = handshake.body else { + unreachable!() + }; + + trace!("Received ServerHelloDone"); + + let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + if cipher_suite.is_psk() { + // PSK: no certificates involved + return Ok(Self::SendClientKeyExchange); + } + + // Validate the server certificate + if client.server_certificates.is_empty() { + return Err((Error::CertificateError( + crate::CertificateError::NoServerCertificateReceived, + )) + .into()); + } + + // Send the server certificate as an event + if !client.server_certificates.is_empty() { + client.local_events.push_back(LocalEvent::PeerCert); + } + + if client.certificate_verify { + Ok(Self::SendCertificate) + } else { + Ok(Self::SendClientKeyExchange) + } + } + + fn send_certificate(self, client: &mut Client) -> Result { + debug!("Sending Certificate"); + + // Start/restart flight timer for client Flight 5 + client.engine.flight_begin(5); + + // Now use the engine with the stored data + client + .engine + .create_handshake(MessageType::Certificate, handshake_create_certificate)?; + + Ok(Self::SendClientKeyExchange) + } + + fn send_client_key_exchange(self, client: &mut Client) -> Result { + trace!("Sending ClientKeyExchange"); + + // Start/restart flight timer only if this flight did not start with Certificate + if !client.certificate_verify { + client.engine.flight_begin(5); + } + + // Send client key exchange message + client.engine.create_handshake( + MessageType::ClientKeyExchange, + handshake_create_client_key_exchange, + )?; + + // Capture session hash now for Extended Master Secret (RFC 7627) + // At this point, the session hash includes: ClientHello, ServerHello, Certificate, + // ServerKeyExchange, CertificateRequest, ServerHelloDone, Certificate, ClientKeyExchange + // This is correct per RFC 7627 - session hash should include messages + // up to and including ClientKeyExchange + let cipher_suite = client.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + let suite_hash = cipher_suite.hash_algorithm(); + let mut buf = Buf::new(); + client.engine.transcript_hash(suite_hash, &mut buf); + client.captured_session_hash = Some(buf); + + if client.certificate_verify { + Ok(Self::SendCertificateVerify) + } else { + Ok(Self::SendChangeCipherSpec) + } + } + + fn send_certificate_verify(self, client: &mut Client) -> Result { + debug!("Sending CertificateVerify"); + + // Send the certificate verify message + client.engine.create_handshake( + MessageType::CertificateVerify, + handshake_create_certificate_verify, + )?; + + Ok(Self::SendChangeCipherSpec) + } + + fn send_change_cipher_spec(self, client: &mut Client) -> Result { + Self::derive_keys(client)?; + + // Send change cipher spec + trace!("Sending ChangeCipherSpec"); + client + .engine + .create_record(ContentType::ChangeCipherSpec, 0, true, |body| { + // Change cipher spec is just a single byte with value 1 + body.push(1); + })?; + + Ok(Self::SendFinished) + } + + fn derive_keys(client: &mut Client) -> Result<(), Error> { + trace!("Deriving keys"); + let Some(cipher_suite) = client.engine.cipher_suite() else { + return Err(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + )); + }; + + trace!("Using cipher suite for key derivation: {:?}", cipher_suite); + + let Some(server_random) = &client.server_random else { + return Err(Error::InvalidState( + crate::InvalidStateError::NoServerRandom, + )); + }; + + // Extract and format the random values for key derivation + let mut client_random_buf_b = Buf::new(); + let mut server_random_buf_b = Buf::new(); + + // Serialize the random values to raw bytes + // unwrap: is ok because we set the random in handle_timeout + client.random.unwrap().serialize(&mut client_random_buf_b); + server_random.serialize(&mut server_random_buf_b); + let client_random_buf = client_random_buf_b; + let server_random_buf = server_random_buf_b; + + // Derive master secret (use EMS if negotiated) + let suite_hash = cipher_suite.hash_algorithm(); + + // Use the captured session hash from when ServerHelloDone was received + let session_hash = client + .captured_session_hash + .as_ref() + .ok_or(Error::InvalidState( + crate::InvalidStateError::ExtendedMasterSecretSessionHashMissing, + ))?; + trace!( + "Using captured session hash for Extended Master Secret (length: {})", + session_hash.len() + ); + let mut out = client.engine.pop_buffer(); + let mut scratch = client.engine.pop_buffer(); + client + .engine + .crypto_context_mut() + .derive_extended_master_secret(session_hash, suite_hash, &mut out, &mut scratch) + .map_err(Error::CryptoError)?; + + // Derive the encryption/decryption keys + client + .engine + .crypto_context_mut() + .derive_keys( + cipher_suite, + &client_random_buf, + &server_random_buf, + &mut out, + &mut scratch, + ) + .map_err(Error::CryptoError)?; + + client.engine.push_buffer(out); + client.engine.push_buffer(scratch); + + Ok(()) + } + + fn send_finished(self, client: &mut Client) -> Result { + trace!("Sending Finished message to complete handshake"); + + client + .engine + .create_handshake(MessageType::Finished, |body, engine| { + // Calculate verify data for Finished message using PRF + let verify_data = engine.generate_verify_data(true)?; + + debug!("Generated verify data for Finished message (12 bytes)"); + + // Directly write the verify data without creating Finished struct + body.extend_from_slice(&verify_data); + Ok(()) + })?; + + Ok(Self::AwaitChangeCipherSpec) + } + + fn await_change_cipher_spec(self, client: &mut Client) -> Result { + let maybe = client.engine.next_record(ContentType::ChangeCipherSpec); + + let Some(_) = maybe else { + // Stay in same state + return Ok(self); + }; + + // Drop any extra CCS resends to avoid being blocked + trace!("Dropping any pending CCS resends from peer"); + client.engine.drop_pending_ccs(); + + // Expect every record to be decrypted from now on. + trace!("Received ChangeCipherSpec; enabling peer encryption"); + client.engine.enable_peer_encryption()?; + + Ok(Self::AwaitNewSessionTicket) + } + + fn await_new_session_ticket(self, client: &mut Client) -> Result { + let has_finished = client.engine.has_complete_handshake(MessageType::Finished); + + if has_finished { + return Ok(Self::AwaitFinished); + } + + let maybe = client + .engine + .next_handshake(MessageType::NewSessionTicket, &mut client.defragment_buffer)?; + + let Some(handshake) = maybe else { + // Stay in same state + return Ok(self); + }; + + let Body::NewSessionTicket(_t) = handshake.body else { + unreachable!() + }; + + // TODO(martin): handle ticket for restart + + trace!("Received NewSessionTicket"); + + Ok(Self::AwaitFinished) + } + + fn await_finished(self, client: &mut Client) -> Result { + // Generate expected verify data based on current transcript. + // This must be done before next_handshake() below since + // it should not include Finished itself. + let expected = client.engine.generate_verify_data(false)?; + + let maybe = client + .engine + .next_handshake(MessageType::Finished, &mut client.defragment_buffer)?; + + if maybe.is_none() { + // stay in same state + return Ok(self); + } + + // Extract the range from the handshake + let verify_data_range = if let Some(ref handshake) = maybe { + if let Body::Finished(finished) = &handshake.body { + finished.verify_data_range.clone() + } else { + panic!("Finished message should have been parsed"); + } + } else { + unreachable!() + }; + + // Drop maybe to release the buffer borrow + drop(maybe); + + // Now we can access the buffer + let verify_data = &client.defragment_buffer[verify_data_range]; + trace!( + "Finished.verify_data received len={}, expected len={}", + verify_data.len(), + expected.len() + ); + // Use constant-time comparison to prevent timing attacks + let is_eq: bool = verify_data.ct_eq(expected.as_slice()).into(); + if !is_eq { + return Err((Error::SecurityError( + crate::SecurityError::ServerFinishedVerificationFailed, + )) + .into()); + } + + trace!("Server Finished verified successfully"); + + // Receiving server Finished implicitly acks our Flight 5; stop resends + client.engine.flight_stop_resend_timers(); + + // Emit Connected event + client.local_events.push_back(LocalEvent::Connected); + + // Extract and emit SRTP keying material if we have a negotiated profile + if let Some(profile) = client.negotiated_srtp_profile { + let suite_hash = client.engine.cipher_suite().unwrap().hash_algorithm(); + + let mut out = client.engine.pop_buffer(); + let mut scratch = client.engine.pop_buffer(); + if let Ok(keying_material) = client + .engine + .crypto_context() + .extract_srtp_keying_material(profile, suite_hash, &mut out, &mut scratch) + { + client.engine.push_buffer(out); + client.engine.push_buffer(scratch); + // Emit the keying material event with the negotiated profile + debug!( + "SRTP keying material extracted ({} bytes) for profile: {:?}", + keying_material.len(), + profile + ); + // expect should be correct here since we negotiated the profile + let profile = client + .negotiated_srtp_profile + .expect("SRTP profile should be negotiated"); + client + .local_events + .push_back(LocalEvent::KeyingMaterial(keying_material, profile)); + } else { + client.engine.push_buffer(out); + client.engine.push_buffer(scratch); + } + } + + client.engine.release_application_data(); + + debug!("Handshake complete; ready for application data"); + + Ok(Self::AwaitApplicationData) + } + + fn await_application_data(self, client: &mut Client) -> Result { + if client.engine.close_notify_received() { + // RFC 5246 §7.2.1: respond with a reciprocal close_notify and + // close down immediately, discarding any pending writes. + client.engine.discard_pending_writes(); + client + .engine + .create_record(ContentType::Alert, 1, false, |body| { + body.push(1); // level: warning + body.push(0); // description: close_notify + })?; + return Ok(State::Closed); + } + + if !client.queued_data.is_empty() { + debug!( + "Sending queued application data: {}", + client.queued_data.len() + ); + for data in client.queued_data.drain(..) { + client + .engine + .create_record(ContentType::ApplicationData, 1, false, |body| { + body.extend_from_slice(&data); + })?; + } + } + + Ok(self) + } +} + +fn handshake_create_client_hello( + body: &mut Buf, + engine: &mut Engine, + cookie: Cookie, + random: Random, + session_id: SessionId, + extension_data: &mut Buf, +) -> Result<(), Error> { + let client_version = ProtocolVersion::DTLS1_2; + + // Get cipher suites from config that are compatible with our key + let cipher_suites: CipherSuiteVec = engine + .config() + .dtls12_cipher_suites() + .map(|cs| cs.suite()) + .filter(|suite| engine.crypto_context().is_cipher_suite_compatible(*suite)) + .take(Dtls12CipherSuite::supported().len()) + .collect(); + + debug!( + "Sending ClientHello: DTLS version={:?}, cookie_len={}, offering {} cipher suites", + client_version, + cookie.len(), + cipher_suites.len() + ); + + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + // Create ClientHello with all required extensions + let client_hello = ClientHello::new( + client_version, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + ) + .with_extensions(extension_data, engine.config()); + + client_hello.serialize(extension_data, body); + Ok(()) +} + +fn handshake_create_certificate(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { + let crypto = engine.crypto_context(); + crypto.serialize_client_certificate(body); + Ok(()) +} + +fn handshake_create_client_key_exchange(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { + // Just check that a cipher suite exists without binding to unused variable + let Some(cipher_suite) = engine.cipher_suite() else { + return Err(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + )); + }; + let key_exchange_algorithm = cipher_suite.as_key_exchange_algorithm(); + + debug!("Using key exchange algorithm: {:?}", key_exchange_algorithm); + + match key_exchange_algorithm { + KeyExchangeAlgorithm::EECDH => { + // Get group info before the mutable borrow + let group_info = engine.crypto_context().get_key_exchange_group_info(); + + // For ECDHE, use the group information we retrieved earlier + let Some((curve_type, named_group)) = group_info else { + unreachable!("No group info available for ECDHE"); + }; + + trace!( + "Using ECDHE group info: {:?}, {:?}", + curve_type, named_group + ); + + let public_key = engine + .crypto_context_mut() + .maybe_init_key_exchange() + .map_err(Error::CryptoError)?; + + trace!("Generated public key size: {} bytes", public_key.len()); + ClientKeyExchange::serialize_from_bytes(public_key, body); + } + KeyExchangeAlgorithm::PSK => { + let identity = engine + .config() + .psk_identity() + .ok_or(Error::PskError(crate::PskError::NoPskIdentityConfigured))? + .to_vec(); + + // Resolve the PSK via the configured resolver + let psk = engine + .config() + .psk_resolver() + .ok_or(Error::PskError(crate::PskError::NoPskResolverConfigured))? + .resolve(&identity) + .ok_or(Error::PskError(crate::PskError::ResolverReturnedNoKey))?; + + // Set the PSK and compute pre-master secret + let crypto = engine.crypto_context_mut(); + crypto.set_psk(psk); + crypto + .compute_psk_pre_master_secret() + .map_err(Error::CryptoError)?; + + ClientPskKeys::serialize_from_bytes(&identity, body); + } + _ => { + return Err(Error::SecurityError( + crate::SecurityError::UnsupportedKeyExchangeAlgorithm, + )); + } + } + + Ok(()) +} + +fn handshake_create_certificate_verify(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { + // The hash algorithm to use is the default for the private key type, not + // the one negotiated to use with the selected cipher suite. I.e. + // if we negotiate ECDHE_ECDSA_AES256_GCM_SHA384, we are gogin to use + // SHA384 for the signature of the main crypto, but not for CertificateVerify + // where a private key using P256 curve means we use SHA256. + // unwrap: CertificateVerify only sent for certificate-based suites + let hash_alg = engine + .crypto_context() + .private_key_default_hash_algorithm() + .unwrap(); + debug!("Using hash algorithm for signature: {:?}", hash_alg); + + // Get the signature algorithm type + // unwrap: CertificateVerify only sent for certificate-based suites + let sig_alg = engine.crypto_context().signature_algorithm().unwrap(); + debug!("Using signature algorithm: {:?}", sig_alg); + + // Create the signature algorithm + let algorithm = SignatureAndHashAlgorithm::new(hash_alg, sig_alg); + + let mut signature = engine.pop_buffer(); + + // Sign all handshake messages + let handshake_data = &engine.transcript; + engine + .crypto_context + .sign_data(handshake_data, hash_alg, &mut signature) + .map_err(Error::CryptoError)?; + + debug!("Generated signature size: {} bytes", signature.len()); + + // For sending, directly write the CertificateVerify bytes + body.extend_from_slice(&algorithm.as_u16().to_be_bytes()); + body.extend_from_slice(&(signature.len() as u16).to_be_bytes()); + body.extend_from_slice(&signature); + + engine.push_buffer(signature); + + Ok(()) +} + +impl LocalEvent { + pub fn into_output<'a>(self, buf: &'a mut [u8], peer_certs: &[Buf]) -> Output<'a> { + match self { + LocalEvent::PeerCert => { + let l = peer_certs[0].len(); + assert!( + l <= buf.len(), + "Output buffer too small for peer certificate" + ); + buf[..l].copy_from_slice(&peer_certs[0]); + Output::PeerCert(&buf[..l]) + } + LocalEvent::Connected => Output::Connected, + LocalEvent::KeyingMaterial(m, profile) => { + Output::KeyingMaterial(KeyingMaterial::new(&m), profile) + } + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + fn psk_client() -> Client { + let engine = Engine::new(Arc::new(Config::default()), AuthMode::Psk); + Client::new_with_engine(engine, Instant::now()) + } + + fn epoch0_handshake_packet(msg_type: MessageType, message_seq: u16, body: &[u8]) -> Vec { + let handshake_len = 12 + body.len(); + let mut packet = Vec::new(); + packet.push(ContentType::Handshake.as_u8()); + packet.extend_from_slice(&[0xfe, 0xfd]); + packet.extend_from_slice(&0u16.to_be_bytes()); + packet.extend_from_slice(&0u64.to_be_bytes()[2..]); + packet.extend_from_slice(&(handshake_len as u16).to_be_bytes()); + packet.push(msg_type.as_u8()); + packet.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); + packet.extend_from_slice(&message_seq.to_be_bytes()); + packet.extend_from_slice(&0u32.to_be_bytes()[1..]); + packet.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); + packet.extend_from_slice(body); + packet + } + + #[test] + fn empty_server_certificate_is_certificate_error() { + let mut client = psk_client(); + client + .engine + .parse_packet(&epoch0_handshake_packet( + MessageType::Certificate, + 0, + &[0, 0, 0], + )) + .expect("queue empty Certificate"); + + let err = State::AwaitCertificate + .await_certificate(&mut client) + .expect_err("empty server Certificate should fail"); + + assert!(matches!( + err, + crate::InternalError::Fatal(Error::CertificateError(_)) + )); + } + + #[test] + fn derive_keys_without_cipher_suite_is_invalid_state() { + let mut client = psk_client(); + + let err = State::derive_keys(&mut client) + .expect_err("derive_keys requires negotiated cipher suite"); + + assert!(matches!(err, Error::InvalidState(_))); + } + + #[test] + fn derive_keys_without_server_random_is_invalid_state() { + let mut client = psk_client(); + client + .engine + .set_cipher_suite(Dtls12CipherSuite::PSK_AES128_CCM_8); + + let err = State::derive_keys(&mut client).expect_err("derive_keys requires server random"); + + assert!(matches!(err, Error::InvalidState(_))); + } +} diff --git a/third_party/dimpl/src/dtls12/context.rs b/third_party/dimpl/src/dtls12/context.rs new file mode 100644 index 0000000..30502c8 --- /dev/null +++ b/third_party/dimpl/src/dtls12/context.rs @@ -0,0 +1,696 @@ +//! DTLS 1.2 cryptographic context for a session. + +use std::sync::Arc; + +use arrayvec::ArrayVec; + +use crate::CryptoError; +use crate::buffer::{Buf, TmpBuf, ToBuf}; +use crate::crypto; +use crate::crypto::SrtpProfile; +use crate::crypto::{Aad, Iv, Nonce}; +use crate::dtls12::message::DigitallySigned; +use crate::dtls12::message::{Asn1Cert, Certificate}; +use crate::dtls12::message::{CurveType, Dtls12CipherSuite, HashAlgorithm}; +use crate::dtls12::message::{NamedGroup, SignatureAlgorithm}; + +/// DTLS 1.2 crypto context holding negotiated keys and ciphers for a session. +pub struct CryptoContext { + /// Configuration (contains crypto provider) + config: Arc, + + /// Key exchange mechanism + key_exchange: Option>, + + /// Our public key from the key exchange (stored for reuse) + key_exchange_public_key: Option>, + + /// Group info from the key exchange (stored for reuse) + key_exchange_group: Option, + + /// Client write key + client_write_key: Option, + + /// Server write key + server_write_key: Option, + + /// Client write IV (4 bytes for AES-GCM, 12 bytes for ChaCha20-Poly1305) + client_write_iv: Option, + + /// Server write IV (4 bytes for AES-GCM, 12 bytes for ChaCha20-Poly1305) + server_write_iv: Option, + + /// Client MAC key (not used for AEAD ciphers) + client_mac_key: Option, + + /// Server MAC key (not used for AEAD ciphers) + server_mac_key: Option, + + /// Master secret + master_secret: Option>, + + /// Pre-master secret (temporary) + pre_master_secret: Option, + + /// Client cipher + client_cipher: Option>, + + /// Server cipher + server_cipher: Option>, + + /// Authentication mode: certificate or PSK. + auth: AuthMode, + + /// Resolved PSK value (set during handshake after identity exchange) + psk: Option>, + + /// Client random (needed for SRTP key export per RFC 5705) + client_random: Option>, + + /// Server random (needed for SRTP key export per RFC 5705) + server_random: Option>, +} + +/// Authentication mode for a DTLS 1.2 session. +pub enum AuthMode { + /// Certificate-based authentication (ECDHE_ECDSA suites). + Certificate { + /// DER-encoded certificate. + certificate: Vec, + /// Parsed signing key for the certificate. + private_key: Box, + }, + /// Pre-shared key authentication (PSK suites). + /// The actual PSK value is resolved during the handshake via [`CryptoContext::set_psk`]. + Psk, +} + +impl CryptoContext { + /// Create a new crypto context with the given authentication mode. + pub fn new(auth: AuthMode, config: Arc) -> Self { + CryptoContext { + config, + key_exchange: None, + key_exchange_public_key: None, + key_exchange_group: None, + client_write_key: None, + server_write_key: None, + client_write_iv: None, + server_write_iv: None, + client_mac_key: None, + server_mac_key: None, + master_secret: None, + pre_master_secret: None, + client_cipher: None, + server_cipher: None, + auth, + psk: None, + client_random: None, + server_random: None, + } + } + + pub fn provider(&self) -> &crypto::CryptoProvider { + self.config.crypto_provider() + } + + /// Generate key exchange public key + pub fn maybe_init_key_exchange(&mut self) -> Result<&[u8], CryptoError> { + // If we already have the public key stored, return it + if let Some(ref pk) = self.key_exchange_public_key { + return Ok(pk); + } + + // Otherwise, get it from the key exchange and store it + match &self.key_exchange { + Some(ke) => { + let pub_key = ke.pub_key().to_vec(); + let group = ke.group(); + self.key_exchange_public_key = Some(pub_key); + self.key_exchange_group = Some(group); + Ok(self.key_exchange_public_key.as_ref().unwrap()) + } + None => Err(CryptoError::KeyExchangeNotInitialized), + } + } + + /// Process peer's public key and compute shared secret + pub fn compute_shared_secret( + &mut self, + peer_public_key: &[u8], + buf: &mut Buf, + ) -> Result<(), CryptoError> { + let ke = self + .key_exchange + .take() + .ok_or(CryptoError::KeyExchangeNotInitialized)?; + ke.complete(peer_public_key, buf)?; + self.pre_master_secret = Some(core::mem::take(buf)); + // Note: we keep key_exchange_public_key since it may be needed later + Ok(()) + } + + /// Set the resolved PSK value for this session. + pub fn set_psk(&mut self, psk: Vec) { + self.psk = Some(psk); + } + + /// Compute PSK pre-master secret per RFC 4279 §2. + /// + /// Format: `uint16(N) || zeros(N) || uint16(N) || PSK(N)` + /// where N is the PSK length. + pub fn compute_psk_pre_master_secret(&mut self) -> Result<(), CryptoError> { + let psk = self.psk.as_ref().ok_or(CryptoError::PskNotSet)?; + let n = psk.len(); + // Total: 2 + N + 2 + N = 2N + 4 + let mut pms = Buf::new(); + pms.extend_from_slice(&(n as u16).to_be_bytes()); + pms.resize(pms.len() + n, 0); + pms.extend_from_slice(&(n as u16).to_be_bytes()); + pms.extend_from_slice(psk); + self.pre_master_secret = Some(pms); + Ok(()) + } + + /// Initialize ECDHE key exchange (server role) and return our ephemeral public key + pub fn init_ecdh_server( + &mut self, + named_group: NamedGroup, + kx_buf: &mut Buf, + ) -> Result<&[u8], CryptoError> { + // Find the matching key exchange group from the provider + let kx_group = self + .provider() + .supported_kx_groups() + .find(|g| g.name() == named_group) + .ok_or(CryptoError::UnsupportedEcdheNamedGroup(named_group))?; + + kx_buf.clear(); + self.key_exchange = Some(kx_group.start_exchange(core::mem::take(kx_buf))?); + self.maybe_init_key_exchange() + } + + /// Process a ServerKeyExchange message and set up key exchange accordingly + pub fn process_ecdh_params( + &mut self, + group: NamedGroup, + server_public: &[u8], + kx_buf: &mut Buf, + ) -> Result<(), CryptoError> { + // Find the matching key exchange group from the provider + let kx_group = self + .provider() + .supported_kx_groups() + .find(|g| g.name() == group) + .ok_or(CryptoError::UnsupportedEcdheNamedGroup(group))?; + + // Create a new ECDH key exchange + kx_buf.clear(); + self.key_exchange = Some(kx_group.start_exchange(core::mem::take(kx_buf))?); + + // Generate our keypair + let _our_public = self.maybe_init_key_exchange()?; + + // Compute shared secret with the server's public key + self.compute_shared_secret(server_public, kx_buf)?; + + Ok(()) + } + + /// Derive master secret using Extended Master Secret (RFC 7627) + pub fn derive_extended_master_secret( + &mut self, + session_hash: &[u8], + hash: HashAlgorithm, + out: &mut Buf, + scratch: &mut Buf, + ) -> Result<(), CryptoError> { + trace!("Deriving extended master secret"); + let Some(pms) = &self.pre_master_secret else { + return Err(CryptoError::PreMasterSecretNotAvailable); + }; + crypto::prf_hkdf::prf_tls12( + self.provider().hmac_provider, + pms, + "extended master secret", + session_hash, + out, + 48, + scratch, + hash, + )?; + let mut master_secret = ArrayVec::new(); + master_secret + .try_extend_from_slice(out) + .map_err(|_| CryptoError::MasterSecretTooLong)?; + self.master_secret = Some(master_secret); + // Clear pre-master secret after use (security measure) + self.pre_master_secret = None; + Ok(()) + } + + /// Derive keys for encryption/decryption + pub fn derive_keys( + &mut self, + cipher_suite: Dtls12CipherSuite, + client_random: &[u8], + server_random: &[u8], + key_block: &mut Buf, + scratch: &mut Buf, + ) -> Result<(), CryptoError> { + let Some(master_secret) = &self.master_secret else { + return Err(CryptoError::MasterSecretNotAvailable); + }; + + // Store the randoms for later SRTP key export (RFC 5705) + let mut client_random_arr = ArrayVec::new(); + client_random_arr + .try_extend_from_slice(client_random) + .expect("client_random too long"); + self.client_random = Some(client_random_arr); + + let mut server_random_arr = ArrayVec::new(); + server_random_arr + .try_extend_from_slice(server_random) + .expect("server_random too long"); + self.server_random = Some(server_random_arr); + + // Find the cipher suite from the provider + let supported_cipher_suite = self + .provider() + .cipher_suites + .iter() + .find(|cs| cs.suite() == cipher_suite) + .ok_or(CryptoError::UnsupportedCipherSuite(cipher_suite))?; + + // Get key sizes from the provider + let (mac_key_len, enc_key_len, fixed_iv_len) = supported_cipher_suite.key_lengths(); + + // Calculate total key material length + let key_material_len = 2 * (mac_key_len + enc_key_len + fixed_iv_len); + + // Compute seed for key expansion: server_random + client_random + let mut seed = [0u8; 64]; + seed[..32].copy_from_slice(server_random); + seed[32..].copy_from_slice(client_random); + + // Generate key material using PRF + crypto::prf_hkdf::prf_tls12( + self.provider().hmac_provider, + master_secret, + "key expansion", + &seed, + key_block, + key_material_len, + scratch, + cipher_suite.hash_algorithm(), + )?; + + // Split key material + let mut offset = 0; + + // Extract MAC keys (if used) + if mac_key_len > 0 { + self.client_mac_key = Some(key_block[offset..offset + mac_key_len].to_buf()); + offset += mac_key_len; + self.server_mac_key = Some(key_block[offset..offset + mac_key_len].to_buf()); + offset += mac_key_len; + } + + // Extract encryption keys + self.client_write_key = Some(key_block[offset..offset + enc_key_len].to_buf()); + offset += enc_key_len; + self.server_write_key = Some(key_block[offset..offset + enc_key_len].to_buf()); + offset += enc_key_len; + + // Extract IVs + self.client_write_iv = Some(Iv::new(&key_block[offset..offset + fixed_iv_len])); + offset += fixed_iv_len; + self.server_write_iv = Some(Iv::new(&key_block[offset..offset + fixed_iv_len])); + + // Initialize ciphers using the provider + self.client_cipher = + Some(supported_cipher_suite.create_cipher(self.client_write_key.as_ref().unwrap())?); + + self.server_cipher = + Some(supported_cipher_suite.create_cipher(self.server_write_key.as_ref().unwrap())?); + + Ok(()) + } + + /// Encrypt data (client to server) + pub fn encrypt_client_to_server( + &mut self, + plaintext: &mut Buf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + match &mut self.client_cipher { + Some(cipher) => cipher.encrypt(plaintext, aad, nonce), + None => Err(CryptoError::ClientCipherNotInitialized), + } + } + + /// Decrypt data (server to client) + pub fn decrypt_server_to_client( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + match &mut self.server_cipher { + Some(cipher) => cipher.decrypt(ciphertext, aad, nonce), + None => Err(CryptoError::ServerCipherNotInitialized), + } + } + + /// Encrypt data (server to client) + pub fn encrypt_server_to_client( + &mut self, + plaintext: &mut Buf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + match &mut self.server_cipher { + Some(cipher) => cipher.encrypt(plaintext, aad, nonce), + None => Err(CryptoError::ServerCipherNotInitialized), + } + } + + /// Decrypt data (client to server) + pub fn decrypt_client_to_server( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), CryptoError> { + match &mut self.client_cipher { + Some(cipher) => cipher.decrypt(ciphertext, aad, nonce), + None => Err(CryptoError::ClientCipherNotInitialized), + } + } + + /// Get client certificate for authentication. + /// + /// Invariant: callers must only invoke this for certificate-based suites. + /// PSK handshakes never send a Certificate message (RFC 4279), and the + /// state machine routes around this path via `cs.is_psk()` checks before + /// reaching Certificate serialization. Violating the invariant is a + /// programmer bug and panics. + pub fn get_client_certificate(&self) -> Certificate { + let AuthMode::Certificate { certificate, .. } = &self.auth else { + panic!("get_client_certificate called in PSK mode"); + }; + let cert = Asn1Cert(0..certificate.len()); + let mut certs = ArrayVec::new(); + certs.push(cert); + Certificate::new(certs) + } + + /// Serialize client certificate for authentication. + /// + /// Same invariant as [`Self::get_client_certificate`]: cert-mode only. + pub fn serialize_client_certificate(&self, output: &mut Buf) { + let cert = self.get_client_certificate(); + let AuthMode::Certificate { certificate, .. } = &self.auth else { + panic!("serialize_client_certificate called in PSK mode"); + }; + cert.serialize(certificate, output); + } + + /// Sign the provided data using the client's private key. + /// Returns an error if no private key is configured (PSK-only mode). + pub fn sign_data( + &mut self, + data: &[u8], + hash_alg: HashAlgorithm, + out: &mut Buf, + ) -> Result<(), CryptoError> { + let AuthMode::Certificate { private_key, .. } = &mut self.auth else { + return Err(CryptoError::NoPrivateKeyConfigured); + }; + private_key.sign(data, hash_alg, out) + } + + /// Generate verify data for a Finished message using PRF + pub fn generate_verify_data( + &self, + handshake_hash: &[u8], + is_client: bool, + hash: HashAlgorithm, + out: &mut Buf, + scratch: &mut Buf, + ) -> Result, CryptoError> { + let master_secret = match &self.master_secret { + Some(ms) => ms, + None => return Err(CryptoError::MasterSecretNotAvailable), + }; + + let label = if is_client { + "client finished" + } else { + "server finished" + }; + + // Generate 12 bytes of verify data using PRF + crypto::prf_hkdf::prf_tls12( + self.provider().hmac_provider, + master_secret, + label, + handshake_hash, + out, + 12, + scratch, + hash, + )?; + let mut verify_data = ArrayVec::new(); + verify_data + .try_extend_from_slice(out) + .map_err(|_| CryptoError::VerifyDataTooLong)?; + Ok(verify_data) + } + + /// Extract SRTP keying material from the master secret + /// This is per RFC 5764 (DTLS-SRTP) section 4.2 and RFC 5705 (TLS Exporter) + pub fn extract_srtp_keying_material( + &self, + profile: SrtpProfile, + hash: HashAlgorithm, + out: &mut Buf, + scratch: &mut Buf, + ) -> Result, CryptoError> { + const DTLS_SRTP_KEY_LABEL: &str = "EXTRACTOR-dtls_srtp"; + + let master_secret = match &self.master_secret { + Some(ms) => ms, + None => return Err(CryptoError::MasterSecretNotAvailable), + }; + + let client_random = match &self.client_random { + Some(cr) => cr, + None => return Err(CryptoError::ClientRandomNotAvailable), + }; + + let server_random = match &self.server_random { + Some(sr) => sr, + None => return Err(CryptoError::ServerRandomNotAvailable), + }; + + // Per RFC 5705, the exporter uses: PRF(master_secret, label, client_random + server_random) + // The seed for DTLS-SRTP exporter is client_random + server_random (no additional context) + let mut seed = ArrayVec::::new(); + seed.try_extend_from_slice(client_random) + .expect("client_random too long"); + seed.try_extend_from_slice(server_random) + .expect("server_random too long"); + + crypto::prf_hkdf::prf_tls12( + self.provider().hmac_provider, + master_secret, + DTLS_SRTP_KEY_LABEL, + &seed, + out, + profile.keying_material_len(), + scratch, + hash, + )?; + let mut keying_material = ArrayVec::new(); + keying_material + .try_extend_from_slice(out) + .map_err(|_| CryptoError::KeyingMaterialTooLong)?; + + Ok(keying_material) + } + + /// Signature algorithm for the configured private key. + /// Returns None in PSK-only mode. + pub fn signature_algorithm(&self) -> Option { + match &self.auth { + AuthMode::Certificate { private_key, .. } => Some(private_key.algorithm()), + AuthMode::Psk => None, + } + } + + /// Default hash algorithm for the configured private key. + /// Returns None in PSK-only mode. + pub fn private_key_default_hash_algorithm(&self) -> Option { + match &self.auth { + AuthMode::Certificate { private_key, .. } => Some(private_key.hash_algorithm()), + AuthMode::Psk => None, + } + } + + /// Hash algorithms the configured private key can sign with. + /// Returns an empty slice in PSK-only mode. + pub fn private_key_supported_hash_algorithms(&self) -> &[HashAlgorithm] { + match &self.auth { + AuthMode::Certificate { private_key, .. } => private_key.supported_hash_algorithms(), + AuthMode::Psk => &[], + } + } + + /// Create a hash context for the given algorithm + pub fn create_hash(&self, algorithm: HashAlgorithm) -> Box { + self.provider().hash_provider.create_hash(algorithm) + } + + /// Get the key exchange group info (curve type and named group). + pub fn get_key_exchange_group_info(&self) -> Option<(CurveType, NamedGroup)> { + // Use stored group if available (after key exchange is consumed) + if let Some(group) = self.key_exchange_group { + return Some((CurveType::NamedCurve, group)); + } + + // Otherwise get it from the active key exchange + let Some(ke) = &self.key_exchange else { + return None; + }; + Some((CurveType::NamedCurve, ke.group())) + } + + /// Check if the client's private key is compatible with a given cipher suite. + pub fn is_cipher_suite_compatible(&self, cipher_suite: Dtls12CipherSuite) -> bool { + match (&self.auth, cipher_suite.signature_algorithm()) { + // Certificate-based suite needs a matching private key + (AuthMode::Certificate { private_key, .. }, Some(sig_alg)) => { + sig_alg == private_key.algorithm() + } + // PSK suite is only compatible in PSK mode + (AuthMode::Psk, None) => true, + // Mismatch: cert context + PSK suite, or PSK context + cert suite + _ => false, + } + } + + /// Get the client write IV if derived. + pub fn get_client_write_iv(&self) -> Option { + self.client_write_iv + } + + /// Get the server write IV if derived. + pub fn get_server_write_iv(&self) -> Option { + self.server_write_iv + } + + /// Verify a DigitallySigned structure against a certificate's public key. + pub fn verify_signature( + &self, + data: &Buf, + signature: &DigitallySigned, + signature_buf: &[u8], + cert_der: &[u8], + ) -> Result<(), CryptoError> { + self.provider().signature_verification.verify_signature( + cert_der, + data, + signature.signature(signature_buf), + signature.algorithm.hash, + signature.algorithm.signature, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Config; + + #[cfg(feature = "rcgen")] + fn cert_auth_mode(config: &Config) -> AuthMode { + let cert = crate::certificate::generate_self_signed_certificate().expect("generate cert"); + let private_key = config + .crypto_provider() + .key_provider + .load_private_key(&cert.private_key) + .expect("parse key"); + AuthMode::Certificate { + certificate: cert.certificate, + private_key, + } + } + + #[test] + #[cfg(feature = "rcgen")] + fn certificate_mode_rejects_psk_suites() { + let config = Arc::new(Config::default()); + let auth = cert_auth_mode(&config); + let ctx = CryptoContext::new(auth, config); + + for suite in Dtls12CipherSuite::supported() { + if suite.is_psk() { + assert!( + !ctx.is_cipher_suite_compatible(*suite), + "Certificate-mode context must reject PSK suite {:?}", + suite + ); + } + } + } + + #[test] + #[cfg(feature = "rcgen")] + fn certificate_mode_accepts_ecdhe_suites() { + let config = Arc::new(Config::default()); + let auth = cert_auth_mode(&config); + let ctx = CryptoContext::new(auth, config); + + // At least one ECDHE_ECDSA suite should be compatible + assert!( + Dtls12CipherSuite::supported() + .iter() + .filter(|s| !s.is_psk()) + .any(|s| ctx.is_cipher_suite_compatible(*s)), + "Certificate-mode context must accept at least one ECDHE suite" + ); + } + + #[test] + fn psk_mode_rejects_certificate_suites() { + let config = Arc::new(Config::default()); + let ctx = CryptoContext::new(AuthMode::Psk, config); + + for suite in Dtls12CipherSuite::supported() { + if !suite.is_psk() { + assert!( + !ctx.is_cipher_suite_compatible(*suite), + "PSK-mode context must reject certificate suite {:?}", + suite + ); + } + } + } + + #[test] + fn psk_mode_accepts_psk_suites() { + let config = Arc::new(Config::default()); + let ctx = CryptoContext::new(AuthMode::Psk, config); + + assert!( + Dtls12CipherSuite::supported() + .iter() + .filter(|s| s.is_psk()) + .any(|s| ctx.is_cipher_suite_compatible(*s)), + "PSK-mode context must accept at least one PSK suite" + ); + } +} diff --git a/third_party/dimpl/src/dtls12/engine.rs b/third_party/dimpl/src/dtls12/engine.rs new file mode 100644 index 0000000..9310eb7 --- /dev/null +++ b/third_party/dimpl/src/dtls12/engine.rs @@ -0,0 +1,1400 @@ +use std::mem; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{Duration, Instant}; + +use super::queue::{QueueRx, QueueTx}; +use crate::buffer::{Buf, BufferPool, TmpBuf}; +use crate::crypto::{Aad, Iv, Nonce}; +use crate::dtls12::context::{AuthMode, CryptoContext}; +use crate::dtls12::incoming::{Incoming, Record, RecordHandler}; +use crate::dtls12::message::{Body, HashAlgorithm, Header, MessageType, ProtocolVersion, Sequence}; +use crate::dtls12::message::{ContentType, DTLSRecord, Dtls12CipherSuite, Handshake}; +use crate::error::bounded_error_len; +use crate::timer::ExponentialBackoff; +use crate::window::ReplayWindow; +use crate::{Config, Error, InternalError, Output, SeededRng}; + +const MAX_DEFRAGMENT_PACKETS: usize = 50; + +// Using debug_ignore_primary since CryptoContext doesn't implement Debug +pub struct Engine { + config: Arc, + + /// Seedable random number generator for deterministic testing + pub(crate) rng: SeededRng, + + /// Pool of buffers + buffers_free: BufferPool, + + /// Counters for sending DTLSRecord during epoch 0. + /// + /// This is kept separate since resends might force us to + /// "go back" to these sequence number even if we technically + /// progressed to epoch 1. + sequence_epoch_0: Sequence, + + /// Counters for epoch 1 and beyond. + sequence_epoch_n: Sequence, + + /// Queue of incoming packets. + queue_rx: QueueRx, + + /// Queue of outgoing packets. + queue_tx: QueueTx, + + /// The cipher suite in use. Set by ServerHello. + cipher_suite: Option, + + /// Per-record explicit nonce length, cached from the provider suite at + /// `set_cipher_suite` time. 0 for ChaCha20-Poly1305, 8 for AES-GCM. + explicit_nonce_len: usize, + + /// Minimum length of a protected record's encrypted fragment, cached from + /// the provider suite. See + /// [`crate::crypto::SupportedDtls12CipherSuite::min_protected_fragment_len`]. + /// For AEAD suites this is `explicit_nonce + tag`; used both to reject + /// short incoming records and to size outgoing record overhead. + min_protected_fragment_len: usize, + + /// Cryptographic context for handling encryption/decryption + pub(crate) crypto_context: CryptoContext, + + /// Whether the remote peer has enabled encryption + peer_encryption_enabled: bool, + + /// Whether this engine is for a client (true) or server (false) + is_client: bool, + + /// Expected peer handshake sequence number + peer_handshake_seq_no: u16, + + /// Next handshake message sequence number for sending + next_handshake_seq_no: u16, + + /// Handshakes collected for hash computation. + /// + /// NB: pub(crate) because we need to sign it in client.rs + pub(crate) transcript: Buf, + + /// Anti-replay window state (per current epoch) + replay: ReplayWindow, + + /// The records that have been sent in the current flight. + flight_saved_records: Vec, + + /// Flight backoff + flight_backoff: ExponentialBackoff, + + /// Timeout for the current flight + flight_timeout: Timeout, + + /// Global timeout for the entire connect operation. + connect_timeout: Timeout, + + /// Whether we are ready to release application data from poll_output. + release_app_data: bool, + + /// Whether we have confirmation that the peer completed the handshake, i.e. + /// that the peer received our final flight. Once set, a stale plaintext + /// handshake (which is unauthenticated and replayable after encryption is + /// enabled) no longer triggers a courtesy flight retransmission. + /// + /// This is set from two signals, each meaningful for one role: + /// - the client stops its resend timer when it completes, which means the + /// server received our final flight (the client confirms at completion); + /// - receiving authenticated application data, which means the peer is past + /// its handshake (the server's only proof the client received flight 6). + peer_handshake_confirmed: bool, + + /// Whether a close_notify alert has been received from the peer. + close_notify_received: bool, + + /// Whether [`Output::CloseNotify`] has already been emitted. + close_notify_reported: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Timeout { + Disabled, + Unarmed, + Armed(Instant), +} + +#[derive(Debug)] +struct Entry { + content_type: ContentType, + epoch: u16, + fragment: Buf, +} + +enum PollOutput<'a> { + Data(&'a [u8]), + BufferTooSmall { needed: usize }, + None(&'a mut [u8]), +} + +impl Engine { + pub fn new(config: Arc, auth: AuthMode) -> Self { + let mut rng = SeededRng::new(config.rng_seed()); + + let flight_backoff = + ExponentialBackoff::new(config.flight_start_rto(), config.flight_retries(), &mut rng); + + let crypto_context = CryptoContext::new(auth, Arc::clone(&config)); + + Self { + config, + rng, + buffers_free: BufferPool::default(), + sequence_epoch_0: Sequence::new(0), + sequence_epoch_n: Sequence::new(1), + queue_rx: QueueRx::new(), + queue_tx: QueueTx::new(), + cipher_suite: None, + explicit_nonce_len: 0, + min_protected_fragment_len: 0, + crypto_context, + peer_encryption_enabled: false, + is_client: false, + peer_handshake_seq_no: 0, + next_handshake_seq_no: 0, + transcript: Buf::new(), + replay: ReplayWindow::new(), + flight_saved_records: Vec::new(), + flight_backoff, + flight_timeout: Timeout::Unarmed, + connect_timeout: Timeout::Unarmed, + release_app_data: false, + peer_handshake_confirmed: false, + close_notify_received: false, + close_notify_reported: false, + } + } + + pub fn set_client(&mut self, is_client: bool) { + self.is_client = is_client; + } + + /// Set the next outgoing handshake message sequence number. + /// + /// Used by `Client::new_from_hybrid` to account for the hybrid + /// ClientHello (message_seq=0) that was already sent outside this engine. + pub fn set_next_handshake_seq_no(&mut self, seq: u16) { + self.next_handshake_seq_no = seq; + } + + /// Advance the epoch-0 record sequence number by one. + /// + /// Used by `Client::new_from_hybrid` so subsequent epoch-0 records + /// don't reuse the sequence number of the hybrid ClientHello record. + pub fn advance_epoch_0_sequence(&mut self) { + self.sequence_epoch_0.sequence_number += 1; + } + + pub fn config(&self) -> &Config { + &self.config + } + + /// Get a reference to the cipher suite + pub fn cipher_suite(&self) -> Option { + self.cipher_suite + } + + /// Minimum length of a protected record's encrypted fragment for the + /// negotiated suite. See + /// [`crate::crypto::SupportedDtls12CipherSuite::min_protected_fragment_len`]. + pub fn min_protected_fragment_len(&self) -> usize { + self.min_protected_fragment_len + } + + /// Is the given cipher suite allowed by configuration + pub fn is_cipher_suite_allowed(&self, suite: Dtls12CipherSuite) -> bool { + self.config + .dtls12_cipher_suites() + .any(|cs| cs.suite() == suite) + } + + /// Get a reference to the crypto context + pub fn crypto_context(&self) -> &CryptoContext { + &self.crypto_context + } + + /// Get a mutable reference to the crypto context + pub fn crypto_context_mut(&mut self) -> &mut CryptoContext { + &mut self.crypto_context + } + + pub fn parse_packet(&mut self, packet: &[u8]) -> Result<(), InternalError> { + let cs = self.cipher_suite; + let incoming = Incoming::parse_packet(packet, self, cs)?; + if let Some(incoming) = incoming { + self.insert_incoming(incoming)?; + } + + Ok(()) + } + + /// Insert a parsed datagram into the receive queue. + fn insert_incoming(&mut self, incoming: Incoming) -> Result<(), Error> { + // Capacity guard before iterating records. + if self.queue_rx.len() >= self.config.max_queue_rx() { + warn!( + "Receive queue full (max {}): {:?}", + self.config.max_queue_rx(), + self.queue_rx + ); + return Err(Error::ReceiveQueueFull); + } + + // Dispatch to specialized handlers + if incoming.first().first_handshake().is_some() { + self.insert_incoming_handshake(incoming) + } else { + self.insert_incoming_non_handshake(incoming) + } + } + + fn insert_incoming_handshake(&mut self, incoming: Incoming) -> Result<(), Error> { + let first_record = incoming.first(); + let handshake = first_record + .first_handshake() + .expect("caller ensures handshake"); + + let key_current = ( + handshake.header.message_seq, + handshake.header.fragment_offset, + ); + + let maybe_dupe_seq = incoming + .records() + .iter() + .filter_map(|r| r.first_handshake()) + .filter_map(|h| h.dupe_triggers_resend()) + .next(); + + // Some MessageType when resent, means we must trigger + // an immediate resend of the entire flight. Once the peer is confirmed + // to have completed the handshake, a stale plaintext handshake is just + // unauthenticated noise (or a replay/amplification attempt) and must not + // drive a resend. + if let Some(dupe_seq) = maybe_dupe_seq { + if dupe_seq < self.peer_handshake_seq_no && !self.peer_handshake_confirmed { + self.flight_resend("dupe triggers resend")?; + } + } + + // Drop old duplicates we've already processed - don't let them block newer messages. + if handshake.header.message_seq < self.peer_handshake_seq_no { + return Ok(()); + } + + if self.peer_encryption_enabled && first_record.record().sequence.epoch == 0 { + // Keep old plaintext handshake records available long enough to + // trigger flight resends above, but never queue or process them as + // new messages after peer encryption is enabled. + return Ok(()); + } + + // Reject new handshakes after initial handshake is complete (renegotiation not supported). + if self.release_app_data && handshake.header.message_seq >= self.peer_handshake_seq_no { + return Err(Error::RenegotiationAttempt); + } + + let search_result = self.queue_rx.binary_search_by(|item| { + let key_other = item + .first() + .first_handshake() + .as_ref() + .map(|h| (h.header.message_seq, h.header.fragment_offset)) + .unwrap_or((u16::MAX, u32::MAX)); + key_other.cmp(&key_current) + }); + + match search_result { + Err(index) => { + // Insert in order of handshake key + self.queue_rx.insert(index, incoming); + } + Ok(_) => { + // Exact duplicate handshake fragment + } + } + + Ok(()) + } + + fn insert_incoming_non_handshake(&mut self, incoming: Incoming) -> Result<(), Error> { + let first = incoming.first(); + let seq_current = first.record().sequence; + + if self.peer_encryption_enabled + && seq_current.epoch == 0 + && first.record().content_type == ContentType::Handshake + { + return Ok(()); + } + + if self.peer_encryption_enabled { + for record in incoming.records().iter() { + if record.record().sequence.epoch == 0 + && record.record().content_type == ContentType::Handshake + { + if record.handshakes().is_empty() { + record.set_handled(); + } else { + for handshake in record.handshakes() { + handshake.set_handled(); + } + } + } + } + } + + let search_result = self + .queue_rx + .binary_search_by_key(&seq_current, |item| item.first().record().sequence); + + match search_result { + Err(index) => self.queue_rx.insert(index, incoming), + Ok(_) => { + // For epoch 0, we can get duplicates due to resends. + // For epoch 1, we have the replay window and there should + // be no duplicates. + assert_eq!(seq_current.epoch, 0); + } + } + + Ok(()) + } + + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + if self.connect_timeout == Timeout::Unarmed { + debug!( + "Connect timeout in: {:.03}s", + self.config.handshake_timeout().as_secs_f32() + ); + let timeout = now + self.config.handshake_timeout(); + self.connect_timeout = Timeout::Armed(timeout); + } + if self.flight_timeout == Timeout::Unarmed { + debug!( + "Flight timeout in: {:.03}s", + self.flight_backoff.rto().as_secs_f32() + ); + let timeout = now + self.flight_backoff.rto(); + self.flight_timeout = Timeout::Armed(timeout); + } + + // The connect timeout is the overall timeout for establishing the connection + if let Timeout::Armed(connect_timeout) = self.connect_timeout { + if now >= connect_timeout { + return Err(Error::Timeout(crate::TimeoutError::Connect)); + } + } + + // If there is no flight timeout, we have already checked the global connect timeout. + let Timeout::Armed(flight_timeout) = self.flight_timeout else { + return Ok(()); + }; + + if now >= flight_timeout { + if self.flight_backoff.can_retry() { + self.flight_backoff.attempt(&mut self.rng); + debug!( + "Re-arm flight timeout due to resend in {}", + self.flight_backoff.rto().as_secs_f32() + ); + let timeout = now + self.flight_backoff.rto(); + self.flight_timeout = Timeout::Armed(timeout); + self.flight_resend("flight timeout")?; + } else { + return Err(Error::Timeout(crate::TimeoutError::Handshake)); + } + } + + Ok(()) + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8], now: Instant) -> Output<'a> { + // Drain incoming queue of processed records. + self.purge_handled_queue_rx(); + + let buf = match self.poll_app_data(buf) { + PollOutput::Data(p) => return Output::ApplicationData(p), + PollOutput::BufferTooSmall { needed } => return Output::BufferTooSmall { needed }, + PollOutput::None(b) => b, + }; + + match self.poll_packet_tx(buf) { + PollOutput::Data(p) => return Output::Packet(p), + PollOutput::BufferTooSmall { needed } => return Output::BufferTooSmall { needed }, + PollOutput::None(_) => {} + } + + if self.close_notify_received && !self.close_notify_reported { + self.close_notify_reported = true; + return Output::CloseNotify; + } + + let next_timeout = self.poll_timeout(now); + + Output::Timeout(next_timeout) + } + + fn poll_app_data<'a>(&mut self, buf: &'a mut [u8]) -> PollOutput<'a> { + if !self.release_app_data { + return PollOutput::None(buf); + } + + let mut unhandled = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .filter(|r| r.record().content_type == ContentType::ApplicationData) + .skip_while(|r| r.is_handled()); + + let Some(next) = unhandled.next() else { + return PollOutput::None(buf); + }; + + let record_buffer = next.buffer(); + let fragment = next.record().fragment(record_buffer); + let len = fragment.len(); + + if len > buf.len() { + return PollOutput::BufferTooSmall { needed: len }; + } + + buf[..len].copy_from_slice(fragment); + next.set_handled(); + + PollOutput::Data(&buf[..len]) + } + + fn purge_handled_queue_rx(&mut self) { + while let Some(peek) = self.queue_rx.front() { + let fully_handled = peek.records().iter().all(|r| r.is_handled()); + + if fully_handled { + let incoming = self.queue_rx.pop_front().unwrap(); + incoming + .into_records() + .for_each(|r| self.buffers_free.push(r.into_buffer())); + } else { + break; + } + } + } + + fn poll_packet_tx<'a>(&mut self, buf: &'a mut [u8]) -> PollOutput<'a> { + let Some(p) = self.queue_tx.front() else { + return PollOutput::None(buf); + }; + + if p.len() > buf.len() { + return PollOutput::BufferTooSmall { needed: p.len() }; + } + + let p = self + .queue_tx + .pop_front() + .expect("queue front checked above"); + let len = p.len(); + buf[..len].copy_from_slice(&p); + + PollOutput::Data(&buf[..len]) + } + + fn poll_timeout(&self, now: Instant) -> Instant { + // No timeouts, return a distant future + if self.connect_timeout == Timeout::Disabled && self.flight_timeout == Timeout::Disabled { + const DISTANT_FUTURE: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60); + return now + DISTANT_FUTURE; + } + + match (self.connect_timeout, self.flight_timeout) { + // Keep this before the `(Armed, _)` arms. Starting a new flight resets its timer to + // `Unarmed`, but leaves the overall connection timer armed. If that mixed state + // returned the connection deadline, the caller would not drive `handle_timeout` to + // arm the flight timer until the whole handshake expired, so the flight would never + // be retransmitted. Returning `now` requests that immediate drive; the next poll sees + // both concrete deadlines and can return the earlier one. + (Timeout::Unarmed, _) | (_, Timeout::Unarmed) => now, + (Timeout::Armed(c), Timeout::Armed(f)) => { + if c < f { + c + } else { + f + } + } + (Timeout::Armed(c), _) => c, + (_, Timeout::Armed(f)) => f, + _ => now, + } + } + + pub fn flight_begin(&mut self, flight_no: u8) { + debug!("Begin flight {}", flight_no); + self.flight_backoff.reset(&mut self.rng); + self.flight_clear_resends(); + self.flight_timeout = Timeout::Unarmed; + } + + pub fn flight_stop_resend_timers(&mut self) { + debug!("Stop connect and flight timeouts"); + self.flight_timeout = Timeout::Disabled; + self.connect_timeout = Timeout::Disabled; + + // The client stops its resend timer only once it has received the + // server's final flight, which proves the server received the client's + // final flight — so the peer is confirmed. The server, by contrast, + // stops its timer right after sending flight 6, before the client has + // confirmed anything, so it must NOT confirm here (it relies on later + // authenticated application data instead). + if self.is_client { + self.peer_handshake_confirmed = true; + } + } + + fn flight_clear_resends(&mut self) { + for entry in self.flight_saved_records.drain(..) { + self.buffers_free.push(entry.fragment); + } + } + + fn flight_resend(&mut self, reason: &str) -> Result<(), Error> { + debug!("Resending flight due to {}", reason); + + let replace_pending_handshake_output = !self.release_app_data; + + if replace_pending_handshake_output { + self.queue_tx.clear(); + } + + // For lifetime issues, we take the entries out of self + let records = mem::take(&mut self.flight_saved_records); + + let mut result = Ok(()); + for (index, entry) in records.iter().enumerate() { + result = self.create_record_inner( + entry.content_type, + entry.epoch, + false, + replace_pending_handshake_output && index == 0, + |fragment| { + fragment.extend_from_slice(&entry.fragment); + }, + ); + if result.is_err() { + break; + } + } + + // Put the entries back into self + self.flight_saved_records = records; + + result + } + + pub fn has_complete_handshake(&mut self, wanted: MessageType) -> bool { + self.has_complete_handshake_with_seq(wanted, self.peer_handshake_seq_no) + } + + fn has_complete_handshake_with_seq(&mut self, wanted: MessageType, expected_seq: u16) -> bool { + let mut skip_handled = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + // Cap to MAX_DEFRAGMENT_PACKETS to avoid misbehaving peers + .take(MAX_DEFRAGMENT_PACKETS) + .flat_map(|r| r.handshakes().iter()) + .skip_while(|h| h.is_handled()) + .peekable(); + + let maybe_first_handshake = skip_handled.peek(); + + let Some(first) = maybe_first_handshake else { + return false; + }; + + if first.header.message_seq != expected_seq { + return false; + } + + if first.header.msg_type != wanted { + return false; + } + + let wanted_seq = first.header.message_seq; + let wanted_length = first.header.length; + let mut last_fragment_end = 0; + + for h in skip_handled { + // A different seq means we're looking at a different handshake + if wanted_seq != h.header.message_seq { + continue; + } + + // Check fragment contiguity + if h.header.fragment_offset != last_fragment_end { + return false; + } + last_fragment_end = h.header.fragment_offset + h.header.fragment_length; + + // Found the last fragment to complete the wanted handshake. + if last_fragment_end == wanted_length { + return true; + } + } + + false + } + + pub fn next_handshake( + &mut self, + wanted: MessageType, + defragment_buffer: &mut Buf, + ) -> Result, InternalError> { + if !self.has_complete_handshake(wanted) { + return Ok(None); + } + + let iter = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + .flat_map(|r| r.handshakes().iter().map(move |h| (h, r.buffer()))) + .skip_while(|(h, _)| h.is_handled()); + + // This sets the handled flag on the handshake. + // Passing Some(&mut self.transcript) to have defragment write to transcript + // before creating the handshake, avoiding borrow conflicts. + let handshake = Handshake::defragment( + iter, + defragment_buffer, + self.cipher_suite, + Some(&mut self.transcript), + )?; + + // Move the expected seq_no along + self.peer_handshake_seq_no = handshake.header.message_seq + 1; + + Ok(Some(handshake)) + } + + pub(crate) fn next_record(&mut self, ctype: ContentType) -> Option<&Record> { + let record = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .find(|r| !r.is_handled())?; + + if record.record().content_type != ctype { + return None; + } + + record.set_handled(); + + Some(record) + } + + /// Mark any pending ChangeCipherSpec records as handled and purge them. + /// We can accumulate multiple ChangeCipherSpec due to resends. Since they + /// don't have any Handshake message_seq and each resend gives a new DTLSRecord + /// sequence number, we might have multiple. + pub fn drop_pending_ccs(&mut self) { + for incoming in self.queue_rx.iter() { + for record in incoming.records().iter() { + if record.record().content_type == ContentType::ChangeCipherSpec { + record.set_handled(); + } + } + } + } + + /// Create a DTLS record and serialize it into a buffer + pub fn create_record( + &mut self, + content_type: ContentType, + epoch: u16, + save_fragment: bool, + f: F, + ) -> Result<(), Error> + where + F: FnOnce(&mut Buf), + { + self.create_record_inner(content_type, epoch, save_fragment, false, f) + } + + fn create_record_inner( + &mut self, + content_type: ContentType, + epoch: u16, + save_fragment: bool, + force_new_datagram: bool, + f: F, + ) -> Result<(), Error> + where + F: FnOnce(&mut Buf), + { + let maybe_suite = if epoch >= 1 { + Some(self.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?) + } else { + None + }; + + // Prepare the plaintext fragment + let mut fragment = self.buffers_free.pop(); + + // Let the caller fill the fragment (plaintext) + f(&mut fragment); + + // Use this as a marker to know whether we are to record fragments for resends. + if save_fragment { + let mut clone = self.buffers_free.pop(); + clone.extend_from_slice(&fragment); + self.flight_saved_records.push(Entry { + content_type, + epoch, + fragment: clone, + }); + } + + // Compute wire length of the record if serialized into a datagram. + // Record header (13) + handshake/change/app data bytes + per-suite + // protection overhead (if epoch >= 1). For AEAD suites the protection + // overhead equals the min-protected-fragment-len. + let overhead = if maybe_suite.is_some() { + self.min_protected_fragment_len() + } else { + 0 + }; + let record_wire_len = DTLSRecord::HEADER_LEN + fragment.len() + overhead; + + // Decide whether to append to the existing last datagram or create a new one + let can_append = self + .queue_tx + .back() + .map(|b| !force_new_datagram && b.len() + record_wire_len <= self.config.mtu()) + .unwrap_or(false); + + // If we cannot append, ensure we have space for a new datagram + if !can_append && self.queue_tx.len() >= self.config.max_queue_tx() { + warn!( + "Transmit queue full (max {}): {:?}", + self.config.max_queue_tx(), + self.queue_tx + ); + return Err(Error::TransmitQueueFull); + } + + // Sequence number to use for this record + let sequence = if epoch == 0 { + self.sequence_epoch_0 + } else { + self.sequence_epoch_n + }; + let length = fragment.len() as u16; + + // Handle encryption for epochs >= 1 + if epoch >= 1 { + let suite = maybe_suite.expect("cipher suite must be set for encrypted epochs"); + + // Get the fixed part of the IV + let iv = if self.is_client { + self.crypto_context.get_client_write_iv() + } else { + self.crypto_context.get_server_write_iv() + }; + + let Some(iv) = iv else { + return Err(Error::CryptoError( + crate::CryptoError::WriteIvNotAvailable { + is_client: self.is_client, + }, + )); + }; + + let explicit_nonce_len = self.explicit_nonce_len; + let mut explicit_nonce = [0u8; DTLSRecord::EXPLICIT_NONCE_LEN]; + let seq64 = ((sequence.epoch as u64) << 48) | sequence.sequence_number; + let nonce = match explicit_nonce_len { + 0 => Nonce::xor(iv.as_12_bytes(), seq64), + DTLSRecord::EXPLICIT_NONCE_LEN => { + explicit_nonce = self.rng.random(); + Nonce::new(iv, &explicit_nonce) + } + _ => { + return Err(Error::CryptoError( + crate::CryptoError::UnsupportedDtls12RecordIvLen { + len: bounded_error_len(explicit_nonce_len), + suite, + }, + )); + } + }; + + // DTLS 1.2 AEAD: AAD uses the plaintext length (DTLSCompressed.length). + let aad = Aad::new_dtls12(content_type, sequence, length); + + // Encrypt the fragment in-place + self.encrypt_data(&mut fragment, aad, nonce)?; + let ctext_len = fragment.len(); + + // For suites with a per-record nonce (e.g. AES-GCM), prefix it on the wire. + if explicit_nonce_len > 0 { + fragment.resize(explicit_nonce_len + ctext_len, 0); + fragment.copy_within(0..ctext_len, explicit_nonce_len); + fragment[..explicit_nonce_len] + .copy_from_slice(&explicit_nonce[..explicit_nonce_len]); + } + } + + // Build the record structure referencing the (possibly encrypted) fragment + let record = DTLSRecord { + content_type, + version: ProtocolVersion::DTLS1_2, + sequence, + length: fragment.len() as u16, + fragment_range: 0..fragment.len(), + }; + + // Increment the sequence number for the next transmission + if epoch == 0 { + self.sequence_epoch_0.sequence_number += 1; + } else { + self.sequence_epoch_n.sequence_number += 1; + } + + // Serialize the record into the chosen datagram buffer + if can_append { + let last = self.queue_tx.back_mut().unwrap(); + record.serialize(&fragment, last); + } else { + let mut buffer = self.buffers_free.pop(); + buffer.clear(); + record.serialize(&fragment, &mut buffer); + self.queue_tx.push_back(buffer); + } + + // Return the fragment buffer to the pool + self.buffers_free.push(fragment); + + Ok(()) + } + + /// Create a handshake message and wrap it in a DTLS record + pub fn create_handshake(&mut self, msg_type: MessageType, f: F) -> Result<(), Error> + where + F: FnOnce(&mut Buf, &mut Self) -> Result<(), Error>, + { + // Get a buffer for the handshake body + let mut body_buffer = self.buffers_free.pop(); + + // Let the callback fill the handshake body + f(&mut body_buffer, self)?; + + // Create the handshake header with the next sequence number + let handshake_header = Header { + msg_type, + length: body_buffer.len() as u32, + message_seq: self.next_handshake_seq_no, + fragment_offset: 0, + fragment_length: body_buffer.len() as u32, + }; + + let mut buffer_full = self.buffers_free.pop(); + { + let handshake = Handshake { + header: handshake_header, + body: Body::Fragment(0..body_buffer.len()), + handled: AtomicBool::new(false), + }; + // Serialize with body_buffer as source + handshake.serialize(&body_buffer, &mut buffer_full); + } + self.transcript.extend_from_slice(&buffer_full); + self.buffers_free.push(buffer_full); + + // Increment the sequence number for the next handshake message + self.next_handshake_seq_no += 1; + + // We want to pack as much as possible into the outgoing datagram and + // remain within the MTU. Fragment the handshake across records as needed. + + let epoch = msg_type.epoch(); + let total_len = body_buffer.len(); + let mut offset: usize = 0; + + // Handshake header is 12 bytes + let handshake_header_len = 12usize; + // Per-record protection overhead on the wire (for AEAD suites this is + // explicit_nonce + tag). Used to size fragments to fit the MTU. + let protection_overhead = if epoch >= 1 { + self.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + self.min_protected_fragment_len() + } else { + 0 + }; + + // At least one record must be created even if total_len == 0 + while offset < total_len || (total_len == 0 && offset == 0) { + // How many bytes are already used in the current datagram (if any)? + let already_used_in_current = self.queue_tx.back().map(|b| b.len()).unwrap_or(0); + let available_in_current = self.config.mtu().saturating_sub(already_used_in_current); + + // Fixed overhead per handshake record on the wire: + // DTLS record header + handshake header + protection overhead (if epoch >= 1) + let fixed_overhead = + DTLSRecord::HEADER_LEN + handshake_header_len + protection_overhead; + + // Prefer to pack into the current datagram. If the current one cannot fit even + // the fixed overhead, we will start a fresh datagram and compute space again. + let available_for_body = if available_in_current > fixed_overhead { + // There is room for at least 1 byte of handshake body in the current datagram + available_in_current - fixed_overhead + } else { + // Not enough space in the current datagram for any body bytes; start a fresh datagram + self.config.mtu().saturating_sub(fixed_overhead) + }; + + // Remaining bytes from the handshake body we still need to send. + let remaining_body_bytes = total_len.saturating_sub(offset); + + // For empty-body handshakes (e.g., ServerHelloDone), we still send a header-only record. + let chunk_len = if total_len == 0 { + 0 + } else { + remaining_body_bytes.min(available_for_body) + }; + + let frag_range = if chunk_len == 0 { + 0..0 + } else { + offset..offset + chunk_len + }; + + let frag_handshake = Handshake { + header: Header { + msg_type, + length: handshake_header.length, + message_seq: handshake_header.message_seq, + fragment_offset: offset as u32, + fragment_length: chunk_len as u32, + }, + body: Body::Fragment(frag_range), + handled: AtomicBool::new(false), + }; + + // Emit the record; packing into current datagram happens inside create_record + self.create_record(ContentType::Handshake, epoch, true, |fragment| { + // Serialize with body_buffer as source + frag_handshake.serialize(&body_buffer, fragment); + })?; + + if total_len == 0 { + // Nothing more to send for empty-body handshake + break; + } + + offset += chunk_len; + } + + // Return the buffer + self.buffers_free.push(body_buffer); + + Ok(()) + } + + /// Release application data from the incoming queue + pub fn release_application_data(&mut self) { + self.release_app_data = true; + } + + /// Whether a close_notify alert has been received from the peer. + pub fn close_notify_received(&self) -> bool { + self.close_notify_received + } + + /// Whether a received close_notify still needs to be surfaced. + pub fn close_notify_pending(&self) -> bool { + self.close_notify_received && !self.close_notify_reported + } + + /// Whether close-related output remains to be polled. + pub fn has_pending_close_output(&self) -> bool { + !self.queue_tx.is_empty() || self.close_notify_pending() + } + + /// Discard all pending outgoing data. + /// + /// RFC 5246 §7.2.1: on receiving close_notify, discard any pending writes. + pub fn discard_pending_writes(&mut self) { + self.queue_tx.clear(); + } + + /// Abort the connection: flush all queued output, retransmission state, and + /// disable timers so that no further packets are emitted. + pub fn abort(&mut self) { + self.queue_tx.clear(); + self.flight_saved_records.clear(); + self.flight_timeout = Timeout::Disabled; + self.connect_timeout = Timeout::Disabled; + } + + /// Pop a buffer from the buffer pool for temporary use + pub(crate) fn pop_buffer(&mut self) -> Buf { + self.buffers_free.pop() + } + + /// Return a buffer to the buffer pool + pub(crate) fn push_buffer(&mut self, buf: Buf) { + self.buffers_free.push(buf); + } + + /// Encrypt data appropriate for the role (client or server) + fn encrypt_data(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), Error> { + if self.is_client { + self.crypto_context + .encrypt_client_to_server(plaintext, aad, nonce) + .map_err(Error::CryptoError) + } else { + self.crypto_context + .encrypt_server_to_client(plaintext, aad, nonce) + .map_err(Error::CryptoError) + } + } + + /// Decrypt data appropriate for the role (client or server) + pub fn decrypt_data( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), Error> { + if self.is_client { + self.crypto_context + .decrypt_server_to_client(ciphertext, aad, nonce) + .map_err(Error::CryptoError) + } else { + self.crypto_context + .decrypt_client_to_server(ciphertext, aad, nonce) + .map_err(Error::CryptoError) + } + } + + /// Reset server handshake state after sending HelloVerifyRequest. + /// + /// Per RFC 6347 §4.2.2, the HelloVerifyRequest exchange is stateless. After sending + /// HVR, the server expects a fresh ClientHello containing the cookie with message_seq=1. + /// + /// The message flow per RFC 6347 §4.2.2: + /// ClientHello (seq=0) ------> + /// <------ HelloVerifyRequest (seq=0) + /// ClientHello (seq=1) ------> (with cookie) + /// <------ ServerHello (seq=1) + pub fn reset_server_for_hello_verify_request(&mut self) { + self.transcript.clear(); + // Per RFC 6347 §4.2.2, the next ClientHello (with cookie) has message_seq=1. + // We keep peer_handshake_seq_no at 1 (already incremented after first ClientHello). + // Clear queued incoming handshakes so the next ClientHello (with cookie) + // isn't rejected as a duplicate of the first ClientHello (without cookie). + self.queue_rx.clear(); + // Note: Don't clear flight_saved_records here - the HelloVerifyRequest should + // still be resendable via timeout until we receive the valid ClientHello with cookie. + // The flight_begin(4) call when processing the cookie-bearing ClientHello will + // clear the old records. + } + + /// Reset client handshake state after receiving HelloVerifyRequest. + /// + /// Per RFC 6347 §4.2.2, the client sends the next ClientHello (with cookie) using + /// message_seq=1. The transcript is cleared because the initial ClientHello and + /// HelloVerifyRequest are not part of the handshake transcript per RFC 6347 §4.2.1. + /// + /// Note: next_handshake_seq_no is already 1 after sending the first ClientHello, + /// so we don't reset it - the next ClientHello will correctly have message_seq=1. + pub fn reset_client_for_hello_verify_request(&mut self) { + self.transcript.clear(); + // Note: next_handshake_seq_no stays at 1 - the next ClientHello (with cookie) + // will have message_seq=1 per RFC 6347 §4.2.2. + // Note: peer_handshake_seq_no stays at 1 - the next message from server + // (ServerHello) will have message_seq=1 per RFC 6347 §4.2.2. + } + + pub fn transcript_hash(&self, algorithm: HashAlgorithm, out: &mut Buf) { + let mut hash = self.crypto_context.create_hash(algorithm); + hash.update(&self.transcript); + hash.clone_and_finalize(out); + } + + pub fn transcript(&self) -> &[u8] { + &self.transcript + } + + pub fn set_cipher_suite(&mut self, cipher_suite: Dtls12CipherSuite) { + // Cache AEAD record parameters from the provider suite. The formula + // (explicit_nonce + tag) lives on the suite trait; Engine just stores + // the resolved values for hot-path access. + let provider_suite = self + .crypto_context + .provider() + .cipher_suites + .iter() + .find(|cs| cs.suite() == cipher_suite) + .expect("cipher suite must be in provider"); + self.explicit_nonce_len = provider_suite.explicit_nonce_len(); + self.min_protected_fragment_len = provider_suite.min_protected_fragment_len(); + self.cipher_suite = Some(cipher_suite); + } + + pub fn enable_peer_encryption(&mut self) -> Result<(), InternalError> { + debug!("Peer encryption enabled"); + self.peer_encryption_enabled = true; + + let maybe_index_epoch1 = self + .queue_rx + .iter() + .position(|i| i.records().iter().any(|r| r.record().sequence.epoch == 1)); + + let Some(index_epoch1) = maybe_index_epoch1 else { + return Ok(()); + }; + + // Now decrypt all entries remaining. + let all = self.queue_rx.split_off(index_epoch1); + + for incoming in all { + let unhandled = incoming.into_records().filter(|r| !r.is_handled()); + + for record in unhandled { + let buf = record.into_buffer(); + self.parse_packet(&buf)?; + self.buffers_free.push(buf); + } + } + + Ok(()) + } + + fn peer_iv(&self) -> Iv { + if self.is_client { + self.crypto_context + .get_server_write_iv() + .expect("Server write IV not available - keys not derived yet") + } else { + self.crypto_context + .get_client_write_iv() + .expect("Client write IV not available - keys not derived yet") + } + } + + pub fn decryption_aad_and_nonce(&self, dtls: &DTLSRecord, buf: &[u8]) -> (Aad, Nonce) { + // DTLS 1.2 AEAD: AAD uses the plaintext length. Recover plaintext length + // from the record header by subtracting this suite's wire overhead. + let plaintext_len = dtls + .length + .saturating_sub(self.min_protected_fragment_len() as u16); + let aad = Aad::new_dtls12(dtls.content_type, dtls.sequence, plaintext_len); + let iv = self.peer_iv(); + let seq64 = ((dtls.sequence.epoch as u64) << 48) | dtls.sequence.sequence_number; + let nonce = match self.explicit_nonce_len { + 0 => Nonce::xor(iv.as_12_bytes(), seq64), + DTLSRecord::EXPLICIT_NONCE_LEN => Nonce::new(iv, dtls.nonce(buf)), + len => Nonce::new(iv, dtls.nonce_with_len(buf, len)), + }; + (aad, nonce) + } + + pub fn generate_verify_data(&mut self, is_client: bool) -> Result<[u8; 12], Error> { + let Some(suite) = self.cipher_suite() else { + return Err(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + )); + }; + let algorithm = suite.hash_algorithm(); + let mut handshake_hash = self.buffers_free.pop(); + self.transcript_hash(algorithm, &mut handshake_hash); + + let suite_hash = suite.hash_algorithm(); + let mut out = self.buffers_free.pop(); + let mut scratch = self.buffers_free.pop(); + let verify_data_vec = self + .crypto_context() + .generate_verify_data( + &handshake_hash, + is_client, + suite_hash, + &mut out, + &mut scratch, + ) + .map_err(Error::CryptoError)?; + + if verify_data_vec.len() != 12 { + return Err(Error::CryptoError( + crate::CryptoError::InvalidVerifyDataLength, + )); + } + + let mut verify_data = [0u8; 12]; + verify_data.copy_from_slice(&verify_data_vec); + + self.buffers_free.push(handshake_hash); + self.buffers_free.push(out); + self.buffers_free.push(scratch); + + Ok(verify_data) + } +} + +impl RecordHandler for Engine { + fn classify_record(&mut self, record: Record) -> Result, Error> { + let epoch = record.record().sequence.epoch; + + if record.record().content_type == ContentType::ChangeCipherSpec + && epoch == 0 + && self.peer_encryption_enabled + { + // DTLS 1.2 peers may retransmit their last handshake flight after + // we have already enabled peer encryption. A late plaintext CCS is + // no longer actionable; queuing it would leave an unhandled control + // record in queue_rx and prevent handled app-data records behind it + // from being purged. + self.push_buffer(record.into_buffer()); + return Ok(None); + } + + if record.record().content_type == ContentType::Handshake + && epoch == 0 + && self.peer_encryption_enabled + && record + .first_handshake() + .and_then(|handshake| handshake.dupe_triggers_resend()) + .is_none() + { + // Stale plaintext handshakes must still be visible to + // insert_incoming_handshake when they can trigger final-flight + // retransmission. Other post-encryption epoch-0 handshakes are + // unauthenticated and no longer actionable. + self.push_buffer(record.into_buffer()); + return Ok(None); + } + + if record.record().content_type == ContentType::Alert { + if epoch == 0 { + if self.peer_encryption_enabled { + // Post-handshake: epoch 0 alerts are unauthenticated, discard. + self.push_buffer(record.into_buffer()); + return Ok(None); + } + + let fatal_description = { + let fragment = record.record().fragment(record.buffer()); + (fragment.len() >= 2 && fragment[0] == 2).then(|| fragment[1]) + }; + self.push_buffer(record.into_buffer()); + + if let Some(description) = fatal_description { + return Err(Error::SecurityError(crate::SecurityError::FatalAlert { + description, + })); + } + + return Ok(None); + } + + if !self.peer_encryption_enabled { + // Epoch >= 1 before peer encryption is enabled must stay queued + // for re-parsing after enable_peer_encryption(). + return Ok(Some(record)); + } + + let alert = { + let fragment = record.record().fragment(record.buffer()); + (fragment.len() >= 2).then(|| (fragment[0], fragment[1])) + }; + self.push_buffer(record.into_buffer()); + + if let Some((level, description)) = alert { + if description == 0 { + self.close_notify_received = true; + return Ok(None); + } + + if level == 2 { + return Err(Error::SecurityError(crate::SecurityError::FatalAlert { + description, + })); + } + } + + return Ok(None); + } + + if self.close_notify_received + && record.record().content_type == ContentType::ApplicationData + { + self.push_buffer(record.into_buffer()); + return Ok(None); + } + + Ok(Some(record)) + } + + fn is_peer_encryption_enabled(&self) -> bool { + self.peer_encryption_enabled + } + + fn replay_check(&self, seq: Sequence) -> bool { + // Only epoch 1 (encrypted) records reach here; epoch 0 records are + // returned early by the DTLS 1.2 incoming parser. + self.replay.check(seq.sequence_number) + } + + fn replay_update(&mut self, seq: Sequence) { + self.replay.update(seq.sequence_number); + } + + fn note_decrypted_record(&mut self, content_type: ContentType) { + // A decrypted (so authenticated) application-data record proves the peer + // is past its handshake, which means it received our final flight. Once + // that's known, a stale plaintext handshake (unauthenticated, replayable) + // must no longer drive a courtesy flight retransmission. The client + // confirms separately at its own completion (flight_stop_resend_timers). + if content_type == ContentType::ApplicationData { + self.peer_handshake_confirmed = true; + } + } + + fn decryption_aad_and_nonce(&self, dtls: &DTLSRecord, buf: &[u8]) -> (Aad, Nonce) { + Engine::decryption_aad_and_nonce(self, dtls, buf) + } + + fn explicit_nonce_len(&self) -> usize { + self.explicit_nonce_len + } + + fn min_protected_fragment_len(&self) -> usize { + self.min_protected_fragment_len + } + + fn decrypt_data( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), Error> { + Engine::decrypt_data(self, ciphertext, aad, nonce) + } + + fn can_discard_bad_protected_record(&self) -> bool { + self.release_app_data + } +} diff --git a/third_party/dimpl/src/dtls12/incoming.rs b/third_party/dimpl/src/dtls12/incoming.rs new file mode 100644 index 0000000..1083af4 --- /dev/null +++ b/third_party/dimpl/src/dtls12/incoming.rs @@ -0,0 +1,485 @@ +use std::ops::Deref; +use std::sync::atomic::{AtomicBool, Ordering}; + +use arrayvec::ArrayVec; +use std::fmt; + +use crate::buffer::{Buf, TmpBuf}; +use crate::crypto::{Aad, Nonce}; +use crate::dtls12::message::{ContentType, DTLSRecord, Dtls12CipherSuite, Handshake, Sequence}; +use crate::{Error, InternalError}; + +/// Holds both the UDP packet and the parsed result of that packet. +pub struct Incoming { + // Box is here to reduce the size of the Incoming struct + // to be passed in register instead of using memmove. + records: Box, +} + +impl Incoming { + pub fn records(&self) -> &Records { + &self.records + } + + pub fn first(&self) -> &Record { + // Invariant: Every Incoming must have at least one Record + // or the parser of Incoming returns None. + &self.records()[0] + } + + pub fn into_records(self) -> impl Iterator { + self.records.records.into_iter() + } +} + +impl Incoming { + /// Parse an incoming UDP packet + /// + /// * `packet` is the data from the UDP socket. + /// * `decrypt` provides the decryption operations for encrypted records. + /// * `cs` is the negotiated cipher suite, if any. + /// + /// Will surface parser errors. + pub fn parse_packet( + packet: &[u8], + decrypt: &mut dyn RecordHandler, + cs: Option, + ) -> Result, InternalError> { + // Parse records directly from packet, copying each record ONCE into its own buffer + let records = Records::parse(packet, decrypt, cs)?; + + // We need at least one Record to be valid. For replayed frames, we discard + // the records, hence this might be None + if records.records.is_empty() { + return Ok(None); + } + + let records = Box::new(records); + + Ok(Some(Incoming { records })) + } +} + +/// A number of records parsed from a single UDP packet. +#[derive(Debug)] +pub struct Records { + pub records: ArrayVec, +} + +impl Records { + pub fn parse( + mut packet: &[u8], + decrypt: &mut dyn RecordHandler, + cs: Option, + ) -> Result { + let mut parsed_records: ArrayVec = ArrayVec::new(); + + // Find record boundaries and copy each record ONCE from the packet + while !packet.is_empty() { + if packet.len() < DTLSRecord::HEADER_LEN { + return Err(InternalError::parse_incomplete()); + } + + let length_bytes: [u8; 2] = packet[DTLSRecord::LENGTH_OFFSET].try_into().unwrap(); + let length = u16::from_be_bytes(length_bytes) as usize; + let record_end = DTLSRecord::HEADER_LEN + length; + + if packet.len() < record_end { + return Err(InternalError::parse_incomplete()); + } + + // This is the ONLY copy: packet -> record buffer + let record_slice = &packet[..record_end]; + let record = Record::parse(record_slice, decrypt, cs)?; + if let Some(record) = record { + if parsed_records.try_push(record).is_err() { + return Err(InternalError::too_many_records()); + } + } else { + trace!("Discarding replayed rec"); + } + + packet = &packet[record_end..]; + } + + let mut records = ArrayVec::new(); + for record in parsed_records { + if let Some(record) = decrypt.classify_record(record)? { + records + .try_push(record) + .expect("filtered records cannot exceed parsed records"); + } + } + + Ok(Records { records }) + } +} + +impl Deref for Records { + type Target = [Record]; + + fn deref(&self) -> &Self::Target { + &self.records + } +} + +pub struct Record { + buffer: Buf, + // Box is here to reduce the size of the Record struct + // to be passed in register instead of using memmove. + parsed: Box, +} + +impl Record { + /// The first parse pass only parses the DTLSRecord header which is unencrypted. + /// Copies record data from UDP packet ONCE into a pooled buffer. + pub fn parse( + record_slice: &[u8], + decrypt: &mut dyn RecordHandler, + cs: Option, + ) -> Result, InternalError> { + // ONLY COPY: UDP packet slice -> pooled buffer + let mut buffer = Buf::new(); + buffer.extend_from_slice(record_slice); + let parsed = match ParsedRecord::parse(&buffer, cs, 0) { + Ok(p) => p, + Err(e) => { + // RFC 6347 §4.1.2.7: Invalid records SHOULD be silently discarded. + // This includes epoch 0 records with invalid ContentType. + trace!("Discarding record: parse failed: {}", e); + return Ok(None); + } + }; + let parsed = Box::new(parsed); + let record = Record { buffer, parsed }; + + // It is not enough to only look at the epoch, since to be able to decrypt the entire + // preceeding set of flights sets up the cryptographic context. In a situation with + // packet loss, we can end up seeing epoch 1 records before we can decrypt them. + let is_epoch_0 = record.record().sequence.epoch == 0; + if is_epoch_0 || !decrypt.is_peer_encryption_enabled() { + return Ok(Some(record)); + } + + // We need to decrypt the record and redo the parsing. + let dtls = record.record(); + let sequence = dtls.sequence; + let content_type = dtls.content_type; + + // Anti-replay check (read-only, does not update window) + if !decrypt.replay_check(sequence) { + return Ok(None); + } + + let explicit_nonce_len = decrypt.explicit_nonce_len(); + if (dtls.length as usize) < decrypt.min_protected_fragment_len() { + return Ok(None); + } + + // Get a reference to the buffer + let (aad, nonce) = decrypt.decryption_aad_and_nonce(dtls, &record.buffer); + + // Extract the buffer for decryption + let mut buffer = record.buffer; + + // Local shorthand for where the encrypted ciphertext starts + let ciph = DTLSRecord::HEADER_LEN + explicit_nonce_len; + + // The encrypted part is after the DTLS header and optional explicit nonce. + // The entire buffer is only the single record, since we chunk + // records up in Records::parse() + let ciphertext = &mut buffer[ciph..]; + + let new_len = { + let mut buffer = TmpBuf::new(ciphertext); + + // This decrypts in place. + if let Err(e) = decrypt.decrypt_data(&mut buffer, aad, nonce) { + if !decrypt.can_discard_bad_protected_record() { + return Err(e.into()); + } + + trace!("Discarding record: decrypt failed: {}", e); + return Ok(None); + } + + buffer.len() + }; + + // Decryption succeeded — now commit the replay window update. + // RFC 6347 §4.1.2.6: "The receive window is updated only if the + // MAC verification succeeds." + decrypt.replay_update(sequence); + + // The record is now authenticated. Tell the handler so it can act on a + // confirmed-genuine record (e.g. mark the peer past its handshake). + decrypt.note_decrypted_record(content_type); + + // Update the length of the record. + buffer[11] = (new_len >> 8) as u8; + buffer[12] = new_len as u8; + + let parsed = ParsedRecord::parse(&buffer, cs, explicit_nonce_len)?; + let parsed = Box::new(parsed); + + Ok(Some(Record { buffer, parsed })) + } + + pub fn record(&self) -> &DTLSRecord { + &self.parsed.record + } + + pub fn handshakes(&self) -> &[Handshake] { + &self.parsed.handshakes + } + + pub fn first_handshake(&self) -> Option<&Handshake> { + self.parsed.handshakes.first() + } + + pub fn is_handled(&self) -> bool { + if self.parsed.handshakes.is_empty() { + self.parsed.handled.load(Ordering::Relaxed) + } else { + self.parsed.handshakes.iter().all(|h| h.is_handled()) + } + } + + pub fn set_handled(&self) { + // Handshakes should be empty because we set_handled() on them individually + // during defragmentation. set_handled() on the record is only for non-handshakes. + assert!(self.parsed.handshakes.is_empty()); + self.parsed.handled.store(true, Ordering::Relaxed); + } + + pub fn buffer(&self) -> &[u8] { + &self.buffer + } + + pub(crate) fn into_buffer(self) -> Buf { + self.buffer + } +} + +pub struct ParsedRecord { + record: DTLSRecord, + handshakes: ArrayVec, + handled: AtomicBool, +} + +impl ParsedRecord { + pub fn parse( + input: &[u8], + cipher_suite: Option, + offset: usize, + ) -> Result { + let (_, record) = DTLSRecord::parse(input, 0, offset)?; + + let handshakes = if record.content_type == ContentType::Handshake { + // This will also return None on the encrypted Finished after ChangeCipherSpec. + // However we will then decrypt and try again. + let fragment_offset = record.fragment_range.start; + parse_handshakes(record.fragment(input), fragment_offset, cipher_suite) + } else { + ArrayVec::new() + }; + + Ok(ParsedRecord { + record, + handshakes, + handled: AtomicBool::new(false), + }) + } +} + +/// Trait abstracting record parsing-time handling for incoming records. +/// +/// This decouples the record parser from the full `Engine`, allowing the parse loop +/// to decrypt records, classify control records, and queue only the records that +/// should survive into `Incoming`. +pub trait RecordHandler { + fn classify_record(&mut self, record: Record) -> Result, Error>; + fn is_peer_encryption_enabled(&self) -> bool; + fn replay_check(&self, seq: Sequence) -> bool; + fn replay_update(&mut self, seq: Sequence); + fn decryption_aad_and_nonce(&self, dtls: &DTLSRecord, buf: &[u8]) -> (Aad, Nonce); + fn explicit_nonce_len(&self) -> usize; + fn min_protected_fragment_len(&self) -> usize; + fn decrypt_data( + &mut self, + ciphertext: &mut TmpBuf, + aad: Aad, + nonce: Nonce, + ) -> Result<(), Error>; + + fn can_discard_bad_protected_record(&self) -> bool { + false + } + + /// Called once a record has been successfully decrypted, i.e. authenticated. + /// Lets the handler react to a confirmed-genuine record (e.g. note that the + /// peer is past its handshake). The default does nothing. + fn note_decrypted_record(&mut self, _content_type: ContentType) {} +} + +fn parse_handshakes( + mut input: &[u8], + mut base_offset: usize, + cipher_suite: Option, +) -> ArrayVec { + let mut handshakes = ArrayVec::new(); + while !input.is_empty() { + if let Ok((remaining, handshake)) = Handshake::parse(input, base_offset, cipher_suite, true) + { + let len = input.len() - remaining.len(); + base_offset += len; + input = remaining; + if handshakes.try_push(handshake).is_err() { + break; + } + } else { + break; + } + } + handshakes +} + +impl fmt::Debug for Incoming { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Incoming") + .field("records", &self.records()) + .finish() + } +} + +impl fmt::Debug for Record { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Record") + .field("record", &self.parsed.record) + .field("handshakes", &self.parsed.handshakes) + .finish() + } +} + +/* +Why it is sound to assert UnwindSafe for Incoming + +- No internal unwind boundaries: this crate does not use catch_unwind. We do not + cross panic boundaries internally while mutating state. This marker exists to + document that external callers can wrap our APIs in catch_unwind without + observing broken invariants from this type. + +- Read-only builders: our dependent builders (e.g., ParsedRecord::parse) take + only a &[u8] to the buffer and do not mutate the buffer during construction. + An unwind during builder execution therefore cannot leave the buffer partially + mutated across a boundary. + +- Decrypt-and-reparse is publish-after-complete: when decrypting we first extract + the buffer, mutate it (length update, in-place decrypt), and only then construct + a fresh Record from the fully transformed bytes. If a panic occurs mid-transformation, + the new Record is not built and the previously-built Record is dropped; no + consumer can observe a half-transformed record across an unwind boundary. + +- Interior mutability is benign across unwind: the only interior mutability is + AtomicBool "handled" flags. They are monotonic (false -> true). If an external + caller catches a panic and continues, the worst effect is conservatively + skipping work already done. This does not introduce memory unsafety or aliasing + violations, and no invariants rely on "handled implies delivery". + +Given the above, an unwind cannot leave Incoming in a state where broken +invariants are later observed across a catch_unwind boundary. Marking Incoming +as UnwindSafe is a sound assertion and clarifies behavior for callers. +*/ +impl std::panic::UnwindSafe for Incoming {} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct TestHandler { + classify_calls: usize, + dropped_alerts: usize, + } + + impl RecordHandler for TestHandler { + fn classify_record(&mut self, record: Record) -> Result, Error> { + self.classify_calls += 1; + if record.record().content_type == ContentType::Alert { + self.dropped_alerts += 1; + return Ok(None); + } + Ok(Some(record)) + } + + fn is_peer_encryption_enabled(&self) -> bool { + false + } + + fn replay_check(&self, _seq: Sequence) -> bool { + panic!("replay_check should not be called for plaintext tests"); + } + + fn replay_update(&mut self, _seq: Sequence) { + panic!("replay_update should not be called for plaintext tests"); + } + + fn decryption_aad_and_nonce(&self, _dtls: &DTLSRecord, _buf: &[u8]) -> (Aad, Nonce) { + panic!("decryption_aad_and_nonce should not be called for plaintext tests"); + } + + fn explicit_nonce_len(&self) -> usize { + panic!("explicit_nonce_len should not be called for plaintext tests"); + } + + fn min_protected_fragment_len(&self) -> usize { + panic!("min_protected_fragment_len should not be called for plaintext tests"); + } + + fn decrypt_data( + &mut self, + _ciphertext: &mut TmpBuf, + _aad: Aad, + _nonce: Nonce, + ) -> Result<(), Error> { + panic!("decrypt_data should not be called for plaintext tests"); + } + } + + fn build_record(content_type: ContentType, epoch: u16, seq: u64, fragment: &[u8]) -> Vec { + let mut out = Vec::new(); + out.push(content_type.as_u8()); + out.extend_from_slice(&[0xFE, 0xFD]); + out.extend_from_slice(&epoch.to_be_bytes()); + out.extend_from_slice(&seq.to_be_bytes()[2..]); + out.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); + out.extend_from_slice(fragment); + out + } + + #[test] + fn parse_packet_filters_control_records_after_packet_validation() { + let mut packet = Vec::new(); + packet.extend_from_slice(&build_record(ContentType::Alert, 0, 1, &[0x01, 0x00])); + packet.extend_from_slice(&build_record( + ContentType::ApplicationData, + 1, + 2, + &[0xAA, 0xBB], + )); + + let mut handler = TestHandler::default(); + let incoming = Incoming::parse_packet(&packet, &mut handler, None) + .unwrap() + .expect("application data record should remain"); + + assert_eq!(handler.classify_calls, 2); + assert_eq!(handler.dropped_alerts, 1); + assert_eq!(incoming.records().len(), 1); + assert_eq!( + incoming.first().record().content_type, + ContentType::ApplicationData + ); + assert_eq!(incoming.first().record().sequence.epoch, 1); + } +} diff --git a/third_party/dimpl/src/dtls12/message/certificate.rs b/third_party/dimpl/src/dtls12/message/certificate.rs new file mode 100644 index 0000000..cce1233 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/certificate.rs @@ -0,0 +1,104 @@ +use super::Asn1Cert; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::{IResult, number::complete::be_u24}; + +#[derive(Debug, PartialEq, Eq)] +pub struct Certificate { + pub certificate_list: ArrayVec, +} + +impl Certificate { + pub fn new(certificate_list: ArrayVec) -> Self { + Certificate { certificate_list } + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Certificate> { + let original_input = input; + let (input, total_len) = be_u24(input)?; + let (input, certs_data) = take(total_len)(input)?; + + // Calculate base offset for certs_data within the root buffer + let certs_base_offset = + base_offset + (certs_data.as_ptr() as usize - original_input.as_ptr() as usize); + + // Parse certificates manually with dynamic base_offset + let mut certificate_list = ArrayVec::new(); + let mut rest = certs_data; + while !rest.is_empty() { + let offset = + certs_base_offset + (rest.as_ptr() as usize - certs_data.as_ptr() as usize); + let (new_rest, cert) = Asn1Cert::parse(rest, offset)?; + certificate_list + .try_push(cert) + .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; + rest = new_rest; + } + + Ok((input, Certificate { certificate_list })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + let total_len: usize = self + .certificate_list + .iter() + .map(|cert| 3 + cert.as_slice(buf).len()) + .sum(); + output.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]); + + for cert in &self.certificate_list { + let cert_data = cert.as_slice(buf); + output.extend_from_slice(&(cert_data.len() as u32).to_be_bytes()[1..]); + output.extend_from_slice(cert_data); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x00, 0x00, 0x0C, // Total length + 0x00, 0x00, 0x04, // Certificate 1 length + 0x01, 0x02, 0x03, 0x04, // Certificate 1 data + 0x00, 0x00, 0x02, // Certificate 2 length + 0x05, 0x06, // Certificate 2 data + ]; + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = Certificate::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } + + #[test] + fn rejects_too_many_certificates() { + let mut message = Vec::new(); + let total_len = 33 * 4; + message.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]); + for _ in 0..33 { + message.extend_from_slice(&[0x00, 0x00, 0x01, 0xAA]); + } + + let result = Certificate::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "oversized certificate list should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls12/message/certificate_request.rs b/third_party/dimpl/src/dtls12/message/certificate_request.rs new file mode 100644 index 0000000..6391d2c --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/certificate_request.rs @@ -0,0 +1,228 @@ +use super::{CertificateTypeVec, ClientCertificateType, DistinguishedName}; +use super::{SignatureAndHashAlgorithm, SignatureAndHashAlgorithmVec}; +use crate::buffer::Buf; +use crate::util::{many0, many1}; +use arrayvec::ArrayVec; +use nom::Err; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u8, be_u16}; +use nom::{IResult, bytes::complete::take}; + +#[derive(Debug, PartialEq, Eq)] +pub struct CertificateRequest { + pub certificate_types: CertificateTypeVec, + pub supported_signature_algorithms: SignatureAndHashAlgorithmVec, + pub certificate_authorities: ArrayVec, +} + +impl CertificateRequest { + pub fn new( + certificate_types: CertificateTypeVec, + supported_signature_algorithms: SignatureAndHashAlgorithmVec, + certificate_authorities: ArrayVec, + ) -> Self { + CertificateRequest { + certificate_types, + supported_signature_algorithms, + certificate_authorities, + } + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateRequest> { + let original_input = input; + let (input, cert_types_len) = be_u8(input)?; + let (input, input_type) = take(cert_types_len)(input)?; + let (rest, certificate_types) = many1( + ClientCertificateType::parse, + ClientCertificateType::is_supported, + )(input_type)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + + let (input, sig_algs_len) = be_u16(input)?; + let (input, input_sigs) = take(sig_algs_len)(input)?; + let (rest, supported_signature_algorithms) = many0( + SignatureAndHashAlgorithm::parse, + SignatureAndHashAlgorithm::is_supported, + )(input_sigs)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + + let (input, cert_auths_len) = be_u16(input)?; + let (input, input_auths) = take(cert_auths_len)(input)?; + + // Calculate base offset for input_auths within the root buffer + let auths_base_offset = + base_offset + (input_auths.as_ptr() as usize - original_input.as_ptr() as usize); + + // Parse certificate authorities manually with dynamic base_offset + let mut certificate_authorities = ArrayVec::new(); + let mut rest = input_auths; + while !rest.is_empty() { + let offset = + auths_base_offset + (rest.as_ptr() as usize - input_auths.as_ptr() as usize); + let (new_rest, auth) = DistinguishedName::parse(rest, offset)?; + certificate_authorities + .try_push(auth) + .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; + rest = new_rest; + } + + Ok(( + input, + CertificateRequest { + certificate_types, + supported_signature_algorithms, + certificate_authorities, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.push(self.certificate_types.len() as u8); + for cert_type in &self.certificate_types { + output.push(cert_type.as_u8()); + } + + let sig_algs_len = (self.supported_signature_algorithms.len() * 2) as u16; + output.extend_from_slice(&sig_algs_len.to_be_bytes()); + for sig_alg in &self.supported_signature_algorithms { + output.extend_from_slice(&sig_alg.as_u16().to_be_bytes()); + } + + let cert_auths_len: usize = self + .certificate_authorities + .iter() + .map(|name| 2 + name.as_slice(buf).len()) + .sum(); + output.extend_from_slice(&(cert_auths_len as u16).to_be_bytes()); + for name in &self.certificate_authorities { + let name_data = name.as_slice(buf); + output.extend_from_slice(&(name_data.len() as u16).to_be_bytes()); + output.extend_from_slice(name_data); + } + } + + /// Checks if the CertificateRequest supports a specific hash algorithm + pub fn supports_hash_algorithm(&self, hash_algorithm: super::HashAlgorithm) -> bool { + self.supported_signature_algorithms + .iter() + .any(|algo| algo.hash == hash_algorithm) + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + // Test message with recognized values: + // - Certificate type: 0x40 (ECDSA_SIGN) + // - Signature algorithms: SHA256/ECDSA (0x04, 0x03), SHA256/RSA (0x04, 0x01) + const MESSAGE: &[u8] = &[ + 0x01, // Certificate types length (1 byte) + 0x40, // Certificate type: ECDSA_SIGN + 0x00, 0x04, // Signature algorithms length (4 bytes = 2 algorithms) + 0x04, 0x03, // SHA256/ECDSA + 0x04, 0x01, // SHA256/RSA + 0x00, 0x0C, // Certificate authorities length + 0x00, 0x04, // Distinguished name 1 length + 0x01, 0x02, 0x03, 0x04, // Distinguished name 1 data + 0x00, 0x04, // Distinguished name 2 length + 0x05, 0x06, 0x07, 0x08, // Distinguished name 2 data + ]; + + #[test] + fn filters_unsupported_rsa_signature_algorithm() { + // Parse the message with base_offset 0 + let (rest, parsed) = CertificateRequest::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + assert_eq!(parsed.supported_signature_algorithms.len(), 1); + assert_eq!( + parsed.supported_signature_algorithms[0], + SignatureAndHashAlgorithm::new( + super::super::HashAlgorithm::SHA256, + super::super::SignatureAlgorithm::ECDSA, + ) + ); + + // Serialization must not re-advertise the filtered RSA algorithm. + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + let expected = [ + 0x01, // Certificate types length (1 byte) + 0x40, // Certificate type: ECDSA_SIGN + 0x00, 0x02, // Signature algorithms length (2 bytes = 1 algorithm) + 0x04, 0x03, // SHA256/ECDSA + 0x00, 0x0C, // Certificate authorities length + 0x00, 0x04, // Distinguished name 1 length + 0x01, 0x02, 0x03, 0x04, // Distinguished name 1 data + 0x00, 0x04, // Distinguished name 2 length + 0x05, 0x06, 0x07, 0x08, // Distinguished name 2 data + ]; + assert_eq!(&*serialized, expected); + } + + #[test] + fn filters_unsupported_types() { + // Message with unsupported certificate types and signature algorithms + let message_with_unsupported: &[u8] = &[ + 0x03, // Certificate types length (3 bytes) + 0x01, // RSA_SIGN (unsupported, filtered) + 0x40, // ECDSA_SIGN (supported) + 0x02, // DSS_SIGN (unsupported, filtered) + 0x00, 0x06, // Signature algorithms length (6 bytes = 3 algorithms) + 0x05, 0x02, // SHA384/DSA (unsupported) + 0x04, 0x03, // SHA256/ECDSA (supported) + 0x01, 0x01, // MD5/RSA (unsupported) + 0x00, 0x00, // Certificate authorities length (0) + ]; + + let (rest, parsed) = CertificateRequest::parse(message_with_unsupported, 0).unwrap(); + assert!(rest.is_empty()); + + // Only supported types should remain + assert_eq!(parsed.certificate_types.len(), 1); + assert_eq!( + parsed.certificate_types[0], + ClientCertificateType::ECDSA_SIGN + ); + + assert_eq!(parsed.supported_signature_algorithms.len(), 1); + assert_eq!( + parsed.supported_signature_algorithms[0], + SignatureAndHashAlgorithm::new( + super::super::HashAlgorithm::SHA256, + super::super::SignatureAlgorithm::ECDSA + ) + ); + } + + #[test] + fn too_many_certificate_authorities_are_rejected() { + let mut message = Vec::new(); + message.push(1); // Certificate types length + message.push(ClientCertificateType::ECDSA_SIGN.as_u8()); + message.extend_from_slice(&0u16.to_be_bytes()); // Signature algorithms length + + let count = 33; + let cert_auths_len = count * 3; + message.extend_from_slice(&(cert_auths_len as u16).to_be_bytes()); + for _ in 0..count { + message.extend_from_slice(&1u16.to_be_bytes()); + message.push(0xAA); + } + + let result = CertificateRequest::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many certificate authorities should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls12/message/certificate_verify.rs b/third_party/dimpl/src/dtls12/message/certificate_verify.rs new file mode 100644 index 0000000..fd13984 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/certificate_verify.rs @@ -0,0 +1,43 @@ +use super::DigitallySigned; +use crate::buffer::Buf; +use nom::IResult; + +#[derive(Debug, PartialEq, Eq)] +pub struct CertificateVerify { + pub signed: DigitallySigned, +} + +impl CertificateVerify { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateVerify> { + let (input, signed) = DigitallySigned::parse(input, base_offset)?; + Ok((input, CertificateVerify { signed })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + self.signed.serialize(buf, output); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x04, 0x01, // SignatureAndHashAlgorithm (SHA256 + RSA) + 0x00, 0x04, // Signature length + 0x01, 0x02, 0x03, 0x04, // Signature data + ]; + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = CertificateVerify::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } +} diff --git a/third_party/dimpl/src/dtls12/message/client_hello.rs b/third_party/dimpl/src/dtls12/message/client_hello.rs new file mode 100644 index 0000000..2747a1f --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/client_hello.rs @@ -0,0 +1,352 @@ +use super::extensions::{ECPointFormatsExtension, SignatureAlgorithmsExtension}; +use super::extensions::{SupportedGroupsExtension, UseSrtpExtension}; +use super::{CipherSuiteVec, CompressionMethod, CompressionMethodVec, Dtls12CipherSuite}; +use super::{Cookie, Extension, ExtensionType, ProtocolVersion, Random, SessionId}; +use arrayvec::ArrayVec; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u8, be_u16}; +use nom::{Err, IResult}; + +use super::extension::ExtensionVec; +use crate::Config; +use crate::buffer::Buf; +use crate::util::many1; + +#[derive(Debug, PartialEq, Eq)] +pub struct ClientHello { + pub client_version: ProtocolVersion, + pub random: Random, + pub session_id: SessionId, + pub cookie: Cookie, + pub cipher_suites: CipherSuiteVec, + pub compression_methods: CompressionMethodVec, + pub extensions: ExtensionVec, +} + +impl ClientHello { + pub fn new( + client_version: ProtocolVersion, + random: Random, + session_id: SessionId, + cookie: Cookie, + cipher_suites: CipherSuiteVec, + compression_methods: CompressionMethodVec, + ) -> Self { + ClientHello { + client_version, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + extensions: ArrayVec::new(), + } + } + + /// Add all required extensions for DTLS handshake + pub fn with_extensions(mut self, buf: &mut Buf, config: &Config) -> Self { + // Clear the extension data buffer + buf.clear(); + + // First write all extension data + let mut ranges = ArrayVec::<(ExtensionType, usize, usize), 8>::new(); + + // Check if provider has ECDH support + let has_ecdh = config.crypto_provider().has_ecdh(); + + // Add supported groups and EC point formats if using ECDH + if has_ecdh { + // Add supported groups extension from config + let mut groups = super::NamedGroupVec::new(); + for kx_group in config.kx_groups() { + groups.push(kx_group.name()); + } + let supported_groups = SupportedGroupsExtension { groups }; + let start_pos = buf.len(); + supported_groups.serialize(buf); + ranges.push((ExtensionType::SupportedGroups, start_pos, buf.len())); + + // Add EC point formats extension + let ec_point_formats = ECPointFormatsExtension::default(); + let start_pos = buf.len(); + ec_point_formats.serialize(buf); + ranges.push((ExtensionType::EcPointFormats, start_pos, buf.len())); + } + + // Add signature algorithms extension (required for TLS 1.2+) + let signature_algorithms = SignatureAlgorithmsExtension::default(); + let start_pos = buf.len(); + signature_algorithms.serialize(buf); + ranges.push((ExtensionType::SignatureAlgorithms, start_pos, buf.len())); + + // Add use_srtp extension for DTLS-SRTP support + let use_srtp = UseSrtpExtension::default(); + let start_pos = buf.len(); + use_srtp.serialize(buf); + ranges.push((ExtensionType::UseSrtp, start_pos, buf.len())); + + // // Add session_ticket extension (empty) + // let start_pos = buf.len(); + // buf.extend_from_slice(&[0x00]); // Empty extension data + // ranges.push((ExtensionType::SessionTicket, start_pos, buf.len())); + + let need_etm = self + .cipher_suites + .iter() + .any(|suite| suite.need_encrypt_then_mac()); + if need_etm { + // Add encrypt_then_mac extension (empty) + let start_pos = buf.len(); + buf.extend_from_slice(&[0x00]); // Empty extension data + ranges.push((ExtensionType::EncryptThenMac, start_pos, buf.len())); + } + + let start_pos = buf.len(); + ranges.push(( + ExtensionType::ExtendedMasterSecret, + start_pos, + start_pos, // No data at all + )); + + // Now create all extensions using ranges + for (extension_type, start, end) in ranges { + self.extensions.push(Extension { + extension_type, + extension_data_range: start..end, + }); + } + + self + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientHello> { + let original_input = input; + let (input, client_version) = ProtocolVersion::parse(input)?; + let (input, random) = Random::parse(input)?; + let (input, session_id) = SessionId::parse(input)?; + let (input, cookie) = Cookie::parse(input)?; + let (input, cipher_suites_len) = be_u16(input)?; + let (input, input_cipher) = take(cipher_suites_len)(input)?; + let (rest, cipher_suites) = + many1(Dtls12CipherSuite::parse, Dtls12CipherSuite::is_supported)(input_cipher)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + let (input, compression_methods_len) = be_u8(input)?; + let (input, input_compression) = take(compression_methods_len)(input)?; + let (rest, compression_methods) = + many1(CompressionMethod::parse, CompressionMethod::is_supported)(input_compression)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + + // Calculate base_offset for extensions parsing + let consumed = input.as_ptr() as usize - original_input.as_ptr() as usize; + let extensions_base_offset = base_offset + consumed; + + // Parse extensions if there are any left + let (remaining_input, extensions) = Self::parse_extensions(input, extensions_base_offset)?; + + Ok(( + remaining_input, + ClientHello { + client_version, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + extensions, + }, + )) + } + + /// Parse extensions from the input, filtering to only known extension types + fn parse_extensions(input: &[u8], base_offset: usize) -> IResult<&[u8], ExtensionVec> { + let mut extensions = ArrayVec::new(); + + // Early return if input is empty + if input.is_empty() { + return Ok((input, extensions)); + } + + let original_input = input; + + // Parse extensions length + let (remaining, extensions_len) = be_u16(input)?; + + // Early return if extensions length is 0 + if extensions_len == 0 { + return Ok((remaining, extensions)); + } + + // Take the extensions data + let (remaining, extensions_data) = take(extensions_len)(remaining)?; + + // Calculate base_offset for extension data + let consumed = extensions_data.as_ptr() as usize - original_input.as_ptr() as usize; + let data_base_offset = base_offset + consumed; + + // Parse individual extensions, filtering to only known types + let mut extensions_rest = extensions_data; + let mut current_offset = data_base_offset; + while !extensions_rest.is_empty() { + let before_len = extensions_rest.len(); + let (rest, extension) = Extension::parse(extensions_rest, current_offset)?; + let parsed_len = before_len - rest.len(); + current_offset += parsed_len; + + // Only keep supported extension types + if extension.extension_type.is_supported() { + if extensions + .iter() + .any(|existing| existing.extension_type == extension.extension_type) + { + return Err(Err::Failure(Error::new( + extensions_rest, + ErrorKind::LengthValue, + ))); + } + extensions.try_push(extension).map_err(|_| { + Err::Failure(Error::new(extensions_rest, ErrorKind::LengthValue)) + })?; + } + extensions_rest = rest; + } + + Ok((remaining, extensions)) + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.client_version.as_u16().to_be_bytes()); + self.random.serialize(output); + output.push(self.session_id.len() as u8); + output.extend_from_slice(&self.session_id); + output.push(self.cookie.len() as u8); + output.extend_from_slice(&self.cookie); + output.extend_from_slice(&(self.cipher_suites.len() as u16 * 2).to_be_bytes()); + for suite in &self.cipher_suites { + output.extend_from_slice(&suite.as_u16().to_be_bytes()); + } + output.push(self.compression_methods.len() as u8); + for method in &self.compression_methods { + output.push(method.as_u8()); + } + + // Add extensions if any + if !self.extensions.is_empty() { + // First calculate total extensions length + let mut extensions_len = 0; + for ext in &self.extensions { + // Extension type (2) + Extension length (2) + Extension data + let ext_data = ext.extension_data(source_buf); + extensions_len += 4 + ext_data.len(); + } + + // Write extensions length + output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + // Write each extension + for ext in &self.extensions { + ext.serialize(source_buf, output); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 + // Random + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, // + 0x01, // SessionId length + 0xAA, // SessionId + 0x01, // Cookie length + 0xBB, // Cookie + 0x00, 0x04, // Dtls12CipherSuites length + 0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + 0xC0, 0x2C, // Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + 0x01, // CompressionMethods length + 0x00, // CompressionMethod::Null + ]; + + #[test] + fn roundtrip() { + let random = Random::parse(&MESSAGE[2..34]).unwrap().1; + let session_id = SessionId::try_new(&[0xAA]).unwrap(); + let cookie = Cookie::try_new(&[0xBB]).unwrap(); + let mut cipher_suites = ArrayVec::new(); + cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256); + cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384); + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + let client_hello = ClientHello::new( + ProtocolVersion::DTLS1_2, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + ); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + client_hello.serialize(&[], &mut serialized); + assert_eq!(&*serialized, MESSAGE); + + // Parse and compare with original + let (rest, parsed) = ClientHello::parse(&serialized, 0).unwrap(); + assert_eq!(parsed, client_hello); + + assert!(rest.is_empty()); + } + + #[test] + fn session_id_too_long() { + let mut message = MESSAGE.to_vec(); + message[34] = 0x21; // SessionId length (33, which is too long) + + let result = ClientHello::parse(&message, 0); + assert!(result.is_err()); + } + + #[test] + fn cookie_too_long() { + let mut message = MESSAGE.to_vec(); + message[36] = 0xFF; // Cookie length (255, which is too long) + + let result = ClientHello::parse(&message, 0); + assert!(result.is_err()); + } + + #[test] + fn duplicate_supported_extensions_are_rejected() { + for count in [2, 9] { + let mut message = MESSAGE.to_vec(); + message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); + for _ in 0..count { + message + .extend_from_slice(&ExtensionType::ExtendedMasterSecret.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = ClientHello::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "duplicate supported extensions should fail with LengthValue" + ); + } + } +} diff --git a/third_party/dimpl/src/dtls12/message/client_key_exchange.rs b/third_party/dimpl/src/dtls12/message/client_key_exchange.rs new file mode 100644 index 0000000..522a6d5 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/client_key_exchange.rs @@ -0,0 +1,211 @@ +use super::KeyExchangeAlgorithm; +use super::{CurveType, NamedGroup}; +use crate::buffer::Buf; +use nom::bytes::complete::take; +use nom::error::Error; +use nom::number::complete::be_u8; +use nom::{Err, IResult}; +use std::ops::Range; + +#[derive(Debug, PartialEq, Eq)] +pub struct ClientKeyExchange { + pub exchange_keys: ExchangeKeys, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum ExchangeKeys { + Ecdh(ClientEcdhKeys), + Psk(ClientPskKeys), +} + +/// ECDHE key exchange parameters +#[derive(Debug, PartialEq, Eq)] +pub struct ClientEcdhKeys { + pub curve_type: CurveType, + pub named_group: NamedGroup, + pub public_key_range: Range, +} + +impl ClientEcdhKeys { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientEcdhKeys> { + let original_input = input; + let (input, public_key_length) = be_u8(input)?; + let (input, public_key_slice) = take(public_key_length)(input)?; + + // Calculate absolute range in root buffer + let relative_offset = public_key_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + public_key_slice.len(); + + Ok(( + input, + ClientEcdhKeys { + // In ClientKeyExchange, we don't include curve_type and named_group + // since they're already established during ServerKeyExchange + curve_type: CurveType::NamedCurve, // Default + named_group: NamedGroup::Secp256r1, // Default + public_key_range: start..end, + }, + )) + } + + pub fn public_key<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.public_key_range.clone()] + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + // For client key exchange, we only need to include the public key length and value + // The curve_type and named_group are already established during ServerKeyExchange + let public_key = self.public_key(buf); + output.push(public_key.len() as u8); + output.extend_from_slice(public_key); + } +} + +impl ClientKeyExchange { + pub fn parse( + input: &[u8], + base_offset: usize, + key_exchange_algorithm: KeyExchangeAlgorithm, + ) -> IResult<&[u8], ClientKeyExchange> { + let (input, exchange_keys) = match key_exchange_algorithm { + KeyExchangeAlgorithm::EECDH => { + let (input, ecdh_keys) = ClientEcdhKeys::parse(input, base_offset)?; + (input, ExchangeKeys::Ecdh(ecdh_keys)) + } + KeyExchangeAlgorithm::PSK => { + let (input, psk_keys) = ClientPskKeys::parse(input, base_offset)?; + (input, ExchangeKeys::Psk(psk_keys)) + } + _ => return Err(Err::Failure(Error::new(input, nom::error::ErrorKind::Tag))), + }; + + Ok((input, ClientKeyExchange { exchange_keys })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + match &self.exchange_keys { + ExchangeKeys::Ecdh(ecdh_keys) => ecdh_keys.serialize(buf, output), + ExchangeKeys::Psk(psk_keys) => psk_keys.serialize(buf, output), + } + } + + /// Helper to serialize directly from public key bytes (for sending) + pub fn serialize_from_bytes(public_key: &[u8], output: &mut Buf) { + output.push(public_key.len() as u8); + output.extend_from_slice(public_key); + } +} + +/// PSK identity sent by the client (RFC 4279 §2). +/// +/// Wire format: `uint16 identity_length + identity` +#[derive(Debug, PartialEq, Eq)] +pub struct ClientPskKeys { + pub identity_range: Range, +} + +impl ClientPskKeys { + pub fn identity<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.identity_range.clone()] + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientPskKeys> { + let original_input = input; + let (input, identity_len) = nom::number::complete::be_u16(input)?; + let (input, identity_slice) = take(identity_len as usize)(input)?; + + let relative_offset = identity_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + identity_slice.len(); + + Ok(( + input, + ClientPskKeys { + identity_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + let identity = self.identity(buf); + output.extend_from_slice(&(identity.len() as u16).to_be_bytes()); + output.extend_from_slice(identity); + } + + /// Serialize directly from identity bytes (for sending). + pub fn serialize_from_bytes(identity: &[u8], output: &mut Buf) { + output.extend_from_slice(&(identity.len() as u16).to_be_bytes()); + output.extend_from_slice(identity); + } +} + +#[cfg(test)] +mod test { + use super::super::KeyExchangeAlgorithm; + use super::*; + use crate::buffer::Buf; + + const ECDH_MESSAGE: &[u8] = &[ + 0x04, // Public key length + 0x01, 0x02, 0x03, 0x04, // Public key data + ]; + + #[test] + fn roundtrip_ecdh() { + // Parse the message with base_offset 0 + let (rest, parsed) = + ClientKeyExchange::parse(ECDH_MESSAGE, 0, KeyExchangeAlgorithm::EECDH).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to ECDH_MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(ECDH_MESSAGE, &mut serialized); + assert_eq!(&*serialized, ECDH_MESSAGE); + } + + #[test] + fn psk_roundtrip() { + const PSK_MESSAGE: &[u8] = &[ + 0x00, 0x05, // identity length = 5 + b'h', b'e', b'l', b'l', b'o', + ]; + let (rest, parsed) = + ClientKeyExchange::parse(PSK_MESSAGE, 0, KeyExchangeAlgorithm::PSK).unwrap(); + assert!(rest.is_empty()); + + let ExchangeKeys::Psk(psk) = &parsed.exchange_keys else { + panic!("expected Psk variant"); + }; + assert_eq!(&PSK_MESSAGE[psk.identity_range.clone()], b"hello"); + + let mut serialized = Buf::new(); + parsed.serialize(PSK_MESSAGE, &mut serialized); + assert_eq!(&*serialized, PSK_MESSAGE); + } + + #[test] + fn psk_rejects_oversized_length() { + // identity_length=0x0064 (100) but only 3 bytes follow — parser must fail + let bad: &[u8] = &[0x00, 0x64, b'a', b'b', b'c']; + let result = ClientKeyExchange::parse(bad, 0, KeyExchangeAlgorithm::PSK); + assert!( + result.is_err(), + "parser must reject PSK identity shorter than advertised length" + ); + } + + #[test] + fn psk_empty_identity() { + // identity_length=0 is wire-legal; parser should accept an empty range. + // (RFC 4279 §5.1 says server MAY reject this — that's an application + // policy decision, not a parse error.) + let empty: &[u8] = &[0x00, 0x00]; + let (rest, parsed) = ClientKeyExchange::parse(empty, 0, KeyExchangeAlgorithm::PSK).unwrap(); + assert!(rest.is_empty()); + let ExchangeKeys::Psk(psk) = &parsed.exchange_keys else { + panic!("expected Psk variant"); + }; + assert!(psk.identity_range.is_empty()); + } +} diff --git a/third_party/dimpl/src/dtls12/message/config.rs b/third_party/dimpl/src/dtls12/message/config.rs new file mode 100644 index 0000000..e69de29 diff --git a/third_party/dimpl/src/dtls12/message/digitally_signed.rs b/third_party/dimpl/src/dtls12/message/digitally_signed.rs new file mode 100644 index 0000000..31c3cda --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/digitally_signed.rs @@ -0,0 +1,68 @@ +use super::SignatureAndHashAlgorithm; +use crate::buffer::Buf; +use nom::number::complete::be_u16; +use nom::{IResult, bytes::complete::take}; +use std::ops::Range; + +#[derive(Debug, PartialEq, Eq)] +pub struct DigitallySigned { + pub algorithm: SignatureAndHashAlgorithm, + pub signature_range: Range, +} + +impl DigitallySigned { + pub fn signature<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.signature_range.clone()] + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], DigitallySigned> { + let original_input = input; + let (rest, algorithm) = SignatureAndHashAlgorithm::parse(input)?; + let (rest, signature_len) = be_u16(rest)?; + let (rest, signature_slice) = take(signature_len)(rest)?; + + // Calculate absolute range in root buffer + let relative_offset = signature_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + signature_slice.len(); + + Ok(( + rest, + DigitallySigned { + algorithm, + signature_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.algorithm.as_u16().to_be_bytes()); + let signature = self.signature(buf); + output.extend_from_slice(&(signature.len() as u16).to_be_bytes()); + output.extend_from_slice(signature); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x04, 0x01, // SignatureAndHashAlgorithm (SHA256 + RSA) + 0x00, 0x04, // Signature length + 0x01, 0x02, 0x03, 0x04, // Signature data + ]; + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = DigitallySigned::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } +} diff --git a/third_party/dimpl/src/dtls12/message/extension.rs b/third_party/dimpl/src/dtls12/message/extension.rs new file mode 100644 index 0000000..3ea0c52 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/extension.rs @@ -0,0 +1,249 @@ +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::{IResult, bytes::complete::take, number::complete::be_u16}; +use std::{fmt, ops::Range}; + +pub type ExtensionVec = ArrayVec; + +#[derive(Debug, PartialEq, Eq, Default)] +pub struct Extension { + pub extension_type: ExtensionType, + pub extension_data_range: Range, +} + +impl Extension { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Extension> { + let original_input = input; + let (input, extension_type) = ExtensionType::parse(input)?; + let (input, extension_length) = be_u16(input)?; + let (input, extension_data_slice) = if extension_length > 0 { + take(extension_length)(input)? + } else { + (input, &input[0..0]) + }; + + // Calculate absolute range in root buffer + let relative_offset = + extension_data_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + extension_data_slice.len(); + + Ok(( + input, + Extension { + extension_type, + extension_data_range: start..end, + }, + )) + } + + pub fn extension_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.extension_data_range.clone()] + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + let extension_data = self.extension_data(buf); + output.extend_from_slice(&self.extension_type.as_u16().to_be_bytes()); + output.extend_from_slice(&(extension_data.len() as u16).to_be_bytes()); + if !extension_data.is_empty() { + output.extend_from_slice(extension_data); + } + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct ExtensionType(u16); + +#[allow(non_upper_case_globals)] +impl ExtensionType { + pub const ServerName: Self = Self(0x0000); + pub const MaxFragmentLength: Self = Self(0x0001); + pub const ClientCertificateUrl: Self = Self(0x0002); + pub const TrustedCaKeys: Self = Self(0x0003); + pub const TruncatedHmac: Self = Self(0x0004); + pub const StatusRequest: Self = Self(0x0005); + pub const UserMapping: Self = Self(0x0006); + pub const ClientAuthz: Self = Self(0x0007); + pub const ServerAuthz: Self = Self(0x0008); + pub const CertType: Self = Self(0x0009); + pub const SupportedGroups: Self = Self(0x000A); + pub const EcPointFormats: Self = Self(0x000B); + pub const Srp: Self = Self(0x000C); + pub const SignatureAlgorithms: Self = Self(0x000D); + pub const UseSrtp: Self = Self(0x000E); + pub const Heartbeat: Self = Self(0x000F); + pub const ApplicationLayerProtocolNegotiation: Self = Self(0x0010); + pub const StatusRequestV2: Self = Self(0x0011); + pub const SignedCertificateTimestamp: Self = Self(0x0012); + pub const ClientCertificateType: Self = Self(0x0013); + pub const ServerCertificateType: Self = Self(0x0014); + pub const Padding: Self = Self(0x0015); + pub const EncryptThenMac: Self = Self(0x0016); + pub const ExtendedMasterSecret: Self = Self(0x0017); + pub const TokenBinding: Self = Self(0x0018); + pub const CachedInfo: Self = Self(0x0019); + pub const SessionTicket: Self = Self(0x0023); + pub const PreSharedKey: Self = Self(0x0029); + pub const EarlyData: Self = Self(0x002A); + pub const SupportedVersions: Self = Self(0x002B); + pub const Cookie: Self = Self(0x002C); + pub const PskKeyExchangeModes: Self = Self(0x002D); + pub const CertificateAuthorities: Self = Self(0x002F); + pub const OidFilters: Self = Self(0x0030); + pub const PostHandshakeAuth: Self = Self(0x0031); + pub const SignatureAlgorithmsCert: Self = Self(0x0032); + pub const KeyShare: Self = Self(0x0033); + pub const RenegotiationInfo: Self = Self(0xFF01); + + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + pub const fn as_u16(&self) -> u16 { + self.0 + } + + const fn is_unknown(&self) -> bool { + !matches!( + *self, + Self(0x0000..=0x0019 | 0x0023 | 0x0029..=0x002D | 0x002F..=0x0033 | 0xFF01) + ) + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], ExtensionType> { + let (input, value) = be_u16(input)?; + Ok((input, ExtensionType::from_u16(value))) + } + + /// Returns true if this extension type is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// Supported extension types that this implementation handles. + pub const fn supported() -> &'static [ExtensionType; 8] { + &[ + ExtensionType::SupportedGroups, + ExtensionType::EcPointFormats, + ExtensionType::SignatureAlgorithms, + ExtensionType::UseSrtp, + ExtensionType::EncryptThenMac, + ExtensionType::ExtendedMasterSecret, + ExtensionType::RenegotiationInfo, + ExtensionType::SessionTicket, + ] + } +} + +impl fmt::Debug for ExtensionType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unknown() { + return f.debug_tuple("Unknown").field(&self.0).finish(); + } + + let name = match *self { + ExtensionType::ServerName => "ServerName", + ExtensionType::MaxFragmentLength => "MaxFragmentLength", + ExtensionType::ClientCertificateUrl => "ClientCertificateUrl", + ExtensionType::TrustedCaKeys => "TrustedCaKeys", + ExtensionType::TruncatedHmac => "TruncatedHmac", + ExtensionType::StatusRequest => "StatusRequest", + ExtensionType::UserMapping => "UserMapping", + ExtensionType::ClientAuthz => "ClientAuthz", + ExtensionType::ServerAuthz => "ServerAuthz", + ExtensionType::CertType => "CertType", + ExtensionType::SupportedGroups => "SupportedGroups", + ExtensionType::EcPointFormats => "EcPointFormats", + ExtensionType::Srp => "Srp", + ExtensionType::SignatureAlgorithms => "SignatureAlgorithms", + ExtensionType::UseSrtp => "UseSrtp", + ExtensionType::Heartbeat => "Heartbeat", + ExtensionType::ApplicationLayerProtocolNegotiation => { + "ApplicationLayerProtocolNegotiation" + } + ExtensionType::StatusRequestV2 => "StatusRequestV2", + ExtensionType::SignedCertificateTimestamp => "SignedCertificateTimestamp", + ExtensionType::ClientCertificateType => "ClientCertificateType", + ExtensionType::ServerCertificateType => "ServerCertificateType", + ExtensionType::Padding => "Padding", + ExtensionType::EncryptThenMac => "EncryptThenMac", + ExtensionType::ExtendedMasterSecret => "ExtendedMasterSecret", + ExtensionType::TokenBinding => "TokenBinding", + ExtensionType::CachedInfo => "CachedInfo", + ExtensionType::SessionTicket => "SessionTicket", + ExtensionType::PreSharedKey => "PreSharedKey", + ExtensionType::EarlyData => "EarlyData", + ExtensionType::SupportedVersions => "SupportedVersions", + ExtensionType::Cookie => "Cookie", + ExtensionType::PskKeyExchangeModes => "PskKeyExchangeModes", + ExtensionType::CertificateAuthorities => "CertificateAuthorities", + ExtensionType::OidFilters => "OidFilters", + ExtensionType::PostHandshakeAuth => "PostHandshakeAuth", + ExtensionType::SignatureAlgorithmsCert => "SignatureAlgorithmsCert", + ExtensionType::KeyShare => "KeyShare", + ExtensionType::RenegotiationInfo => "RenegotiationInfo", + _ => unreachable!("known DTLS 1.2 extension type missing Debug label"), + }; + + f.write_str(name) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x00, 0x0A, // ExtensionType::SupportedGroups + 0x00, 0x08, // Extension length + 0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, // Extension data + ]; + + #[test] + fn extension_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(ExtensionType::default().as_u16(), 0); + assert_eq!(ExtensionType::default(), ExtensionType::ServerName); + } + + #[test] + fn extension_type_wire_roundtrip() { + for extension_type in ExtensionType::supported() { + assert_eq!( + ExtensionType::from_u16(extension_type.as_u16()), + *extension_type + ); + assert!(!extension_type.is_unknown()); + } + + let unknown = ExtensionType::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn extension_type_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", ExtensionType::SupportedGroups), + "SupportedGroups" + ); + assert_eq!( + format!("{:?}", ExtensionType::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = Extension::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } +} diff --git a/third_party/dimpl/src/dtls12/message/extensions/ec_point_formats.rs b/third_party/dimpl/src/dtls12/message/extensions/ec_point_formats.rs new file mode 100644 index 0000000..f6cb9d1 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/extensions/ec_point_formats.rs @@ -0,0 +1,186 @@ +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::{Err, IResult, number::complete::be_u8}; + +/// EC Point Format as defined in RFC 4492 Section 5.1.2 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[allow(unused)] +pub enum ECPointFormat { + #[default] + Uncompressed = 0x00, + AnsiX962CompressedPrime = 0x01, + AnsiX962CompressedChar2 = 0x02, +} + +impl ECPointFormat { + #[allow(unused)] + pub fn parse(input: &[u8]) -> IResult<&[u8], ECPointFormat> { + let (input, value) = be_u8(input)?; + let format = match value { + 0x00 => ECPointFormat::Uncompressed, + 0x01 => ECPointFormat::AnsiX962CompressedPrime, + 0x02 => ECPointFormat::AnsiX962CompressedChar2, + _ => { + return Err(nom::Err::Error(nom::error::Error::new( + input, + nom::error::ErrorKind::Switch, + ))); + } + }; + Ok((input, format)) + } + + pub fn as_u8(&self) -> u8 { + *self as u8 + } +} + +/// ECPointFormats extension as defined in RFC 4492 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ECPointFormatsExtension { + pub formats: ArrayVec, +} + +impl ECPointFormatsExtension { + /// Create a default ECPointFormatsExtension with standard formats + pub fn default() -> Self { + let mut formats = ArrayVec::new(); + // Most implementations only support uncompressed format + formats.push(ECPointFormat::Uncompressed); + + ECPointFormatsExtension { formats } + } + + #[allow(unused)] + pub fn parse(input: &[u8]) -> IResult<&[u8], ECPointFormatsExtension> { + let (input, list_len) = be_u8(input)?; + let (input, formats_data) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let mut formats = ArrayVec::new(); + let mut current_input = formats_data; + + while !current_input.is_empty() { + let format_input = current_input; + let (rest, format) = be_u8(current_input)?; + let Some(format) = (match format { + 0x00 => Some(ECPointFormat::Uncompressed), + 0x01 => Some(ECPointFormat::AnsiX962CompressedPrime), + 0x02 => Some(ECPointFormat::AnsiX962CompressedChar2), + _ => None, + }) else { + current_input = rest; + continue; + }; + + formats + .try_push(format) + .map_err(|_| Err::Failure(Error::new(format_input, ErrorKind::LengthValue)))?; + current_input = rest; + } + + Ok((current_input, ECPointFormatsExtension { formats })) + } + + pub fn serialize(&self, output: &mut Buf) { + // Write the number of formats + output.push(self.formats.len() as u8); + + // Write each format + for format in &self.formats { + output.push(format.as_u8()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn test_ec_point_formats_extension() { + let mut formats = ArrayVec::new(); + formats.push(ECPointFormat::Uncompressed); + formats.push(ECPointFormat::AnsiX962CompressedPrime); + + let ext = ECPointFormatsExtension { formats }; + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x02, // Number of formats (2) + 0x00, // Uncompressed (0x00) + 0x01, // ANSI X9.62 compressed prime (0x01) + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = ECPointFormatsExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.formats.as_slice(), ext.formats.as_slice()); + } + + #[test] + fn too_many_ec_point_formats_are_rejected() { + let bytes = [ + 0x04, // Four point formats. + 0x00, // Uncompressed. + 0x00, // Uncompressed. + 0x00, // Uncompressed. + 0x00, // Uncompressed. + ]; + + let err = ECPointFormatsExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } + + #[test] + fn unknown_ec_point_formats_are_ignored() { + let (rest, parsed) = ECPointFormatsExtension::parse(&[ + 0x03, // Three point formats. + 0x02, // ANSI X9.62 compressed char2. + 0x00, // Uncompressed. + 0xFF, // Unknown/private point format. + ]) + .unwrap(); + + assert!(rest.is_empty()); + assert_eq!( + parsed.formats.as_slice(), + &[ + ECPointFormat::AnsiX962CompressedChar2, + ECPointFormat::Uncompressed, + ] + ); + } + + #[test] + fn trailing_ec_point_format_bytes_are_rejected() { + let result = ECPointFormatsExtension::parse(&[ + 0x01, // One point format. + 0x00, // Uncompressed. + 0xFF, // Extension body has a trailing byte beyond the vector. + ]); + + assert!(matches!( + result, + Err(Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + })) + )); + } +} diff --git a/third_party/dimpl/src/dtls12/message/extensions/mod.rs b/third_party/dimpl/src/dtls12/message/extensions/mod.rs new file mode 100644 index 0000000..7c6ec7c --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/extensions/mod.rs @@ -0,0 +1,9 @@ +pub mod ec_point_formats; +pub mod signature_algorithms; +pub mod supported_groups; +pub mod use_srtp; + +pub use ec_point_formats::ECPointFormatsExtension; +pub use signature_algorithms::SignatureAlgorithmsExtension; +pub use supported_groups::SupportedGroupsExtension; +pub use use_srtp::UseSrtpExtension; diff --git a/third_party/dimpl/src/dtls12/message/extensions/signature_algorithms.rs b/third_party/dimpl/src/dtls12/message/extensions/signature_algorithms.rs new file mode 100644 index 0000000..258bdd5 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/extensions/signature_algorithms.rs @@ -0,0 +1,213 @@ +use super::super::{SignatureAndHashAlgorithm, SignatureAndHashAlgorithmVec}; +use crate::buffer::Buf; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; + +/// SignatureAlgorithms extension as defined in RFC 5246 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignatureAlgorithmsExtension { + pub supported_signature_algorithms: SignatureAndHashAlgorithmVec, +} + +impl SignatureAlgorithmsExtension { + /// Create a default SignatureAlgorithmsExtension with standard algorithms + pub fn default() -> Self { + SignatureAlgorithmsExtension { + supported_signature_algorithms: SignatureAndHashAlgorithmVec::from( + *SignatureAndHashAlgorithm::supported(), + ), + } + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAlgorithmsExtension> { + let (input, list_len) = nom::number::complete::be_u16(input)?; + if list_len == 0 || list_len % 2 != 0 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let mut algorithms = SignatureAndHashAlgorithmVec::new(); + let (input, mut current_input) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + // Parse algorithms, filtering to only keep supported ones + while !current_input.is_empty() { + let (rest, alg) = SignatureAndHashAlgorithm::parse(current_input)?; + // Only keep supported signature+hash combinations + if alg.is_supported() { + algorithms + .try_push(alg) + .map_err(|_| Err::Failure(Error::new(current_input, ErrorKind::LengthValue)))?; + } + current_input = rest; + } + + Ok(( + input, + SignatureAlgorithmsExtension { + supported_signature_algorithms: algorithms, + }, + )) + } + + pub fn serialize(&self, output: &mut Buf) { + // Write the total length of all algorithms (2 bytes per algorithm) + output.extend_from_slice( + &((self.supported_signature_algorithms.len() * 2) as u16).to_be_bytes(), + ); + + // Write each algorithm + for alg in &self.supported_signature_algorithms { + output.extend_from_slice(&alg.as_u16().to_be_bytes()); + } + } +} + +#[cfg(test)] +mod tests { + use super::super::super::{HashAlgorithm, SignatureAlgorithm}; + + use super::*; + + #[test] + fn test_signature_algorithms_extension() { + let mut algorithms = SignatureAndHashAlgorithmVec::new(); + algorithms.push(SignatureAndHashAlgorithm::new( + HashAlgorithm::SHA256, + SignatureAlgorithm::ECDSA, + )); + algorithms.push(SignatureAndHashAlgorithm::new( + HashAlgorithm::SHA256, + SignatureAlgorithm::RSA, + )); + + let ext = SignatureAlgorithmsExtension { + supported_signature_algorithms: algorithms.clone(), + }; + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x00, 0x04, // Length (4 bytes) + 0x04, 0x03, // SHA256/ECDSA + 0x04, 0x01, // SHA256/RSA + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = SignatureAlgorithmsExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.supported_signature_algorithms.len(), 1); + assert_eq!( + parsed.supported_signature_algorithms[0], + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA,) + ); + } + + #[test] + fn default_does_not_advertise_rsa() { + let extension = SignatureAlgorithmsExtension::default(); + + assert!( + extension + .supported_signature_algorithms + .iter() + .all(|algorithm| algorithm.signature != SignatureAlgorithm::RSA) + ); + } + + #[test] + fn capacity_matches_supported() { + let extension = SignatureAlgorithmsExtension::default(); + + assert_eq!( + extension.supported_signature_algorithms.capacity(), + SignatureAndHashAlgorithm::supported().len() + ); + } + + #[test] + fn too_many_supported_signature_algorithms_are_rejected() { + let mut bytes = Vec::new(); + let count = SignatureAndHashAlgorithm::supported().len() + 1; + bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes()); + for _ in 0..count { + bytes.extend_from_slice( + &SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA) + .as_u16() + .to_be_bytes(), + ); + } + + let result = SignatureAlgorithmsExtension::parse(&bytes); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many supported signature algorithms should fail with LengthValue" + ); + } + + #[test] + fn odd_length_signature_algorithms_are_rejected_without_panic() { + let result = std::panic::catch_unwind(|| { + SignatureAlgorithmsExtension::parse(&[ + 0x00, 0x01, // Declared list length is not divisible by 2. + 0x04, 0x03, // Extra byte proves the parser must reject before looping. + ]) + }); + + assert!( + result.is_ok(), + "odd signature_algorithms length must not panic" + ); + assert!( + matches!( + result.unwrap(), + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "odd signature_algorithms length should fail with LengthValue" + ); + } + + #[test] + fn empty_signature_algorithms_are_rejected() { + let result = SignatureAlgorithmsExtension::parse(&[ + 0x00, 0x00, // Empty signature_algorithms vector is invalid. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "empty signature_algorithms vector should fail with LengthValue" + ); + } + + #[test] + fn trailing_signature_algorithms_bytes_are_rejected() { + let result = SignatureAlgorithmsExtension::parse(&[ + 0x00, 0x02, // One algorithm follows. + 0x04, 0x03, // SHA256/ECDSA + 0xff, // Extension body has a trailing byte beyond the vector. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing signature_algorithms bytes should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls12/message/extensions/supported_groups.rs b/third_party/dimpl/src/dtls12/message/extensions/supported_groups.rs new file mode 100644 index 0000000..12b9fb4 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/extensions/supported_groups.rs @@ -0,0 +1,161 @@ +use super::super::{NamedGroup, NamedGroupVec}; +use crate::buffer::Buf; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; + +/// SupportedGroups extension as defined in RFC 8422 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SupportedGroupsExtension { + pub groups: NamedGroupVec, +} + +impl SupportedGroupsExtension { + pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedGroupsExtension> { + let (input, list_len) = nom::number::complete::be_u16(input)?; + if list_len % 2 != 0 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let (input, mut current_input) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let mut groups = NamedGroupVec::new(); + + // Parse groups; only include supported groups (skip Unknown and unsupported) + while !current_input.is_empty() { + let group_input = current_input; + let (rest, group) = NamedGroup::parse(group_input)?; + current_input = rest; + // Only add supported groups + if group.is_supported() { + groups + .try_push(group) + .map_err(|_| Err::Failure(Error::new(group_input, ErrorKind::LengthValue)))?; + } + } + + Ok((input, SupportedGroupsExtension { groups })) + } + + pub fn serialize(&self, output: &mut Buf) { + // Write the total length of all groups (2 bytes per group) + output.extend_from_slice(&((self.groups.len() * 2) as u16).to_be_bytes()); + + // Write each group + for group in &self.groups { + output.extend_from_slice(&group.as_u16().to_be_bytes()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn test_supported_groups_extension() { + let mut groups = NamedGroupVec::new(); + groups.push(NamedGroup::X25519); + groups.push(NamedGroup::Secp256r1); + + let ext = SupportedGroupsExtension { groups }; + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x00, 0x04, // Groups length (4 bytes) + 0x00, 0x1D, // X25519 (0x001D) + 0x00, 0x17, // secp256r1 (0x0017) + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = SupportedGroupsExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.groups.as_slice(), ext.groups.as_slice()); + } + + #[test] + fn test_supported_groups_parse_provided_bytes() { + // Provided bytes: [0,10,0,29,0,23,0,24,1,0,1,1] + // Meaning: + // 0x000A -> list length = 10 bytes (5 groups) + // groups: 0x001D (X25519), 0x0017 (P-256), 0x0018 (P-384), 0x0100 (unknown), 0x0101 (unknown) + let bytes = [0, 10, 0, 29, 0, 23, 0, 24, 1, 0, 1, 1]; + + let (rest, parsed) = + SupportedGroupsExtension::parse(&bytes).expect("parse SupportedGroups"); + assert!(rest.is_empty()); + + // Expect only the supported groups in order as they appear + assert_eq!( + parsed.groups.as_slice(), + &[ + NamedGroup::X25519, + NamedGroup::Secp256r1, + NamedGroup::Secp384r1 + ] + ); + } + + #[test] + fn too_many_supported_groups_are_rejected() { + let mut bytes = Vec::new(); + let count = NamedGroup::supported().len() + 1; + bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes()); + for _ in 0..count { + bytes.extend_from_slice(&NamedGroup::X25519.as_u16().to_be_bytes()); + } + + let result = SupportedGroupsExtension::parse(&bytes); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many supported groups should fail with LengthValue" + ); + } + + #[test] + fn odd_supported_groups_vector_is_rejected() { + let result = SupportedGroupsExtension::parse(&[ + 0x00, 0x03, // Declared vector length is not divisible by 2. + 0x00, 0x1D, 0xFF, + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "odd supported_groups vector should fail with LengthValue" + ); + } + + #[test] + fn trailing_supported_groups_bytes_are_rejected() { + let result = SupportedGroupsExtension::parse(&[ + 0x00, 0x02, // One named group. + 0x00, 0x1D, // X25519. + 0xFF, // Extension body has a trailing byte beyond the vector. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing supported_groups bytes should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls12/message/extensions/use_srtp.rs b/third_party/dimpl/src/dtls12/message/extensions/use_srtp.rs new file mode 100644 index 0000000..e0abfd1 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/extensions/use_srtp.rs @@ -0,0 +1,293 @@ +use crate::SrtpProfile; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u8, be_u16}; +use nom::{Err, IResult}; + +pub type SrtpProfileVec = ArrayVec; + +/// DTLS-SRTP protection profile identifiers +/// From RFC 5764 Section 4.1.2 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[allow(non_camel_case_types)] +pub enum SrtpProfileId { + #[default] + SRTP_AES128_CM_SHA1_80 = 0x0001, + SRTP_AEAD_AES_128_GCM = 0x0007, + SRTP_AEAD_AES_256_GCM = 0x0008, +} + +impl SrtpProfileId { + pub fn parse(input: &[u8]) -> IResult<&[u8], SrtpProfileId> { + let (input, value) = be_u16(input)?; + let profile = match value { + 0x0001 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, + 0x0007 => SrtpProfileId::SRTP_AEAD_AES_128_GCM, + 0x0008 => SrtpProfileId::SRTP_AEAD_AES_256_GCM, + _ => { + return Err(nom::Err::Error(nom::error::Error::new( + input, + nom::error::ErrorKind::Switch, + ))); + } + }; + Ok((input, profile)) + } + + pub fn as_u16(&self) -> u16 { + *self as u16 + } + + /// All recognized SRTP profile IDs (every non-`Unknown` variant). + pub const fn all() -> &'static [SrtpProfileId; 3] { + &[ + SrtpProfileId::SRTP_AES128_CM_SHA1_80, + SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfileId::SRTP_AEAD_AES_256_GCM, + ] + } + + /// Supported SRTP profile IDs. + pub const fn supported() -> &'static [SrtpProfileId; 3] { + Self::all() + } +} + +impl From for SrtpProfileId { + fn from(profile: SrtpProfile) -> Self { + match profile { + SrtpProfile::AES128_CM_SHA1_80 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, + SrtpProfile::AEAD_AES_128_GCM => SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfile::AEAD_AES_256_GCM => SrtpProfileId::SRTP_AEAD_AES_256_GCM, + } + } +} + +impl From for SrtpProfile { + fn from(profile: SrtpProfileId) -> Self { + match profile { + SrtpProfileId::SRTP_AES128_CM_SHA1_80 => SrtpProfile::AES128_CM_SHA1_80, + SrtpProfileId::SRTP_AEAD_AES_128_GCM => SrtpProfile::AEAD_AES_128_GCM, + SrtpProfileId::SRTP_AEAD_AES_256_GCM => SrtpProfile::AEAD_AES_256_GCM, + } + } +} + +/// UseSrtp extension as defined in RFC 5764 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UseSrtpExtension { + pub profiles: SrtpProfileVec, + pub mki: ArrayVec, // MKI value (usually empty) +} + +impl UseSrtpExtension { + pub fn new(profiles: SrtpProfileVec, mki: ArrayVec) -> Self { + UseSrtpExtension { profiles, mki } + } + + /// Create a default UseSrtpExtension with standard profiles + pub fn default() -> Self { + let mut profiles = SrtpProfileVec::new(); + // Add profiles in order of preference (most secure first) + profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM); + profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM); + profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80); + + // MKI is typically empty as per RFC 5764 + UseSrtpExtension { + profiles, + mki: ArrayVec::new(), + } + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], UseSrtpExtension> { + let (input, profiles_length) = be_u16(input)?; + let (input, profiles_data) = take(profiles_length)(input)?; + + // Parse the profiles (ignore unknown profile IDs instead of failing) + let mut profiles = SrtpProfileVec::new(); + let mut profiles_rest = profiles_data; + + while profiles_rest.len() >= 2 { + let profile_input = profiles_rest; + let (rest, value) = be_u16(profile_input)?; + profiles_rest = rest; + match value { + 0x0001 => profiles + .try_push(SrtpProfileId::SRTP_AES128_CM_SHA1_80) + .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, + 0x0007 => profiles + .try_push(SrtpProfileId::SRTP_AEAD_AES_128_GCM) + .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, + 0x0008 => profiles + .try_push(SrtpProfileId::SRTP_AEAD_AES_256_GCM) + .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, + _ => { + // Unknown SRTP profile: skip + } + } + } + if !profiles_rest.is_empty() { + return Err(Err::Failure(Error::new( + profiles_rest, + ErrorKind::LengthValue, + ))); + } + + // Parse MKI + let (input, mki_length) = be_u8(input)?; + let (input, mki) = take(mki_length)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok(( + input, + UseSrtpExtension { + profiles, + mki: ArrayVec::try_from(mki).unwrap_or_default(), + }, + )) + } + + pub fn serialize(&self, output: &mut Buf) { + // Length of all profiles (2 bytes per profile) + output.extend_from_slice(&((self.profiles.len() * 2) as u16).to_be_bytes()); + + // Write each profile + for profile in &self.profiles { + output.extend_from_slice(&profile.as_u16().to_be_bytes()); + } + + // MKI length and data + output.push(self.mki.len() as u8); + output.extend_from_slice(&self.mki); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn test_use_srtp_extension() { + let mut profiles = SrtpProfileVec::new(); + profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM); + profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM); + profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80); + + let mut mki = ArrayVec::new(); + mki.push(1); + mki.push(2); + mki.push(3); + + let ext = UseSrtpExtension::new(profiles, mki.clone()); + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x00, 0x06, // Profiles length (6 bytes) + 0x00, 0x08, // SRTP_AEAD_AES_256_GCM (0x0008) + 0x00, 0x07, // SRTP_AEAD_AES_128_GCM (0x0007) + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80 (0x0001) + 0x03, // MKI length (3 bytes) + 0x01, 0x02, 0x03, // MKI + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = UseSrtpExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.profiles.as_slice(), ext.profiles.as_slice()); + assert_eq!(parsed.mki, mki); + } + + #[test] + fn test_use_srtp_parse_provided_bytes() { + // Provided bytes: [0,8,0,7,0,8,0,1,0,2,0] + // Meaning: + // 0x0008 -> profiles length = 8 bytes (4 profile IDs) + // profiles: 0x0007, 0x0008, 0x0001, 0x0002 (0x0002 is unknown and should be ignored) + // MKI length = 0 + let bytes = [0, 8, 0, 7, 0, 8, 0, 1, 0, 2, 0]; + + let (_, parsed) = UseSrtpExtension::parse(&bytes).expect("parse UseSrtpExtension"); + + // Expect only the three known profiles, in the same order as offered + assert_eq!( + parsed.profiles.as_slice(), + &[ + SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfileId::SRTP_AEAD_AES_256_GCM, + SrtpProfileId::SRTP_AES128_CM_SHA1_80 + ] + ); + assert_eq!(parsed.mki, ArrayVec::::new()); + } + + #[test] + fn too_many_supported_srtp_profiles_are_rejected() { + let bytes = [ + 0x00, 0x08, // Four profile IDs. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, // Empty MKI. + ]; + + let err = UseSrtpExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } + + #[test] + fn odd_srtp_profile_vector_is_rejected() { + let bytes = [ + 0x00, 0x03, // Odd profile vector length. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, // Dangling byte in profile vector. + 0x00, // Empty MKI. + ]; + + let err = UseSrtpExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } + + #[test] + fn trailing_mki_bytes_are_rejected() { + let bytes = [ + 0x00, 0x02, // One profile ID. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, // Empty MKI. + 0xFF, // Trailing extension-body byte. + ]; + + let err = UseSrtpExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } +} diff --git a/third_party/dimpl/src/dtls12/message/finished.rs b/third_party/dimpl/src/dtls12/message/finished.rs new file mode 100644 index 0000000..33d8cd9 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/finished.rs @@ -0,0 +1,64 @@ +use super::Dtls12CipherSuite; +use crate::buffer::Buf; +use nom::IResult; +use nom::bytes::complete::take; +use std::ops::Range; + +#[derive(Debug, PartialEq, Eq)] +pub struct Finished { + pub verify_data_range: Range, +} + +impl Finished { + pub fn verify_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.verify_data_range.clone()] + } + + pub fn parse(input: &[u8], cipher_suite: Dtls12CipherSuite) -> IResult<&[u8], Finished> { + let verify_data_length = cipher_suite.verify_data_length(); + let (rest, verify_data_slice) = take(verify_data_length)(input)?; + + // Calculate range relative to input buffer without unsafe code + // verify_data_slice is a sub-slice of input from nom's take combinator + let start = verify_data_slice.as_ptr() as usize - input.as_ptr() as usize; + let end = start + verify_data_slice.len(); + + Ok(( + rest, + Finished { + verify_data_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.extend_from_slice(self.verify_data(buf)); + } +} + +#[cfg(test)] +mod test { + use super::Dtls12CipherSuite; + use super::*; + use crate::buffer::Buf; + + #[test] + fn roundtrip() { + let verify_data = vec![ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, + ]; + + // Parse the data + let (rest, parsed) = Finished::parse( + &verify_data, + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, + ) + .unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to original + let mut serialized = Buf::new(); + parsed.serialize(&verify_data, &mut serialized); + assert_eq!(&*serialized, &verify_data[..]); + } +} diff --git a/third_party/dimpl/src/dtls12/message/handshake.rs b/third_party/dimpl/src/dtls12/message/handshake.rs new file mode 100644 index 0000000..c6b409e --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/handshake.rs @@ -0,0 +1,836 @@ +use std::fmt; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::Certificate; +use super::CertificateRequest; +use super::CertificateVerify; +use super::ClientHello; +use super::ClientKeyExchange; +use super::Dtls12CipherSuite; +use super::Finished; +use super::HelloVerifyRequest; +use super::ServerHello; +use super::ServerKeyExchange; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u8; +use nom::number::complete::{be_u16, be_u24}; + +// Defensive stack cap over flattened handshake fragments selected for one +// defragmentation attempt. This intentionally does not mirror the receive +// queue's record-count cap; exceeding 50 fragments for one handshake implies +// pathologically tiny records and is treated as invalid input. +const MAX_DEFRAGMENT_HANDSHAKES: usize = 50; + +#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)] +pub struct Header { + pub msg_type: MessageType, + pub length: u32, + pub message_seq: u16, + pub fragment_offset: u32, + pub fragment_length: u32, +} + +#[derive(Debug, Default)] +pub struct Handshake { + pub header: Header, + pub body: Body, + pub handled: AtomicBool, +} + +impl PartialEq for Handshake { + fn eq(&self, other: &Self) -> bool { + self.header == other.header + && self.body == other.body + && self.handled.load(Ordering::Relaxed) == other.handled.load(Ordering::Relaxed) + } +} + +impl Eq for Handshake {} + +impl Handshake { + #[cfg(test)] + pub fn new( + msg_type: MessageType, + length: u32, + message_seq: u16, + fragment_offset: u32, + fragment_length: u32, + body: Body, + ) -> Self { + Handshake { + header: Header { + msg_type, + length, + message_seq, + fragment_offset, + fragment_length, + }, + body, + handled: AtomicBool::new(false), + } + } + + pub fn parse_header(input: &[u8]) -> IResult<&[u8], Header> { + let (input, msg_type) = MessageType::parse(input)?; + let (input, length) = be_u24(input)?; + let (input, message_seq) = be_u16(input)?; + let (input, fragment_offset) = be_u24(input)?; + let (input, fragment_length) = be_u24(input)?; + + Ok(( + input, + Header { + msg_type, + length, + message_seq, + fragment_offset, + fragment_length, + }, + )) + } + + pub fn parse( + input: &[u8], + base_offset: usize, + c: Option, + as_fragment: bool, + ) -> IResult<&[u8], Handshake> { + let original_input = input; + let (input, header) = Self::parse_header(input)?; + + let is_fragment = header.fragment_offset > 0 || header.fragment_length < header.length; + + if !as_fragment && is_fragment { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let (input, body) = if as_fragment { + let (input, fragment_slice) = take(header.fragment_length as usize)(input)?; + // Calculate range relative to original input + let relative_offset = + fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + fragment_slice.len(); + (input, Body::Fragment(start..end)) + } else { + let (input, body_bytes) = take(header.length as usize)(input)?; + // Calculate base_offset for body parsing + let consumed = body_bytes.as_ptr() as usize - original_input.as_ptr() as usize; + let body_base_offset = base_offset + consumed; + let (_, body) = Body::parse(body_bytes, body_base_offset, header.msg_type, c)?; + (input, body) + }; + + Ok(( + input, + Handshake { + header, + body, + handled: AtomicBool::new(false), + }, + )) + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + output.push(self.header.msg_type.as_u8()); + output.extend_from_slice(&self.header.length.to_be_bytes()[1..]); + output.extend_from_slice(&self.header.message_seq.to_be_bytes()); + output.extend_from_slice(&self.header.fragment_offset.to_be_bytes()[1..]); + output.extend_from_slice(&self.header.fragment_length.to_be_bytes()[1..]); + self.body.serialize(source_buf, output); + } + + #[allow(private_interfaces)] + pub fn defragment<'b>( + mut iter: impl Iterator, + buffer: &mut Buf, + cipher_suite: Option, + transcript: Option<&mut Buf>, + ) -> Result { + buffer.clear(); + + // Invariant is upheld by the caller. + let (first_handshake, first_buffer) = iter.next().unwrap(); + + let Body::Fragment(range) = &first_handshake.body else { + unreachable!("Non-Fragment body in defragment()") + }; + let mut handled = ArrayVec::<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>::new(); + handled + .try_push(first_handshake) + .map_err(|_| crate::InternalError::too_many_records())?; + buffer.extend_from_slice(&first_buffer[range.clone()]); + + for (handshake, source_buf) in iter { + if handshake.header.msg_type != first_handshake.header.msg_type + || handshake.header.message_seq != first_handshake.header.message_seq + { + break; + } + + let Body::Fragment(range) = &handshake.body else { + unreachable!("Non-Fragment body in defragment()") + }; + + handled + .try_push(handshake) + .map_err(|_| crate::InternalError::too_many_records())?; + + buffer.extend_from_slice(&source_buf[range.clone()]); + } + + if buffer.len() != first_handshake.header.length as usize { + debug!("Defragmentation failed. Fragment length mismatch"); + return Err(crate::InternalError::parse_incomplete()); + } + + let (rest, body) = + match Body::parse(buffer, 0, first_handshake.header.msg_type, cipher_suite) { + Ok(parsed) => parsed, + Err(err) => { + mark_handled(handled); + return Err(err.into()); + } + }; + + if !rest.is_empty() + && first_handshake + .header + .msg_type + .rejects_trailing_body_bytes() + { + debug!("Defragmentation failed. Body::parse() did not consume the entire buffer"); + mark_handled(handled); + return Err(crate::InternalError::parse_incomplete()); + } + + // Intentional boundary: Body::parse validates the handshake body shape and + // extension envelopes, but known extension payloads remain validated by the + // client/server state handlers. A transiently corrupted UDP datagram whose + // extension payload fails later may therefore have been consumed here; that + // recovery edge is accepted to keep this path parser-only and avoid the + // broader transaction/rollback machinery. + mark_handled(handled); + + // If transcript is provided, write the handshake header + body after parsing succeeds. + if let Some(transcript) = transcript { + transcript.push(first_handshake.header.msg_type.as_u8()); + transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]); + transcript.extend_from_slice(&first_handshake.header.message_seq.to_be_bytes()); + // Defragmented handshake has fragment_offset=0 and fragment_length=length + transcript.extend_from_slice(&0u32.to_be_bytes()[1..]); + transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]); + transcript.extend_from_slice(&buffer[..first_handshake.header.length as usize]); + } + + let handshake = Handshake { + header: Header { + msg_type: first_handshake.header.msg_type, + length: first_handshake.header.length, + message_seq: first_handshake.header.message_seq, + fragment_offset: 0, + fragment_length: first_handshake.header.length, + }, + body, + handled: AtomicBool::new(false), + }; + + // Create a new Handshake with the merged body + Ok(handshake) + } + + #[cfg(test)] + fn do_clone(&self) -> Handshake { + Handshake { + header: Header { + msg_type: self.header.msg_type, + length: self.header.length, + message_seq: self.header.message_seq, + fragment_offset: self.header.fragment_offset, + fragment_length: self.header.fragment_length, + }, + body: Body::HelloRequest, // Placeholder + handled: AtomicBool::new(false), + } + } + + #[cfg(test)] + pub fn fragment<'b>( + &self, + max: usize, + buffer: &'b mut Buf, + ) -> impl Iterator + 'b { + // Must be called with an empty buffer. + assert!(buffer.is_empty()); + + // Note: For fragmentize, self is already serialized data in Body::Fragment + // which doesn't need source_buf, so we pass an empty slice + self.body.serialize(&[], buffer); + + // If this is wrong, the serialize has not produced the same output as we parsed. + assert_eq!(buffer.len(), self.header.length as usize); + + let to_clone = self.do_clone(); + + buffer.chunks(max).enumerate().map(move |(i, chunk)| { + let fragment_length = chunk.len() as u32; + let offset = i * max; + let fragment_range = offset..(offset + chunk.len()); + + let mut fragment = to_clone.do_clone(); + fragment.header.fragment_offset = offset as u32; + fragment.header.fragment_length = fragment_length; + fragment.header.message_seq = to_clone.header.message_seq; + fragment.body = Body::Fragment(fragment_range); + + fragment + }) + } + + // These are (unencrypted) handshakes that, when detected as + // duplicates, trigger a resend of the entire flight. + pub fn dupe_triggers_resend(&self) -> Option { + // Only trigger on the first fragment of a handshake message to avoid + // multiple resends caused by fragmented duplicates of the same message. + if self.header.fragment_offset != 0 { + return None; + } + + let qualifies = matches!( + self.header.msg_type, + MessageType::ClientHello | // flight 1 and 3 + MessageType::HelloVerifyRequest | // flight 2 + MessageType::ServerHelloDone | // flight 4 + MessageType::ClientKeyExchange // flight 5 + ); + + qualifies.then_some(self.header.message_seq) + } + + pub fn is_handled(&self) -> bool { + self.handled.load(Ordering::Relaxed) + } + + pub fn set_handled(&self) { + self.handled.store(true, Ordering::Relaxed); + } +} + +fn mark_handled(handled: ArrayVec<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>) { + for handshake in handled { + handshake.set_handled(); + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct MessageType(u8); + +#[allow(non_upper_case_globals)] +impl MessageType { + pub const HelloRequest: Self = Self(0); + pub const ClientHello: Self = Self(1); + pub const ServerHello: Self = Self(2); + pub const HelloVerifyRequest: Self = Self(3); + pub const NewSessionTicket: Self = Self(4); + pub const Certificate: Self = Self(11); + pub const ServerKeyExchange: Self = Self(12); + pub const CertificateRequest: Self = Self(13); + pub const ServerHelloDone: Self = Self(14); + pub const CertificateVerify: Self = Self(15); + pub const ClientKeyExchange: Self = Self(16); + pub const Finished: Self = Self(20); + + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + pub const fn as_u8(&self) -> u8 { + self.0 + } + + const fn is_unknown(&self) -> bool { + !matches!(*self, Self(0..=4 | 11..=16 | 20)) + } + + const fn rejects_trailing_body_bytes(&self) -> bool { + !self.is_unknown() + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], MessageType> { + let (input, byte) = be_u8(input)?; + Ok((input, Self::from_u8(byte))) + } + + pub fn epoch(&self) -> u16 { + if matches!(*self, MessageType::NewSessionTicket | MessageType::Finished) { + 1 + } else { + 0 + } + } +} + +impl fmt::Debug for MessageType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unknown() { + return f.debug_tuple("Unknown").field(&self.0).finish(); + } + + let name = match *self { + MessageType::HelloRequest => "HelloRequest", + MessageType::ClientHello => "ClientHello", + MessageType::HelloVerifyRequest => "HelloVerifyRequest", + MessageType::ServerHello => "ServerHello", + MessageType::Certificate => "Certificate", + MessageType::ServerKeyExchange => "ServerKeyExchange", + MessageType::CertificateRequest => "CertificateRequest", + MessageType::ServerHelloDone => "ServerHelloDone", + MessageType::CertificateVerify => "CertificateVerify", + MessageType::ClientKeyExchange => "ClientKeyExchange", + MessageType::NewSessionTicket => "NewSessionTicket", + MessageType::Finished => "Finished", + _ => unreachable!("known DTLS 1.2 handshake message type missing Debug label"), + }; + + f.write_str(name) + } +} + +#[derive(Debug, PartialEq, Eq)] +#[allow(clippy::large_enum_variant)] +pub enum Body { + HelloRequest, // empty + ClientHello(ClientHello), + HelloVerifyRequest(HelloVerifyRequest), + ServerHello(ServerHello), + Certificate(Certificate), + ServerKeyExchange(ServerKeyExchange), + CertificateRequest(CertificateRequest), + ServerHelloDone, // empty + CertificateVerify(CertificateVerify), + ClientKeyExchange(ClientKeyExchange), + NewSessionTicket(Range), + Finished(Finished), + Unknown(u8), + Fragment(Range), +} + +impl Default for Body { + fn default() -> Self { + Self::Unknown(0) + } +} + +impl Body { + pub fn parse( + input: &[u8], + base_offset: usize, + m: MessageType, + c: Option, + ) -> IResult<&[u8], Body> { + match m { + MessageType::HelloRequest => Ok((input, Body::HelloRequest)), + MessageType::ClientHello => { + let (input, client_hello) = ClientHello::parse(input, base_offset)?; + Ok((input, Body::ClientHello(client_hello))) + } + MessageType::HelloVerifyRequest => { + let (input, hello_verify_request) = HelloVerifyRequest::parse(input)?; + Ok((input, Body::HelloVerifyRequest(hello_verify_request))) + } + MessageType::ServerHello => { + let (input, server_hello) = ServerHello::parse(input, base_offset)?; + Ok((input, Body::ServerHello(server_hello))) + } + MessageType::Certificate => { + let (input, certificate) = Certificate::parse(input, base_offset)?; + Ok((input, Body::Certificate(certificate))) + } + MessageType::ServerKeyExchange => { + let cipher_suite = + c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; + let algo = cipher_suite.as_key_exchange_algorithm(); + let (input, server_key_exchange) = + ServerKeyExchange::parse(input, base_offset, algo)?; + Ok((input, Body::ServerKeyExchange(server_key_exchange))) + } + MessageType::CertificateRequest => { + let (input, certificate_request) = CertificateRequest::parse(input, base_offset)?; + Ok((input, Body::CertificateRequest(certificate_request))) + } + MessageType::ServerHelloDone => Ok((input, Body::ServerHelloDone)), + MessageType::CertificateVerify => { + let (input, certificate_verify) = CertificateVerify::parse(input, base_offset)?; + Ok((input, Body::CertificateVerify(certificate_verify))) + } + MessageType::ClientKeyExchange => { + let cipher_suite = + c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; + let algo = cipher_suite.as_key_exchange_algorithm(); + let (input, client_key_exchange) = + ClientKeyExchange::parse(input, base_offset, algo)?; + Ok((input, Body::ClientKeyExchange(client_key_exchange))) + } + MessageType::NewSessionTicket => { + // Treat ticket as opaque per RFC 5077: lifetime_hint(4) + ticket (opaque vector) + let range = base_offset..(base_offset + input.len()); + Ok((&[], Body::NewSessionTicket(range))) + } + MessageType::Finished => { + let cipher_suite = + c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; + let (input, finished) = Finished::parse(input, cipher_suite)?; + Ok((input, Body::Finished(finished))) + } + _ => Ok((input, Body::Unknown(m.as_u8()))), + } + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + match self { + Body::HelloRequest => { + // Serialize HelloRequest (empty) + } + Body::ClientHello(client_hello) => { + client_hello.serialize(source_buf, output); + } + Body::HelloVerifyRequest(hello_verify_request) => { + hello_verify_request.serialize(output); + } + Body::ServerHello(server_hello) => { + server_hello.serialize(source_buf, output); + } + Body::Certificate(certificate) => { + certificate.serialize(source_buf, output); + } + Body::ServerKeyExchange(server_key_exchange) => { + server_key_exchange.serialize(source_buf, output, true); + } + Body::CertificateRequest(certificate_request) => { + certificate_request.serialize(source_buf, output); + } + Body::ServerHelloDone => { + // Serialize ServerHelloDone (empty) + } + Body::CertificateVerify(certificate_verify) => { + certificate_verify.serialize(source_buf, output); + } + Body::ClientKeyExchange(client_key_exchange) => { + client_key_exchange.serialize(source_buf, output); + } + Body::NewSessionTicket(range) => { + output.extend_from_slice(&source_buf[range.clone()]); + } + Body::Finished(finished) => { + finished.serialize(source_buf, output); + } + Body::Unknown(value) => { + output.push(*value); + } + Body::Fragment(range) => { + output.extend_from_slice(&source_buf[range.clone()]); + } + } + } +} + +#[cfg(test)] +mod tests { + use arrayvec::ArrayVec; + use std::collections::VecDeque; + + use super::*; + use crate::buffer::Buf; + use crate::dtls12::message::CompressionMethod; + use crate::dtls12::message::Cookie; + use crate::dtls12::message::Dtls12CipherSuite; + use crate::dtls12::message::ProtocolVersion; + use crate::dtls12::message::Random; + use crate::dtls12::message::SessionId; + + const MESSAGE: &[u8] = &[ + 0x01, // MessageType::ClientHello + 0x00, 0x00, 0x2E, // length + 0x00, 0x00, // message_seq + 0x00, 0x00, 0x00, // fragment_offset + 0x00, 0x00, 0x2E, // fragment_length + // ClientHello + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 + // Random + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, // + 0x01, // SessionId length + 0xAA, // SessionId + 0x01, // Cookie length + 0xBB, // Cookie + 0x00, 0x04, // Dtls12CipherSuites length + 0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + 0xC0, 0x2C, // Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + 0x01, // CompressionMethods length + 0x00, // CompressionMethod::Null + ]; + + #[test] + fn message_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(MessageType::default().as_u8(), 0); + assert_eq!(MessageType::default(), MessageType::HelloRequest); + } + + #[test] + fn message_type_wire_roundtrip() { + for message_type in [ + MessageType::HelloRequest, + MessageType::ClientHello, + MessageType::ServerHello, + MessageType::HelloVerifyRequest, + MessageType::NewSessionTicket, + MessageType::Certificate, + MessageType::ServerKeyExchange, + MessageType::CertificateRequest, + MessageType::ServerHelloDone, + MessageType::CertificateVerify, + MessageType::ClientKeyExchange, + MessageType::Finished, + ] { + assert_eq!(MessageType::from_u8(message_type.as_u8()), message_type); + assert!(!message_type.is_unknown()); + } + + let unknown = MessageType::from_u8(0xFF); + assert_eq!(unknown.as_u8(), 0xFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn message_type_debug_stays_enum_like() { + assert_eq!(format!("{:?}", MessageType::ClientHello), "ClientHello"); + assert_eq!(format!("{:?}", MessageType::from_u8(0xFF)), "Unknown(255)"); + } + + #[test] + fn handshake_size() { + let h = Handshake::new( + // ServerHelloDone has a 0 sized body. + MessageType::ServerHelloDone, + 0, + 0, + 0, + 0, + Body::ServerHelloDone, + ); + + let mut v = Buf::new(); + h.serialize(&[], &mut v); + + assert_eq!(v.len(), 12); + } + + #[test] + fn roundtrip() { + let mut serialized = Buf::new(); + + let random = Random::parse(&MESSAGE[14..46]).unwrap().1; + let session_id = SessionId::try_new(&[0xAA]).unwrap(); + let cookie = Cookie::try_new(&[0xBB]).unwrap(); + let mut cipher_suites = ArrayVec::new(); + cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256); + cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384); + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + let client_hello = ClientHello::new( + ProtocolVersion::DTLS1_2, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + ); + + let handshake = Handshake::new( + MessageType::ClientHello, + 0x2E, + 0, + 0, + 0x2E, + Body::ClientHello(client_hello), + ); + + // Serialize and compare to MESSAGE + handshake.serialize(&[], &mut serialized); + assert_eq!(&*serialized, MESSAGE); + + // Parse and compare with original + let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap(); + assert_eq!(parsed, handshake); + + assert!(rest.is_empty()); + } + + #[test] + fn roundtrip_fragment() { + let mut serialized = Buf::new(); + let mut buffer = Buf::new(); + + let random = Random::parse(&MESSAGE[14..46]).unwrap().1; + let session_id = SessionId::try_new(&[0xAA]).unwrap(); + let cookie = Cookie::try_new(&[0xBB]).unwrap(); + let mut cipher_suites = ArrayVec::new(); + cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256); + cipher_suites.push(Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384); + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + let client_hello = ClientHello::new( + ProtocolVersion::DTLS1_2, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + ); + + let handshake = Handshake::new( + MessageType::ClientHello, + 46, + 0, + 0, + 46, + Body::ClientHello(client_hello), + ); + + // Fragment the handshake with size 10 + let fragments: VecDeque<_> = handshake.fragment(10, &mut buffer).collect(); + + // Defragment the fragments + let mut defragmented_buffer = Buf::new(); + let defragmented_handshake = Handshake::defragment( + fragments.iter().map(|h| (h, &buffer[..])), + &mut defragmented_buffer, + None, + None, + ) + .unwrap(); + + // Serialize and compare to MESSAGE + // Save header info and drop handshake to release buffer borrow + let header = defragmented_handshake.header; + drop(defragmented_handshake); + + serialized.push(header.msg_type.as_u8()); + serialized.extend_from_slice(&header.length.to_be_bytes()[1..]); + serialized.extend_from_slice(&header.message_seq.to_be_bytes()); + serialized.extend_from_slice(&header.fragment_offset.to_be_bytes()[1..]); + serialized.extend_from_slice(&header.fragment_length.to_be_bytes()[1..]); + serialized.extend_from_slice(&defragmented_buffer[..header.length as usize]); + assert_eq!(&*serialized, MESSAGE); + + // Parse and compare with original + let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap(); + assert_eq!(parsed, handshake); + + assert!(rest.is_empty()); + } + + #[test] + fn failed_defragment_parse_discards_candidate_without_writing_transcript() { + let mut body = MESSAGE[12..].to_vec(); + body[38] = 0; + body[39] = 3; + + let handshake = Handshake::new( + MessageType::ClientHello, + body.len() as u32, + 0, + 0, + body.len() as u32, + Body::Fragment(0..body.len()), + ); + + let mut defragmented_buffer = Buf::new(); + let mut transcript = Buf::new(); + let result = Handshake::defragment( + std::iter::once((&handshake, body.as_slice())), + &mut defragmented_buffer, + None, + Some(&mut transcript), + ); + + assert!(result.is_err()); + assert!(handshake.is_handled()); + assert!(transcript.is_empty()); + } + + #[test] + fn defragment_stops_at_cross_sequence_fragment() { + let body = &MESSAGE[12..]; + let mut source = body.to_vec(); + source.push(0); + + let handshake = Handshake::new( + MessageType::ClientHello, + body.len() as u32, + 0, + 0, + body.len() as u32, + Body::Fragment(0..body.len()), + ); + let decoy = Handshake::new( + MessageType::ClientHello, + body.len() as u32 + 1, + 1, + body.len() as u32, + 1, + Body::Fragment(body.len()..body.len() + 1), + ); + + let mut defragmented_buffer = Buf::new(); + let defragmented_handshake = Handshake::defragment( + [(&handshake, source.as_slice()), (&decoy, source.as_slice())].into_iter(), + &mut defragmented_buffer, + None, + None, + ) + .unwrap(); + + assert_eq!(defragmented_handshake.header.message_seq, 0); + assert_eq!(&defragmented_buffer[..body.len()], body); + assert!(handshake.is_handled()); + assert!(!decoy.is_handled()); + } + + #[test] + fn known_body_rejects_trailing_bytes() { + let body = [0]; + let handshake = Handshake::new( + MessageType::HelloRequest, + body.len() as u32, + 0, + 0, + body.len() as u32, + Body::Fragment(0..body.len()), + ); + + let mut defragmented_buffer = Buf::new(); + let mut transcript = Buf::new(); + let result = Handshake::defragment( + std::iter::once((&handshake, body.as_slice())), + &mut defragmented_buffer, + None, + Some(&mut transcript), + ); + + assert!(result.is_err()); + assert!(handshake.is_handled()); + assert!(transcript.is_empty()); + } +} diff --git a/third_party/dimpl/src/dtls12/message/hello_verify.rs b/third_party/dimpl/src/dtls12/message/hello_verify.rs new file mode 100644 index 0000000..a27f794 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/hello_verify.rs @@ -0,0 +1,93 @@ +use super::ProtocolVersion; +use super::id::Cookie; +use crate::buffer::Buf; +use nom::IResult; +use nom::error::{Error, ErrorKind}; + +#[derive(Debug, PartialEq, Eq)] +pub struct HelloVerifyRequest { + pub server_version: ProtocolVersion, + pub cookie: Cookie, +} + +impl HelloVerifyRequest { + pub fn new(server_version: ProtocolVersion, cookie: Cookie) -> Self { + HelloVerifyRequest { + server_version, + cookie, + } + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], HelloVerifyRequest> { + let (input, server_version) = ProtocolVersion::parse(input)?; + let (input, cookie) = Cookie::parse(input)?; + + if cookie.is_empty() { + return Err(nom::Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok(( + input, + HelloVerifyRequest { + server_version, + cookie, + }, + )) + } + + pub fn serialize(&self, output: &mut Buf) { + output.extend_from_slice(&self.server_version.as_u16().to_be_bytes()); + output.push(self.cookie.len() as u8); + output.extend_from_slice(&self.cookie); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 + 0x01, // Cookie length + 0xBB, // Cookie + ]; + + #[test] + fn roundtrip() { + let cookie = Cookie::try_new(&[0xBB]).unwrap(); + + let hello_verify_request = HelloVerifyRequest::new(ProtocolVersion::DTLS1_2, cookie); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + hello_verify_request.serialize(&mut serialized); + assert_eq!(&*serialized, MESSAGE); + + // Parse and compare with original + let (rest, parsed) = HelloVerifyRequest::parse(&serialized).unwrap(); + assert_eq!(parsed, hello_verify_request); + + assert!(rest.is_empty()); + } + + #[test] + fn empty_cookie() { + let message: &[u8] = &[ + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 + 0x00, // Cookie length (0, which is empty) + ]; + + let result = HelloVerifyRequest::parse(message); + assert!(result.is_err()); + } + + #[test] + fn cookie_too_long() { + let mut message = MESSAGE.to_vec(); + message[2] = 0xFF; // Cookie length (255, which is too long) + + let result = HelloVerifyRequest::parse(&message); + assert!(result.is_err()); + } +} diff --git a/third_party/dimpl/src/dtls12/message/id.rs b/third_party/dimpl/src/dtls12/message/id.rs new file mode 100644 index 0000000..2580544 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/id.rs @@ -0,0 +1,128 @@ +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u8; +use nom::{Err, IResult}; +use std::fmt; +use std::ops::Deref; + +pub struct InvalidLength(&'static str, IdType, usize); + +impl fmt::Debug for InvalidLength { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self) + } +} + +impl std::error::Error for InvalidLength {} + +impl fmt::Display for InvalidLength { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.1 { + IdType::Fixed(len) => write!( + f, + "Incorrect fixed ID ({}) length: {} should be {}", + self.0, self.2, len + ), + IdType::Variable(min, max) => write!( + f, + "Incorrect variable ID ({}) length: {} <= {} <= {}", + self.0, min, self.2, max, + ), + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum IdType { + #[allow(unused)] + Fixed(usize), + Variable(usize, usize), +} + +macro_rules! var_array { + ($name:ident, $min:expr, $max:expr) => { + #[derive(Clone, Copy)] + pub struct $name([u8; $max], usize); + + impl $name { + pub fn try_new(data: &[u8]) -> Result { + #[allow(unused_comparisons)] + if data.len() < $min || data.len() > $max { + return Err(InvalidLength( + stringify!($name), + IdType::Variable($min, $max), + data.len(), + )); + } + let mut array = [0; $max]; + array[..data.len()].copy_from_slice(data); + Ok($name(array, data.len())) + } + + pub fn empty() -> Self { + if $min > 0 { + panic!("{}::empty() is not valid", stringify!($name)); + } + Self([0; $max], 0) + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], Self> { + let (input, len) = be_u8(input)?; + if len < $min as u8 || len > $max as u8 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + let (input, data) = take(len as usize)(input)?; + // unwrap() is ok because we check the size above. + let instance = Self::try_new(data).unwrap(); + Ok((input, instance)) + } + } + + impl fmt::Debug for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self) + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}({:02x?})", stringify!($name), &self.0[..self.1]) + } + } + + impl PartialEq for $name { + fn eq(&self, other: &Self) -> bool { + self.deref() == other.deref() + } + } + + impl Eq for $name {} + + impl Deref for $name { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0[..self.1] + } + } + + impl<'a> TryFrom<&'a [u8]> for $name { + type Error = InvalidLength; + + fn try_from(value: &'a [u8]) -> Result { + Self::try_new(value) + } + } + + impl<'a> TryFrom<&'a str> for $name { + type Error = InvalidLength; + + fn try_from(value: &'a str) -> Result { + Self::try_new(value.as_bytes()) + } + } + }; +} + +var_array!(SessionId, 0, 32); +var_array!(Cookie, 0, 255); diff --git a/third_party/dimpl/src/dtls12/message/mod.rs b/third_party/dimpl/src/dtls12/message/mod.rs new file mode 100644 index 0000000..1d254aa --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/mod.rs @@ -0,0 +1,465 @@ +//! Low-level DTLS message parsing and serialization types. +//! +//! This module exposes enums and helpers used by the public API for negotiating +//! cipher suites and signature algorithms, as well as parsing wire formats. +//! Only the public items are documented here; the rest are internal helpers. + +mod certificate; +mod certificate_request; +mod certificate_verify; +mod client_hello; +mod client_key_exchange; +mod digitally_signed; +mod extension; +mod extensions; +mod finished; +mod handshake; +mod hello_verify; +mod id; +mod named_group; +mod record; +mod server_hello; +mod server_key_exchange; +mod wrapped; + +use std::fmt; + +use arrayvec::ArrayVec; +pub use certificate::Certificate; +pub use certificate_request::CertificateRequest; +pub use certificate_verify::CertificateVerify; +pub use client_hello::ClientHello; +pub use client_key_exchange::{ClientKeyExchange, ClientPskKeys, ExchangeKeys}; +pub use digitally_signed::DigitallySigned; +pub use extension::{Extension, ExtensionType}; +pub use extensions::ec_point_formats::ECPointFormatsExtension; +pub use extensions::signature_algorithms::SignatureAlgorithmsExtension; +pub use extensions::supported_groups::SupportedGroupsExtension; +pub use extensions::use_srtp::{SrtpProfileId, SrtpProfileVec, UseSrtpExtension}; +pub use finished::Finished; +pub use handshake::{Body, Handshake, Header, MessageType}; +pub use hello_verify::HelloVerifyRequest; +pub use id::{Cookie, SessionId}; +pub use named_group::CurveType; +pub use record::DTLSRecord; + +// Re-export shared types for backwards compatibility +pub use crate::types::{ + CompressionMethod, ContentType, HashAlgorithm, NamedGroup, NamedGroupVec, ProtocolVersion, + Random, Sequence, SignatureAlgorithm, +}; +pub use server_hello::ServerHello; +pub use server_key_exchange::{PskParams, ServerKeyExchange, ServerKeyExchangeParams}; +pub use wrapped::{Asn1Cert, DistinguishedName}; + +use nom::IResult; +use nom::number::complete::{be_u8, be_u16}; + +pub type CipherSuiteVec = ArrayVec; + +/// Supported TLS 1.2 cipher suites for DTLS. +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Dtls12CipherSuite(u16); + +impl Dtls12CipherSuite { + /// ECDHE with ECDSA authentication, AES-256-GCM, SHA-384. + pub const ECDHE_ECDSA_AES256_GCM_SHA384: Self = Self(0xC02C); + /// ECDHE with ECDSA authentication, AES-128-GCM, SHA-256. + pub const ECDHE_ECDSA_AES128_GCM_SHA256: Self = Self(0xC02B); + /// ECDHE with ECDSA authentication, ChaCha20-Poly1305, SHA-256. + pub const ECDHE_ECDSA_CHACHA20_POLY1305_SHA256: Self = Self(0xCCA9); + /// PSK with AES-128-CCM-8 (8-byte tag), SHA-256. + pub const PSK_AES128_CCM_8: Self = Self(0xC0A8); + + /// Convert the 16-bit IANA value to a `Dtls12CipherSuite`. + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + /// Return the 16-bit IANA value for this cipher suite. + pub const fn as_u16(&self) -> u16 { + self.0 + } + + /// Returns true if this is not a known DTLS 1.2 cipher suite wire value. + pub const fn is_unknown(&self) -> bool { + !matches!(*self, Self(0xC02B..=0xC02C | 0xC0A8 | 0xCCA9)) + } + + /// Parse a `Dtls12CipherSuite` from network byte order. + pub fn parse(input: &[u8]) -> IResult<&[u8], Dtls12CipherSuite> { + let (input, value) = be_u16(input)?; + Ok((input, Dtls12CipherSuite::from_u16(value))) + } + + /// Length in bytes of verify_data for Finished MACs. + pub fn verify_data_length(&self) -> usize { + match *self { + // AES-GCM suites + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 + | Dtls12CipherSuite::PSK_AES128_CCM_8 => 12, + + _ => 12, // Default length for unknown cipher suites + } + } + + /// The key exchange algorithm family for this cipher suite. + pub fn as_key_exchange_algorithm(&self) -> KeyExchangeAlgorithm { + match *self { + // All ECDHE ciphers + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => { + KeyExchangeAlgorithm::EECDH + } + + Dtls12CipherSuite::PSK_AES128_CCM_8 => KeyExchangeAlgorithm::PSK, + + _ => KeyExchangeAlgorithm::Unknown, + } + } + + /// Whether this cipher suite uses ECC-based key exchange. + pub fn has_ecc(&self) -> bool { + matches!( + *self, + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 + ) + } + + /// Whether this cipher suite uses PSK (Pre-Shared Key) key exchange. + pub fn is_psk(&self) -> bool { + matches!(*self, Dtls12CipherSuite::PSK_AES128_CCM_8) + } + + /// All supported cipher suites in server preference order. + pub const fn all() -> &'static [Dtls12CipherSuite; 4] { + &[ + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384, + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, + Dtls12CipherSuite::PSK_AES128_CCM_8, + ] + } + + /// Cipher suites compatible with a given certificate's signature algorithm. + pub fn compatible_with_certificate( + cert_type: SignatureAlgorithm, + ) -> &'static [Dtls12CipherSuite; 3] { + match cert_type { + SignatureAlgorithm::ECDSA => &[ + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384, + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, + ], + _ => panic!("Need either RSA or ECDSA certificate"), + } + } + + fn need_encrypt_then_mac(&self) -> bool { + // We do not support and ciphers such as: + // ECDHE-RSA-AES128-SHA + // ECDHE-RSA-AES256-SHA + // DHE-RSA-AES128-SHA256 + false + } + + /// The hash algorithm used by this cipher suite. + pub fn hash_algorithm(&self) -> HashAlgorithm { + match *self { + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 => HashAlgorithm::SHA384, + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 + | Dtls12CipherSuite::PSK_AES128_CCM_8 => HashAlgorithm::SHA256, + _ => HashAlgorithm::UNKNOWN_DERIVED, + } + } + + /// The signature algorithm associated with the suite's key exchange. + /// + /// Returns `None` for PSK cipher suites (no signature authentication). + pub fn signature_algorithm(&self) -> Option { + match *self { + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + | Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => { + Some(SignatureAlgorithm::ECDSA) + } + Dtls12CipherSuite::PSK_AES128_CCM_8 => None, + _ => Some(SignatureAlgorithm::UNKNOWN_DERIVED), + } + } + + /// Returns true if this cipher suite is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// Supported DTLS 1.2 cipher suites in server preference order. + pub const fn supported() -> &'static [Dtls12CipherSuite; 4] { + Self::all() + } +} + +impl fmt::Debug for Dtls12CipherSuite { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 => { + f.write_str("ECDHE_ECDSA_AES256_GCM_SHA384") + } + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 => { + f.write_str("ECDHE_ECDSA_AES128_GCM_SHA256") + } + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => { + f.write_str("ECDHE_ECDSA_CHACHA20_POLY1305_SHA256") + } + Dtls12CipherSuite::PSK_AES128_CCM_8 => f.write_str("PSK_AES128_CCM_8"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +pub type CompressionMethodVec = + ArrayVec; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[allow(non_camel_case_types)] +#[allow(clippy::upper_case_acronyms)] +pub enum KeyExchangeAlgorithm { + EECDH, + PSK, + Unknown, +} + +pub type CertificateTypeVec = + ArrayVec; + +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct ClientCertificateType(u8); + +impl ClientCertificateType { + pub const RSA_SIGN: Self = Self(1); + pub const DSS_SIGN: Self = Self(2); + pub const RSA_FIXED_DH: Self = Self(3); + pub const DSS_FIXED_DH: Self = Self(4); + pub const RSA_EPHEMERAL_DH: Self = Self(5); + pub const DSS_EPHEMERAL_DH: Self = Self(6); + pub const FORTEZZA_DMS: Self = Self(20); + pub const ECDSA_SIGN: Self = Self(64); + + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + /// Returns true if this certificate type is supported by this implementation. + /// Currently only ECDSA_SIGN is supported. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// Supported client certificate types. + pub const fn supported() -> &'static [ClientCertificateType; 1] { + &[ClientCertificateType::ECDSA_SIGN] + } + + pub const fn as_u8(&self) -> u8 { + self.0 + } + + const fn is_unknown(&self) -> bool { + !matches!(*self, Self(1..=6 | 20 | 64)) + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], ClientCertificateType> { + let (input, value) = be_u8(input)?; + Ok((input, ClientCertificateType::from_u8(value))) + } +} + +impl fmt::Debug for ClientCertificateType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unknown() { + return f.debug_tuple("Unknown").field(&self.0).finish(); + } + + let name = match *self { + ClientCertificateType::RSA_SIGN => "RSA_SIGN", + ClientCertificateType::DSS_SIGN => "DSS_SIGN", + ClientCertificateType::RSA_FIXED_DH => "RSA_FIXED_DH", + ClientCertificateType::DSS_FIXED_DH => "DSS_FIXED_DH", + ClientCertificateType::RSA_EPHEMERAL_DH => "RSA_EPHEMERAL_DH", + ClientCertificateType::DSS_EPHEMERAL_DH => "DSS_EPHEMERAL_DH", + ClientCertificateType::FORTEZZA_DMS => "FORTEZZA_DMS", + ClientCertificateType::ECDSA_SIGN => "ECDSA_SIGN", + _ => unreachable!("known DTLS 1.2 client certificate type missing Debug label"), + }; + + f.write_str(name) + } +} + +// SignatureAlgorithm and HashAlgorithm are now in crate::types + +pub type SignatureAndHashAlgorithmVec = + ArrayVec; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SignatureAndHashAlgorithm { + pub hash: HashAlgorithm, + pub signature: SignatureAlgorithm, +} + +impl SignatureAndHashAlgorithm { + pub const fn new(hash: HashAlgorithm, signature: SignatureAlgorithm) -> Self { + SignatureAndHashAlgorithm { hash, signature } + } + + pub fn from_u16(value: u16) -> Self { + let hash = HashAlgorithm::from_u8((value >> 8) as u8); + let signature = SignatureAlgorithm::from_u8(value as u8); + SignatureAndHashAlgorithm { hash, signature } + } + + pub fn as_u16(&self) -> u16 { + ((self.hash.as_u8() as u16) << 8) | (self.signature.as_u8() as u16) + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAndHashAlgorithm> { + let (input, value) = be_u16(input)?; + Ok((input, SignatureAndHashAlgorithm::from_u16(value))) + } + + /// All recognized signature+hash combinations. + #[allow(dead_code)] + pub const fn all() -> &'static [SignatureAndHashAlgorithm; 4] { + const ALL: &[SignatureAndHashAlgorithm; 4] = &[ + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA), + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA), + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA), + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::RSA), + ]; + + ALL + } + + /// Supported signature+hash combinations. + pub const fn supported() -> &'static [SignatureAndHashAlgorithm; 2] { + const SUPPORTED: &[SignatureAndHashAlgorithm; 2] = &[ + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA), + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA), + ]; + + SUPPORTED + } + + /// Returns true if this signature+hash combination is supported. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rsa_signature_algorithms_are_recognized_but_not_supported() { + let rsa_sha256 = + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA); + + assert!(SignatureAndHashAlgorithm::all().contains(&rsa_sha256)); + assert!(!rsa_sha256.is_supported()); + assert_eq!(SignatureAndHashAlgorithm::supported().len(), 2); + } + + #[test] + fn dtls12_cipher_suite_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(Dtls12CipherSuite::default().as_u16(), 0); + assert!(Dtls12CipherSuite::default().is_unknown()); + } + + #[test] + fn dtls12_cipher_suite_wire_roundtrip() { + for suite in Dtls12CipherSuite::all() { + assert_eq!(Dtls12CipherSuite::from_u16(suite.as_u16()), *suite); + assert!(!suite.is_unknown()); + } + + let unknown = Dtls12CipherSuite::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn dtls12_cipher_suite_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256), + "ECDHE_ECDSA_AES128_GCM_SHA256" + ); + assert_eq!( + format!("{:?}", Dtls12CipherSuite::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn client_certificate_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(ClientCertificateType::default().as_u8(), 0); + assert!(ClientCertificateType::default().is_unknown()); + } + + #[test] + fn client_certificate_type_wire_roundtrip() { + for certificate_type in [ + ClientCertificateType::RSA_SIGN, + ClientCertificateType::DSS_SIGN, + ClientCertificateType::RSA_FIXED_DH, + ClientCertificateType::DSS_FIXED_DH, + ClientCertificateType::RSA_EPHEMERAL_DH, + ClientCertificateType::DSS_EPHEMERAL_DH, + ClientCertificateType::FORTEZZA_DMS, + ClientCertificateType::ECDSA_SIGN, + ] { + assert_eq!( + ClientCertificateType::from_u8(certificate_type.as_u8()), + certificate_type + ); + assert!(!certificate_type.is_unknown()); + } + + let unknown = ClientCertificateType::from_u8(0xFF); + assert_eq!(unknown.as_u8(), 0xFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn client_certificate_type_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", ClientCertificateType::ECDSA_SIGN), + "ECDSA_SIGN" + ); + assert_eq!( + format!("{:?}", ClientCertificateType::from_u8(0xFF)), + "Unknown(255)" + ); + } + + #[test] + fn unknown_dtls12_cipher_suite_uses_internal_derived_markers() { + let unknown = Dtls12CipherSuite::from_u16(0xFFFF); + assert!(unknown.hash_algorithm().is_unknown()); + assert!( + unknown + .signature_algorithm() + .is_some_and(|s| s.is_unknown()) + ); + } +} diff --git a/third_party/dimpl/src/dtls12/message/named_group.rs b/third_party/dimpl/src/dtls12/message/named_group.rs new file mode 100644 index 0000000..5e715dd --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/named_group.rs @@ -0,0 +1,94 @@ +//! DTLS 1.2 curve type definitions. +//! +//! NamedGroup is now in crate::types as it's shared between DTLS versions. +//! CurveType is DTLS 1.2 specific (used in ServerKeyExchange). + +use nom::IResult; +use nom::number::complete::be_u8; +use std::fmt; + +/// Curve type for ECDH parameters in DTLS 1.2. +/// +/// This is specific to DTLS 1.2's ServerKeyExchange message format. +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct CurveType(u8); + +#[allow(non_upper_case_globals)] +impl CurveType { + /// Explicit prime curve parameters. + pub const ExplicitPrime: Self = Self(1); + /// Explicit characteristic-2 curve parameters. + pub const ExplicitChar2: Self = Self(2); + /// Named curve (the common case). + pub const NamedCurve: Self = Self(3); + + /// Convert a u8 value to a `CurveType`. + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + /// Convert this `CurveType` to its u8 value. + pub const fn as_u8(&self) -> u8 { + self.0 + } + + const fn is_unknown(&self) -> bool { + !matches!(*self, Self(1..=3)) + } + + /// Parse a `CurveType` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], CurveType> { + let (input, value) = be_u8(input)?; + Ok((input, CurveType::from_u8(value))) + } +} + +impl fmt::Debug for CurveType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unknown() { + return f.debug_tuple("Unknown").field(&self.0).finish(); + } + + let name = match *self { + CurveType::ExplicitPrime => "ExplicitPrime", + CurveType::ExplicitChar2 => "ExplicitChar2", + CurveType::NamedCurve => "NamedCurve", + _ => unreachable!("known DTLS 1.2 curve type missing Debug label"), + }; + + f.write_str(name) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn curve_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + } + + #[test] + fn curve_type_wire_roundtrip() { + for curve_type in [ + CurveType::ExplicitPrime, + CurveType::ExplicitChar2, + CurveType::NamedCurve, + ] { + assert_eq!(CurveType::from_u8(curve_type.as_u8()), curve_type); + assert!(!curve_type.is_unknown()); + } + + let unknown = CurveType::from_u8(0xFF); + assert_eq!(unknown.as_u8(), 0xFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn curve_type_debug_stays_enum_like() { + assert_eq!(format!("{:?}", CurveType::NamedCurve), "NamedCurve"); + assert_eq!(format!("{:?}", CurveType::from_u8(0xFF)), "Unknown(255)"); + } +} diff --git a/third_party/dimpl/src/dtls12/message/record.rs b/third_party/dimpl/src/dtls12/message/record.rs new file mode 100644 index 0000000..896e0af --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/record.rs @@ -0,0 +1,258 @@ +//! DTLS 1.2 record layer types. +//! +//! ContentType and Sequence are now in crate::types as they're shared between DTLS versions. + +use std::fmt; +use std::ops::Range; + +use super::ProtocolVersion; +use crate::buffer::Buf; +use crate::types::{ContentType, Sequence}; +use crate::util::be_u48; +use nom::bytes::complete::take; +use nom::number::complete::be_u16; +use nom::{Err, IResult}; + +/// DTLS 1.2 record structure. +#[derive(PartialEq, Eq, Default)] +pub struct DTLSRecord { + /// The content type of this record. + pub content_type: ContentType, + /// The protocol version. + pub version: ProtocolVersion, + /// The epoch and sequence number. + pub sequence: Sequence, + /// The length of the fragment. + pub length: u16, + /// The range of the fragment in the source buffer. + pub fragment_range: Range, +} + +impl DTLSRecord { + /// DTLS record header length: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) + pub const HEADER_LEN: usize = 13; + + /// Length of the explicit nonce prefix in DTLS 1.2 AES-GCM records. + pub const EXPLICIT_NONCE_LEN: usize = 8; + + /// Byte offset in the record header where the 2-byte length field is + pub const LENGTH_OFFSET: Range = 11..13; + + /// Parse a DTLS record from the input buffer. + pub fn parse( + input: &[u8], + base_offset: usize, + skip_offset: usize, + ) -> IResult<&[u8], DTLSRecord> { + let original_input = input; + let (input, content_type) = ContentType::parse(input)?; // u8 + let (input, version) = ProtocolVersion::parse(input)?; // u16 + + // Accept DTLS 1.0 or 1.2 in record layer per RFC 6347 + // DTLS 1.0 (0xFEFF) is often used in record layer during handshake for compatibility + // The actual protocol version is negotiated in the handshake messages + match version { + ProtocolVersion::DTLS1_0 | ProtocolVersion::DTLS1_2 => { + // Valid DTLS versions for record layer + } + _ => { + return Err(Err::Failure(nom::error::Error::new( + input, + nom::error::ErrorKind::Tag, + ))); + } + } + + let (input, epoch) = be_u16(input)?; // u16 + + // Epoch 0 records are plaintext in DTLS 1.2. Reject plaintext + // ApplicationData before record protection is active, and only accept + // the epoch-0 content types this implementation supports. + if epoch == 0 { + match content_type { + ContentType::ChangeCipherSpec | ContentType::Alert | ContentType::Handshake => {} + _ => { + return Err(Err::Failure(nom::error::Error::new( + input, + nom::error::ErrorKind::Tag, + ))); + } + } + } + let (input, sequence_number) = be_u48(input)?; // u48 + let (input, length) = be_u16(input)?; // u16 + + // When encrypted, skip_offset is 0 and this has the explicit nonce. + // When decrypted, skip_offset is > 0 to skip the explicit nonce. + let input = &input[skip_offset..]; + + let (rest, fragment_slice) = take(length as usize)(input)?; + + // Calculate absolute range in root buffer + // fragment_slice is already offset from original_input by all the header bytes and skip_offset + let relative_offset = fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + fragment_slice.len(); + + let sequence = Sequence { + epoch, + sequence_number, + }; + + Ok(( + rest, + DTLSRecord { + content_type, + version, + sequence, + length, + fragment_range: start..end, + }, + )) + } + + /// Get the fragment data from the source buffer. + pub fn fragment<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.fragment_range.clone()] + } + + /// Serialize this record to the output buffer. + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.push(self.content_type.as_u8()); + self.version.serialize(output); + output.extend_from_slice(&self.sequence.epoch.to_be_bytes()); + output.extend_from_slice(&self.sequence.sequence_number.to_be_bytes()[2..]); + output.extend_from_slice(&self.length.to_be_bytes()); + output.extend_from_slice(self.fragment(buf)); + } + + /// Get the explicit nonce from the fragment using the requested length. + pub fn nonce_with_len<'a>(&self, buf: &'a [u8], len: usize) -> &'a [u8] { + let fragment = self.fragment(buf); + &fragment[..len] + } + + /// Get the explicit nonce from the fragment (AES-GCM default). + pub fn nonce<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + self.nonce_with_len(buf, Self::EXPLICIT_NONCE_LEN) + } +} + +impl fmt::Debug for DTLSRecord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DTLSRecord") + .field("content_type", &self.content_type) + .field("version", &self.version) + .field("sequence", &self.sequence) + .field("length", &self.length) + .field("fragment_range", &self.fragment_range) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const RECORD: &[u8] = &[ + 0x16, // ContentType::Handshake + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 + 0x00, 0x01, // epoch + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // sequence_number + 0x00, 0x10, // length + // fragment + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, + ]; + + #[test] + fn roundtrip() { + // Parse the record with base_offset 0, skip_offset 0 + let (rest, parsed) = DTLSRecord::parse(RECORD, 0, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to RECORD + let mut serialized = Buf::new(); + parsed.serialize(RECORD, &mut serialized); + assert_eq!(&*serialized, RECORD); + } + + #[test] + fn epoch_0_content_type_whitelist() { + // Epoch 0 is plaintext (RFC 6347 §4.1: epoch starts at 0, incremented by each CCS). + // Only ChangeCipherSpec(20), Alert(21), and Handshake(22) can legitimately + // appear unencrypted. ApplicationData in epoch 0 is rejected at parse time. + + fn build_epoch_0_record(content_type: u8) -> Vec { + vec![ + content_type, // ContentType + 0xFE, + 0xFD, // version: DTLS 1.2 + 0x00, + 0x00, // epoch: 0 (plaintext) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, // sequence_number + 0x00, + 0x02, // length: 2 + 0xAA, + 0xBB, // fragment payload + ] + } + + // ALLOWED: ChangeCipherSpec (20) + let ccs = build_epoch_0_record(0x14); + assert!( + DTLSRecord::parse(&ccs, 0, 0).is_ok(), + "ChangeCipherSpec should be allowed in epoch 0" + ); + + // ALLOWED: Alert (21) + let alert = build_epoch_0_record(0x15); + assert!( + DTLSRecord::parse(&alert, 0, 0).is_ok(), + "Alert should be allowed in epoch 0" + ); + + // ALLOWED: Handshake (22) + let handshake = build_epoch_0_record(0x16); + assert!( + DTLSRecord::parse(&handshake, 0, 0).is_ok(), + "Handshake should be allowed in epoch 0" + ); + + // REJECTED: ApplicationData (23) + let app_data = build_epoch_0_record(0x17); + assert!( + DTLSRecord::parse(&app_data, 0, 0).is_err(), + "ApplicationData must be rejected in epoch 0" + ); + + // REJECTED: Ack (26) - valid in DTLS 1.3 but not DTLS 1.2 + let ack = build_epoch_0_record(0x1A); + assert!( + DTLSRecord::parse(&ack, 0, 0).is_err(), + "Ack must be rejected in DTLS 1.2 epoch 0" + ); + + // REJECTED: Unknown ContentType (0x99) + let unknown = build_epoch_0_record(0x99); + assert!( + DTLSRecord::parse(&unknown, 0, 0).is_err(), + "Unknown ContentType must be rejected in epoch 0" + ); + + // Verify that epoch 1+ allows ApplicationData (no whitelist restriction) + let mut epoch_1_app_data = build_epoch_0_record(0x17); + epoch_1_app_data[3] = 0x00; // epoch high byte + epoch_1_app_data[4] = 0x01; // epoch low byte = 1 + assert!( + DTLSRecord::parse(&epoch_1_app_data, 0, 0).is_ok(), + "ApplicationData should be allowed in epoch 1+" + ); + } +} diff --git a/third_party/dimpl/src/dtls12/message/server_hello.rs b/third_party/dimpl/src/dtls12/message/server_hello.rs new file mode 100644 index 0000000..5ae0c6c --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/server_hello.rs @@ -0,0 +1,256 @@ +use super::extension::ExtensionVec; +use super::extensions::use_srtp::{SrtpProfileId, UseSrtpExtension}; +use super::{CompressionMethod, Dtls12CipherSuite, Extension, ExtensionType}; +use super::{ProtocolVersion, Random, SessionId}; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::error::{Error, ErrorKind}; +use nom::{IResult, bytes::complete::take, number::complete::be_u16}; + +#[derive(Debug, PartialEq, Eq)] +pub struct ServerHello { + pub server_version: ProtocolVersion, + pub random: Random, + pub session_id: SessionId, + pub cipher_suite: Dtls12CipherSuite, + pub compression_method: CompressionMethod, + pub extensions: Option, +} + +impl ServerHello { + pub fn new( + server_version: ProtocolVersion, + random: Random, + session_id: SessionId, + cipher_suite: Dtls12CipherSuite, + compression_method: CompressionMethod, + extensions: Option, + ) -> Self { + ServerHello { + server_version, + random, + session_id, + cipher_suite, + compression_method, + extensions, + } + } + + /// Add extensions to ServerHello using a builder-style API, mirroring ClientHello::with_extensions + /// + /// - Uses the provided buffer to stage extension bytes and then stores Range references + /// - Includes UseSRTP if a profile is provided + /// - Includes Extended Master Secret if the flag is set + pub fn with_extensions(mut self, buf: &mut Buf, srtp_profile: Option) -> Self { + // Clear the buffer and collect extension byte ranges + buf.clear(); + + let mut ranges: ArrayVec< + (ExtensionType, usize, usize), + { ExtensionType::supported().len() }, + > = ArrayVec::new(); + + // UseSRTP (if negotiated) + if let Some(pid) = srtp_profile { + let start = buf.len(); + let mut profiles = ArrayVec::new(); + profiles.push(pid); + let ext = UseSrtpExtension::new(profiles, ArrayVec::new()); + ext.serialize(buf); + ranges.push((ExtensionType::UseSrtp, start, buf.len())); + } + + // Extended Master Secret (mandatory) + let start = buf.len(); + ranges.push((ExtensionType::ExtendedMasterSecret, start, start)); + + // Renegotiation Info (RFC 5746) - empty for initial handshake + let start = buf.len(); + buf.push(0); // renegotiated_connection length = 0 + ranges.push((ExtensionType::RenegotiationInfo, start, buf.len())); + + let mut extensions = ExtensionVec::new(); + for (t, s, e) in ranges { + extensions.push(Extension { + extension_type: t, + extension_data_range: s..e, + }); + } + self.extensions = Some(extensions); + + self + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ServerHello> { + let original_input = input; + let (input, server_version) = ProtocolVersion::parse(input)?; + let (input, random) = Random::parse(input)?; + let (input, session_id) = SessionId::parse(input)?; + let (input, cipher_suite) = Dtls12CipherSuite::parse(input)?; + let (input, compression_method) = CompressionMethod::parse(input)?; + + // Parse extensions if there are any bytes left + let (input, extensions) = if !input.is_empty() { + // Check if we have enough bytes to read the extensions length (2 bytes) + if input.len() < 2 { + return Err(Err::Failure(Error::new(input, ErrorKind::Eof))); + } + let (input, extensions_len) = be_u16(input)?; + + // Check if we have enough bytes to read the extensions data + if input.len() < extensions_len as usize { + return Err(Err::Failure(Error::new(input, ErrorKind::Eof))); + } + + if extensions_len > 0 { + let (rest, input_ext) = take(extensions_len)(input)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + let consumed_to_ext_data = + input_ext.as_ptr() as usize - original_input.as_ptr() as usize; + let ext_base_offset = base_offset + consumed_to_ext_data; + + // Parse extensions manually to pass base_offset, filtering unknown types + let mut extensions_vec = ExtensionVec::new(); + let mut current_input = input_ext; + let mut current_offset = ext_base_offset; + while !current_input.is_empty() { + let before_len = current_input.len(); + let (new_rest, ext) = Extension::parse(current_input, current_offset)?; + let parsed_len = before_len - new_rest.len(); + current_offset += parsed_len; + // Only keep supported extension types + if ext.extension_type.is_supported() { + if extensions_vec + .iter() + .any(|existing| existing.extension_type == ext.extension_type) + { + return Err(Err::Failure(Error::new( + current_input, + ErrorKind::LengthValue, + ))); + } + extensions_vec.try_push(ext).map_err(|_| { + Err::Failure(Error::new(current_input, ErrorKind::LengthValue)) + })?; + } + current_input = new_rest; + } + (rest, Some(extensions_vec)) + } else { + (input, None) + } + } else { + (input, None) + }; + + Ok(( + input, + ServerHello { + server_version, + random, + session_id, + cipher_suite, + compression_method, + extensions, + }, + )) + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.server_version.as_u16().to_be_bytes()); + self.random.serialize(output); + output.push(self.session_id.len() as u8); + output.extend_from_slice(&self.session_id); + output.extend_from_slice(&self.cipher_suite.as_u16().to_be_bytes()); + output.push(self.compression_method.as_u8()); + if let Some(extensions) = &self.extensions { + // Calculate total extensions length according to spec: + // For each extension: type (2) + length (2) + data + let mut extensions_len = 0; + for ext in extensions.iter() { + let ext_data = ext.extension_data(source_buf); + extensions_len += 2 + 2 + ext_data.len(); + } + + // Write extensions length + output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + // Write each extension + for ext in extensions { + ext.serialize(source_buf, output); + } + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 + // Random + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, // + 0x01, // SessionId length + 0xAA, // SessionId + 0xC0, 0x2B, // Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 + 0x00, // CompressionMethod::Null + 0x00, 0x0C, // Extensions length (12 bytes total: 2 type + 2 length + 8 data) + 0x00, 0x0A, // ExtensionType::SupportedGroups + 0x00, 0x08, // Extension data length (8 bytes) + 0x00, 0x06, // Extension data + 0x00, 0x17, // NamedGroup::Secp256r1 + 0x00, 0x18, // NamedGroup::Secp384r1 + 0x00, 0x19, // NamedGroup::Secp521r1 + ]; + + #[test] + fn roundtrip() { + // Parse the message first to get the Extension with proper ranges + let (rest, parsed) = ServerHello::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } + + #[test] + fn session_id_too_long() { + let mut message = MESSAGE.to_vec(); + message[34] = 0x21; // SessionId length (33, which is too long) + + let result = ServerHello::parse(&message, 0); + assert!(result.is_err()); + } + + #[test] + fn duplicate_supported_extensions_are_rejected() { + for count in [2, 9] { + let mut message = MESSAGE[..39].to_vec(); + message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); + for _ in 0..count { + message + .extend_from_slice(&ExtensionType::ExtendedMasterSecret.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = ServerHello::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "duplicate supported extensions should fail with LengthValue" + ); + } + } +} diff --git a/third_party/dimpl/src/dtls12/message/server_key_exchange.rs b/third_party/dimpl/src/dtls12/message/server_key_exchange.rs new file mode 100644 index 0000000..cc70dee --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/server_key_exchange.rs @@ -0,0 +1,250 @@ +use super::{CurveType, DigitallySigned, KeyExchangeAlgorithm, NamedGroup}; +use crate::buffer::Buf; +use nom::Err; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u8; +use nom::{IResult, bytes::complete::take}; +use std::ops::Range; + +#[derive(Debug, PartialEq, Eq)] +pub struct ServerKeyExchange { + pub params: ServerKeyExchangeParams, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum ServerKeyExchangeParams { + Ecdh(EcdhParams), + Psk(PskParams), +} + +impl ServerKeyExchange { + pub fn parse( + input: &[u8], + base_offset: usize, + key_exchange_algorithm: KeyExchangeAlgorithm, + ) -> IResult<&[u8], ServerKeyExchange> { + let (input, params) = match key_exchange_algorithm { + KeyExchangeAlgorithm::EECDH => { + let (input, ecdh_params) = EcdhParams::parse(input, base_offset)?; + (input, ServerKeyExchangeParams::Ecdh(ecdh_params)) + } + KeyExchangeAlgorithm::PSK => { + let (input, psk_params) = PskParams::parse(input, base_offset)?; + (input, ServerKeyExchangeParams::Psk(psk_params)) + } + _ => return Err(Err::Failure(Error::new(input, ErrorKind::Tag))), + }; + + Ok((input, ServerKeyExchange { params })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf, with_signature: bool) { + match &self.params { + ServerKeyExchangeParams::Ecdh(ecdh_params) => { + ecdh_params.serialize(buf, output, with_signature) + } + ServerKeyExchangeParams::Psk(psk_params) => psk_params.serialize(buf, output), + } + } + + pub fn signature(&self) -> Option<&DigitallySigned> { + match &self.params { + ServerKeyExchangeParams::Ecdh(ecdh_params) => ecdh_params.signature.as_ref(), + ServerKeyExchangeParams::Psk(_) => None, + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct EcdhParams { + pub curve_type: CurveType, + pub named_group: NamedGroup, + pub public_key_range: Range, + pub signature: Option, +} + +impl EcdhParams { + pub fn public_key<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.public_key_range.clone()] + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], EcdhParams> { + let original_input = input; + let (input, curve_type) = CurveType::parse(input)?; + let (input, named_group) = NamedGroup::parse(input)?; + + // First byte is the length of the public key + let (input, public_key_len) = be_u8(input)?; + let (input, public_key_slice) = take(public_key_len as usize)(input)?; + + // Calculate absolute range for public key + let relative_offset = public_key_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + public_key_slice.len(); + let public_key_range = start..end; + + // Optionally parse a trailing DigitallySigned structure + let (input, signature) = if !input.is_empty() { + // Calculate absolute offset for the signature part + let sig_offset = + base_offset + (input.as_ptr() as usize - original_input.as_ptr() as usize); + let (rest, signed) = DigitallySigned::parse(input, sig_offset)?; + (rest, Some(signed)) + } else { + (input, None) + }; + + Ok(( + input, + EcdhParams { + curve_type, + named_group, + public_key_range, + signature, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf, with_signature: bool) { + let public_key = self.public_key(buf); + output.push(self.curve_type.as_u8()); + output.extend_from_slice(&self.named_group.as_u16().to_be_bytes()); + output.push(public_key.len() as u8); + output.extend_from_slice(public_key); + + if with_signature { + if let Some(signed) = &self.signature { + signed.serialize(buf, output); + } + } + } +} + +/// PSK identity hint (RFC 4279 §2). +/// +/// Wire format: `uint16 hint_length + hint` +#[derive(Debug, PartialEq, Eq)] +pub struct PskParams { + pub hint_range: Range, +} + +impl PskParams { + pub fn hint<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.hint_range.clone()] + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], PskParams> { + let original_input = input; + let (input, hint_len) = nom::number::complete::be_u16(input)?; + let (input, hint_slice) = take(hint_len as usize)(input)?; + + let relative_offset = hint_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + hint_slice.len(); + + Ok(( + input, + PskParams { + hint_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + let hint = self.hint(buf); + output.extend_from_slice(&(hint.len() as u16).to_be_bytes()); + output.extend_from_slice(hint); + } + + /// Serialize directly from hint bytes (for sending). + pub fn serialize_from_bytes(hint: &[u8], output: &mut Buf) { + output.extend_from_slice(&(hint.len() as u16).to_be_bytes()); + output.extend_from_slice(hint); + } +} + +#[cfg(test)] +mod test { + use super::super::{HashAlgorithm, SignatureAlgorithm, SignatureAndHashAlgorithm}; + use super::*; + use crate::buffer::Buf; + + const MESSAGE_ECDH_PUBKEY: &[u8] = &[ + 0x03, // curve_type + 0x00, 0x17, // named_group + 0x04, // public_key length + 0x01, 0x02, 0x03, 0x04, // public_key + ]; + + #[test] + fn roundtrip_ecdh() { + // Build expected message + let algorithm = + SignatureAndHashAlgorithm::new(HashAlgorithm::SHA256, SignatureAlgorithm::RSA); + let signature_bytes: &[u8] = &[0x05, 0x06, 0x07, 0x08]; + + let mut expected = Buf::new(); + expected.extend_from_slice(MESSAGE_ECDH_PUBKEY); + expected.extend_from_slice(&algorithm.as_u16().to_be_bytes()); + expected.extend_from_slice(&(signature_bytes.len() as u16).to_be_bytes()); + expected.extend_from_slice(signature_bytes); + + // Parse the message with base_offset 0 + let (rest, parsed) = + ServerKeyExchange::parse(&expected, 0, KeyExchangeAlgorithm::EECDH).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to expected bytes + let mut serialized = Buf::new(); + parsed.serialize(&expected, &mut serialized, true); + assert_eq!(&*serialized, &*expected); + } + + #[test] + fn psk_roundtrip() { + // PSK ServerKeyExchange: just hint_length + hint + const PSK_MESSAGE: &[u8] = &[ + 0x00, 0x04, // hint length = 4 + b'h', b'i', b'n', b't', + ]; + let (rest, parsed) = + ServerKeyExchange::parse(PSK_MESSAGE, 0, KeyExchangeAlgorithm::PSK).unwrap(); + assert!(rest.is_empty()); + + let ServerKeyExchangeParams::Psk(psk) = &parsed.params else { + panic!("expected Psk variant"); + }; + assert_eq!(&PSK_MESSAGE[psk.hint_range.clone()], b"hint"); + assert!( + parsed.signature().is_none(), + "PSK SKE must have no signature" + ); + + let mut serialized = Buf::new(); + parsed.serialize(PSK_MESSAGE, &mut serialized, true); + assert_eq!(&*serialized, PSK_MESSAGE); + } + + #[test] + fn psk_rejects_oversized_hint_length() { + // hint_length=0x00FF (255) but only 2 bytes follow — parser must fail + let bad: &[u8] = &[0x00, 0xFF, b'a', b'b']; + let result = ServerKeyExchange::parse(bad, 0, KeyExchangeAlgorithm::PSK); + assert!( + result.is_err(), + "parser must reject PSK hint shorter than advertised length" + ); + } + + #[test] + fn psk_empty_hint() { + // Zero-length hint is wire-legal (RFC 4279 §2). + let empty: &[u8] = &[0x00, 0x00]; + let (rest, parsed) = ServerKeyExchange::parse(empty, 0, KeyExchangeAlgorithm::PSK).unwrap(); + assert!(rest.is_empty()); + let ServerKeyExchangeParams::Psk(psk) = &parsed.params else { + panic!("expected Psk variant"); + }; + assert!(psk.hint_range.is_empty()); + } +} diff --git a/third_party/dimpl/src/dtls12/message/wrapped.rs b/third_party/dimpl/src/dtls12/message/wrapped.rs new file mode 100644 index 0000000..6d39103 --- /dev/null +++ b/third_party/dimpl/src/dtls12/message/wrapped.rs @@ -0,0 +1,40 @@ +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u16, be_u24}; +use std::ops::Range; + +macro_rules! wrapped_slice { + ($name:ident, $length_parser:path, $min:expr) => { + #[derive(Debug, Clone, PartialEq, Eq, Default)] + pub struct $name(pub Range); + + impl $name { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Self> { + let original_input = input; + let (input, len) = $length_parser(input)?; + #[allow(unused_comparisons)] + if len < $min { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + let (input, data_slice) = take(len)(input)?; + + // Calculate absolute range in root buffer + let relative_offset = + data_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + data_slice.len(); + + Ok((input, $name(start..end))) + } + + pub fn as_slice<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.0.clone()] + } + } + }; +} + +wrapped_slice!(Asn1Cert, be_u24, 0); +wrapped_slice!(DistinguishedName, be_u16, 1); diff --git a/third_party/dimpl/src/dtls12/mod.rs b/third_party/dimpl/src/dtls12/mod.rs new file mode 100644 index 0000000..aee2190 --- /dev/null +++ b/third_party/dimpl/src/dtls12/mod.rs @@ -0,0 +1,38 @@ +//! DTLS 1.2 protocol implementation. +//! + +// This is the full DTLS 1.2 handshake flow +// +// Client Server +// +// 1 ClientHello --------> +// +// 2 <-------- HelloVerifyRequest +// (contains cookie) +// +// 3 ClientHello --------> +// (with cookie) +// 4 ServerHello +// Certificate* +// ServerKeyExchange* +// CertificateRequest* +// <-------- ServerHelloDone +// 5 Certificate* +// ClientKeyExchange +// CertificateVerify* +// [ChangeCipherSpec] +// Finished --------> +// 6 [ChangeCipherSpec] +// <-------- Finished +// Application Data <-------> Application Data + +mod client; +mod context; +mod engine; +pub mod incoming; +pub mod message; +mod queue; +mod server; + +pub use client::Client; +pub use server::Server; diff --git a/third_party/dimpl/src/dtls12/queue.rs b/third_party/dimpl/src/dtls12/queue.rs new file mode 100644 index 0000000..b67f4db --- /dev/null +++ b/third_party/dimpl/src/dtls12/queue.rs @@ -0,0 +1,118 @@ +//! Queue wrapper types with safe Debug implementations. +//! +//! These wrappers ensure that debug output only shows metadata, +//! not potentially sensitive payload data. + +use std::collections::VecDeque; +use std::fmt; +use std::ops::{Deref, DerefMut}; + +use crate::buffer::Buf; +use crate::dtls12::incoming::Incoming; +use crate::types::ContentType; + +/// Wrapper around the receive queue that provides safe Debug output. +/// +/// The Debug implementation only shows metadata (counts by content type), +/// not potentially sensitive payload data. +pub(crate) struct QueueRx(VecDeque); + +impl QueueRx { + pub fn new() -> Self { + Self(VecDeque::new()) + } +} + +impl Deref for QueueRx { + type Target = VecDeque; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for QueueRx { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl fmt::Debug for QueueRx { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut handshake = 0; + let mut app_data = 0; + let mut alert = 0; + let mut ccs = 0; + let mut other = 0; + let mut min_seq: Option<(u16, u64)> = None; + let mut max_seq: Option<(u16, u64)> = None; + + for item in &self.0 { + let record = item.first().record(); + match record.content_type { + ContentType::Handshake => handshake += 1, + ContentType::ApplicationData => app_data += 1, + ContentType::Alert => alert += 1, + ContentType::ChangeCipherSpec => ccs += 1, + _ => other += 1, + } + + let seq = (record.sequence.epoch, record.sequence.sequence_number); + min_seq = Some(min_seq.map_or(seq, |m| m.min(seq))); + max_seq = Some(max_seq.map_or(seq, |m| m.max(seq))); + } + + let mut s = f.debug_struct("QueueRx"); + s.field("len", &self.0.len()) + .field("handshake", &handshake) + .field("app_data", &app_data) + .field("alert", &alert) + .field("ccs", &ccs) + .field("other", &other); + + if let (Some(min), Some(max)) = (min_seq, max_seq) { + s.field( + "seq_range", + &format_args!("{}:{} - {}:{}", min.0, min.1, max.0, max.1), + ); + } + + s.finish() + } +} + +/// Wrapper around the transmit queue that provides safe Debug output. +/// +/// The Debug implementation only shows metadata (datagram count and total bytes), +/// not potentially sensitive payload data. +pub(crate) struct QueueTx(VecDeque); + +impl QueueTx { + pub fn new() -> Self { + Self(VecDeque::new()) + } +} + +impl Deref for QueueTx { + type Target = VecDeque; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for QueueTx { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl fmt::Debug for QueueTx { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let total_bytes: usize = self.0.iter().map(|b| b.len()).sum(); + f.debug_struct("QueueTx") + .field("datagrams", &self.0.len()) + .field("total_bytes", &total_bytes) + .finish() + } +} diff --git a/third_party/dimpl/src/dtls12/server.rs b/third_party/dimpl/src/dtls12/server.rs new file mode 100644 index 0000000..1e0a765 --- /dev/null +++ b/third_party/dimpl/src/dtls12/server.rs @@ -0,0 +1,1502 @@ +// DTLS Server Handshake Flow: +// +// 1. Client sends ClientHello (maybe without cookie) +// 2. If cookie missing/invalid, Server sends HelloVerifyRequest (stateless cookie) +// - Client resends ClientHello with cookie +// 3. Server sends ServerHello, Certificate, ServerKeyExchange, +// CertificateRequest (required), ServerHelloDone +// 4. Client sends Certificate (optional), ClientKeyExchange, +// CertificateVerify (if client cert), ChangeCipherSpec, Finished +// 5. Server verifies Finished, then sends ChangeCipherSpec, Finished +// 6. Handshake complete, application data can flow +// +// This implementation mirrors the client structure and ordering for a DTLS server. + +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::Instant; + +use arrayvec::ArrayVec; +use subtle::ConstantTimeEq; + +use crate::buffer::{Buf, ToBuf}; +use crate::crypto::SrtpProfile; +use crate::dtls12::Client; +use crate::dtls12::client::LocalEvent; +use crate::dtls12::context::AuthMode; +use crate::dtls12::engine::Engine; +use crate::dtls12::message::ECPointFormatsExtension; +use crate::dtls12::message::PskParams; +use crate::dtls12::message::{Body, CertificateRequest, CertificateTypeVec, Dtls12CipherSuite}; +use crate::dtls12::message::{ClientCertificateType, CompressionMethod, ContentType}; +use crate::dtls12::message::{Cookie, CurveType, DistinguishedName, ExchangeKeys, ExtensionType}; +use crate::dtls12::message::{HashAlgorithm, HelloVerifyRequest, KeyExchangeAlgorithm}; +use crate::dtls12::message::{MessageType, NamedGroup, NamedGroupVec, ProtocolVersion, Random}; +use crate::dtls12::message::{ServerHello, SessionId, SignatureAlgorithm}; +use crate::dtls12::message::{SignatureAlgorithmsExtension, SignatureAndHashAlgorithm}; +use crate::dtls12::message::{SignatureAndHashAlgorithmVec, SrtpProfileId}; +use crate::dtls12::message::{SrtpProfileVec, SupportedGroupsExtension, UseSrtpExtension}; +use crate::{Config, Error, InternalError, Output}; + +/// Length of the random dummy PSK used when identity resolution fails. +/// Fixed so handshake timing does not leak the failure, and long enough +/// that a coincidental match with a real 32-byte PSK is cryptographically +/// impossible. +const DUMMY_PSK_LEN: usize = 32; + +/// DTLS server +pub struct Server { + /// Current server state. + state: State, + + /// Engine in common between server and client. + engine: Engine, + + /// Random unique data (with gmt timestamp). Used for signature checks. + random: Option, + + /// SessionId we provide to the client (unused/resumption not implemented). + session_id: Option, + + /// Cookie secret for HMAC, generated per-server instance + cookie_secret: [u8; 32], + + /// Storage for extension data + extension_data: Buf, + + /// The negotiated SRTP profile (if any) + negotiated_srtp_profile: Option, + + /// Client's offered supported_groups (if any) + client_supported_groups: Option, + + /// Client's offered signature_algorithms (if any) + client_signature_algorithms: Option, + + /// Client random. Set by ClientHello. + client_random: Option, + + /// Client certificates + client_certificates: Vec, + + /// Buffer for defragmenting handshakes + defragment_buffer: Buf, + + /// Captured session hash for Extended Master Secret (RFC 7627) + captured_session_hash: Option, + + /// Whether the PSK identity resolved to a real key. + /// + /// `None` until the PSK ClientKeyExchange is processed. Non-PSK handshakes + /// leave this `None` and the Finished check skips the PSK branch entirely. + /// Defaulting to `None` (rather than `true`) means a future refactor that + /// forgets to set it in the PSK path fails closed instead of silently + /// bypassing identity validation. + psk_valid: Option, + + /// The last now we seen + last_now: Instant, + + /// Events we are to emit from this Server. + local_events: VecDeque, + + /// Data that is sent before we are connected. + queued_data: Vec, +} + +/// Current state of the server. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + AwaitClientHello, + SendServerHello, + SendCertificate, + SendServerKeyExchange, + SendCertificateRequest, + SendServerHelloDone, + AwaitCertificate, + AwaitClientKeyExchange, + AwaitCertificateVerify, + AwaitChangeCipherSpec, + AwaitFinished, + SendChangeCipherSpec, + SendFinished, + AwaitApplicationData, + Closed, +} + +impl Server { + /// Create a new DTLS server + pub fn new(config: Arc, certificate: crate::DtlsCertificate, now: Instant) -> Server { + assert!( + !certificate.certificate.is_empty(), + "Server certificate cannot be empty" + ); + // unwrap: malformed private_key bytes are a programmer error from the + // caller who constructed DtlsCertificate; panic matches the prior + // CryptoContext::new behavior which also panicked on empty/invalid + // key material. + let private_key = config + .crypto_provider() + .key_provider + .load_private_key(&certificate.private_key) + .expect("Failed to parse server private key"); + let auth = AuthMode::Certificate { + certificate: certificate.certificate, + private_key, + }; + let engine = Engine::new(config, auth); + Self::new_with_engine(engine, now) + } + + /// Create a new PSK-only DTLS server (no certificate). + pub fn new_psk(config: Arc, now: Instant) -> Server { + let engine = Engine::new(config, AuthMode::Psk); + Self::new_with_engine(engine, now) + } + + pub(crate) fn new_with_engine(mut engine: Engine, now: Instant) -> Server { + engine.set_client(false); + + let cookie_secret: [u8; 32] = engine.rng.random(); + + Server { + state: State::AwaitClientHello, + engine, + random: None, + session_id: None, + cookie_secret, + extension_data: Buf::new(), + negotiated_srtp_profile: None, + client_supported_groups: None, + client_signature_algorithms: None, + client_random: None, + client_certificates: Vec::with_capacity(3), + defragment_buffer: Buf::new(), + captured_session_hash: None, + psk_valid: None, + last_now: now, + local_events: VecDeque::new(), + queued_data: Vec::new(), + } + } + + pub fn into_client(self) -> Client { + Client::new_with_engine(self.engine, self.last_now) + } + + pub(crate) fn state_name(&self) -> &'static str { + self.state.name() + } + + pub fn is_closing(&self) -> bool { + self.state == State::Closed && !self.is_closed() + } + + pub fn is_closed(&self) -> bool { + self.state == State::Closed + && self.local_events.is_empty() + && !self.engine.has_pending_close_output() + } + + pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { + match self + .engine + .parse_packet(packet) + .and_then(|_| self.make_progress()) + { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { + if let Some(event) = self.local_events.pop_front() { + return event.into_output(buf, &self.client_certificates); + } + self.engine.poll_output(buf, self.last_now) + } + + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + self.last_now = now; + if self.random.is_none() { + self.random = Some(Random::new_with_time(now, &mut self.engine.rng)); + } + self.engine.handle_timeout(now)?; + match self.make_progress() { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + /// Send application data when the server is in the Running state + pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { + if self.state == State::Closed { + return Err(Error::ConnectionClosed); + } + + if self.state != State::AwaitApplicationData { + self.queued_data.push(data.to_buf()); + return Ok(()); + } + + // Use the engine's create_record to send application data + // The encryption is now handled in the engine + self.engine + .create_record(ContentType::ApplicationData, 1, false, |body| { + body.extend_from_slice(data); + })?; + + Ok(()) + } + + /// Initiate graceful shutdown by sending a `close_notify` alert. + pub fn close(&mut self) -> Result<(), Error> { + if self.state == State::Closed { + return Ok(()); + } + if self.state != State::AwaitApplicationData { + self.engine.abort(); + self.state = State::Closed; + return Ok(()); + } + self.engine + .create_record(ContentType::Alert, 1, false, |body| { + body.push(1); // level: warning + body.push(0); // description: close_notify + })?; + self.state = State::Closed; + Ok(()) + } + + fn make_progress(&mut self) -> Result<(), InternalError> { + loop { + let prev_state = self.state; + + let new_state = prev_state.make_progress(self)?; + if prev_state != new_state { + self.state = new_state; + trace!("{:?} -> {:?}", prev_state, new_state); + } else { + break; + } + } + Ok(()) + } +} + +impl State { + fn name(&self) -> &'static str { + match self { + State::AwaitClientHello => "AwaitClientHello", + State::SendServerHello => "SendServerHello", + State::SendCertificate => "SendCertificate", + State::SendServerKeyExchange => "SendServerKeyExchange", + State::SendCertificateRequest => "SendCertificateRequest", + State::SendServerHelloDone => "SendServerHelloDone", + State::AwaitCertificate => "AwaitCertificate", + State::AwaitClientKeyExchange => "AwaitClientKeyExchange", + State::AwaitCertificateVerify => "AwaitCertificateVerify", + State::AwaitChangeCipherSpec => "AwaitChangeCipherSpec", + State::AwaitFinished => "AwaitFinished", + State::SendChangeCipherSpec => "SendChangeCipherSpec", + State::SendFinished => "SendFinished", + State::AwaitApplicationData => "AwaitApplicationData", + State::Closed => "Closed", + } + } + + fn make_progress(self, server: &mut Server) -> Result { + match self { + State::AwaitClientHello => self.await_client_hello(server), + State::SendServerHello => self.send_server_hello(server), + State::SendCertificate => self.send_certificate(server), + State::SendServerKeyExchange => self.send_server_key_exchange(server), + State::SendCertificateRequest => self.send_certificate_request(server), + State::SendServerHelloDone => self.send_server_hello_done(server), + State::AwaitCertificate => self.await_certificate(server), + State::AwaitClientKeyExchange => self.await_client_key_exchange(server), + State::AwaitCertificateVerify => self.await_certificate_verify(server), + State::AwaitChangeCipherSpec => self.await_change_cipher_spec(server), + State::AwaitFinished => self.await_finished(server), + State::SendChangeCipherSpec => self.send_change_cipher_spec(server), + State::SendFinished => self.send_finished(server), + State::AwaitApplicationData => self.await_application_data(server), + State::Closed => Ok(self), + } + } + + fn await_client_hello(self, server: &mut Server) -> Result { + let maybe = server + .engine + .next_handshake(MessageType::ClientHello, &mut server.defragment_buffer)?; + + let Some(handshake) = maybe else { + // Stay in same state + return Ok(self); + }; + + let Body::ClientHello(ch) = handshake.body else { + unreachable!() + }; + + // Enforce DTLS1.2 + if ch.client_version != ProtocolVersion::DTLS1_2 { + return Err( + Error::SecurityError(crate::SecurityError::UnsupportedClientVersion( + ch.client_version, + )) + .into(), + ); + } + + // Enforce Null compression only (client must offer it) + let has_null = ch.compression_methods.contains(&CompressionMethod::Null); + if !has_null { + return Err( + Error::SecurityError(crate::SecurityError::UnsupportedClientCompression).into(), + ); + } + + trace!( + "ClientHello: cookie_len={}, offered_suites={}", + ch.cookie.len(), + ch.cipher_suites.len() + ); + + // Stateless cookie: require 32-byte cookie matching HMAC(secret, client_random) + let client_random = ch.random; + let hmac_provider = server.engine.config().crypto_provider().hmac_provider; + let need_cookie = server.engine.config().use_server_cookie(); + let cookie_valid = !need_cookie + || verify_cookie( + hmac_provider, + &server.cookie_secret, + client_random, + ch.cookie, + ); + if !cookie_valid { + debug!("Invalid/missing cookie; sending HelloVerifyRequest"); + + let cookie = compute_cookie(hmac_provider, &server.cookie_secret, client_random)?; + // Start/restart flight timer for server Flight 2 (HelloVerifyRequest) + server.engine.flight_begin(2); + server + .engine + .create_handshake(MessageType::HelloVerifyRequest, |body, _engine| { + // RFC 6347 4.2.1: The server_version field in the HelloVerifyRequest + // message MUST be set to DTLS 1.0 + let hvr = HelloVerifyRequest::new(ProtocolVersion::DTLS1_0, cookie); + hvr.serialize(body); + Ok(()) + })?; + + // The HelloVerifyRequest exchange is stateless per RFC 6347. + // Reset all handshake state so the next ClientHello (with cookie) is processed fresh. + server.engine.reset_server_for_hello_verify_request(); + return Ok(self); + } + + trace!("Accepted ClientHello cookie; proceeding with handshake"); + + // Client offered suites; we pick per client order intersecting allowed and server key compatibility + let mut selected: Option = None; + for s in ch.cipher_suites.iter() { + let is_allowed = server.engine.is_cipher_suite_allowed(*s); + let is_compatible = server + .engine + .crypto_context() + .is_cipher_suite_compatible(*s); + if is_allowed && is_compatible { + selected = Some(*s); + break; + } + } + + let Some(cs) = selected else { + return Err((Error::SecurityError( + crate::SecurityError::NoMutuallyAcceptableCipherSuite, + )) + .into()); + }; + + server.engine.set_cipher_suite(cs); + server.client_random = Some(client_random); + + debug!("Selected cipher suite: {:?}", cs); + + // Process client extensions: SRTP, EMS, SupportedGroups and SignatureAlgorithms + let mut client_offers_ems = false; + let mut client_srtp_profiles: Option = None; + let mut client_supported_groups: Option = None; + let mut client_signature_algorithms: Option = None; + for ext in ch.extensions { + match ext.extension_type { + ExtensionType::UseSrtp => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let (_, use_srtp) = + UseSrtpExtension::parse(ext_data).map_err(InternalError::from)?; + client_srtp_profiles = Some(use_srtp.profiles); + } + ExtensionType::ExtendedMasterSecret => { + client_offers_ems = true; + } + ExtensionType::SupportedGroups => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let (_, groups) = + SupportedGroupsExtension::parse(ext_data).map_err(InternalError::from)?; + client_supported_groups = Some(groups.groups); + } + ExtensionType::EcPointFormats => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let _ = + ECPointFormatsExtension::parse(ext_data).map_err(InternalError::from)?; + } + ExtensionType::SignatureAlgorithms => { + let ext_data = ext.extension_data(&server.defragment_buffer); + if let Ok((_, sigs)) = SignatureAlgorithmsExtension::parse(ext_data) { + client_signature_algorithms = Some(sigs.supported_signature_algorithms); + } else { + warn!("Failed to parse SignatureAlgorithms extension"); + } + } + _ => {} + } + } + + // EMS is mandatory + if !client_offers_ems { + return Err(Error::SecurityError( + crate::SecurityError::ExtendedMasterSecretNotNegotiated, + ) + .into()); + } + + // Select SRTP profile according to server priority: AES256GCM, AES128GCM, then SHA1 + if let Some(profiles) = client_srtp_profiles { + // Map client profile ids to SrtpProfile, then pick our preferred + let mut selected_profile: Option = None; + for preferred in [ + SrtpProfile::AEAD_AES_256_GCM, + SrtpProfile::AEAD_AES_128_GCM, + SrtpProfile::AES128_CM_SHA1_80, + ] { + if profiles.iter().any(|pid| preferred == (*pid).into()) { + selected_profile = Some(preferred); + break; + } + } + server.negotiated_srtp_profile = selected_profile; + if let Some(profile) = server.negotiated_srtp_profile { + debug!("Negotiated SRTP profile: {:?}", profile); + } + } + + // Store client's offers for later selection + server.client_supported_groups = client_supported_groups; + server.client_signature_algorithms = client_signature_algorithms; + + // Proceed to send the server flight + trace!("Extended Master Secret enabled"); + Ok(Self::SendServerHello) + } + + fn send_server_hello(self, server: &mut Server) -> Result { + trace!("Sending ServerHello"); + + // Start/restart flight timer for server Flight 4 + server.engine.flight_begin(4); + + let session_id = server.session_id.unwrap_or_else(SessionId::empty); + // unwrap: is ok because we set the random in handle_timeout + let random = server.random.unwrap(); + let negotiated_srtp_profile = server.negotiated_srtp_profile; + let extension_data = &mut server.extension_data; + + // Send ServerHello + server + .engine + .create_handshake(MessageType::ServerHello, move |body, engine| { + handshake_create_server_hello( + body, + engine, + random, + session_id, + negotiated_srtp_profile, + extension_data, + ) + })?; + + let cs = server.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + // PSK suites skip Certificate + if cs.is_psk() { + Ok(Self::SendServerKeyExchange) + } else { + Ok(Self::SendCertificate) + } + } + + fn send_certificate(self, server: &mut Server) -> Result { + trace!("Sending Certificate"); + + server + .engine + .create_handshake(MessageType::Certificate, handshake_create_certificate)?; + + Ok(Self::SendServerKeyExchange) + } + + fn send_server_key_exchange(self, server: &mut Server) -> Result { + trace!("Sending ServerKeyExchange"); + + let cs = server.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + if cs.is_psk() { + return self.send_server_key_exchange_psk(server); + } + + let client_random = server.client_random.ok_or(Error::InvalidState( + crate::InvalidStateError::NoClientRandom, + ))?; + // unwrap: is ok because we set the random in handle_timeout + let server_random = server.random.unwrap(); + + // Select ECDHE group from the intersection of: + // - client offers, and + // - server-allowed DTLS 1.2 groups (provider + config filter) + // Preference follows Config::kx_groups() order. + let allowed_named_groups: Vec = server + .engine + .config() + .kx_groups() + .map(|g| g.name()) + .collect(); + let selected_named_group = select_named_group( + server.client_supported_groups.as_ref(), + &allowed_named_groups, + ) + .ok_or_else(|| { + if server.client_supported_groups.is_some() { + Error::SecurityError(crate::SecurityError::NoCommonKeyExchangeGroup) + } else { + Error::CryptoError(crate::CryptoError::NoDtls12KeyExchangeGroupsConfigured) + } + })?; + + // Select signature/hash for SKE by intersecting client's list + // with our key type, preferring the key's native hash algorithm. + // unwrap: ServerKeyExchange signature only needed for certificate-based suites + let selected_signature = select_ske_signature_algorithm( + server.client_signature_algorithms.as_ref(), + server + .engine + .crypto_context() + .signature_algorithm() + .unwrap(), + server + .engine + .crypto_context() + .private_key_default_hash_algorithm() + .unwrap(), + server + .engine + .crypto_context() + .private_key_supported_hash_algorithms(), + ); + + debug!( + "ServerKeyExchange params: group={:?}, signature_alg={:?}", + selected_named_group, selected_signature + ); + + server + .engine + .create_handshake(MessageType::ServerKeyExchange, |body, engine| { + handshake_create_server_key_exchange( + body, + engine, + client_random, + server_random, + selected_named_group, + selected_signature, + ) + })?; + + if server.engine.config().require_client_certificate() { + Ok(Self::SendCertificateRequest) + } else { + Ok(Self::SendServerHelloDone) + } + } + + /// PSK ServerKeyExchange: send identity hint only (no ECDHE, no signature). + /// Per RFC 4279 §2, the message is omitted entirely when no hint is configured. + fn send_server_key_exchange_psk(self, server: &mut Server) -> Result { + let Some(hint) = server + .engine + .config() + .psk_identity_hint() + .map(<[u8]>::to_vec) + else { + return Ok(Self::SendServerHelloDone); + }; + + server + .engine + .create_handshake(MessageType::ServerKeyExchange, move |body, _engine| { + PskParams::serialize_from_bytes(&hint, body); + Ok(()) + })?; + + // PSK never sends CertificateRequest + Ok(Self::SendServerHelloDone) + } + + fn send_certificate_request(self, server: &mut Server) -> Result { + debug!("Sending CertificateRequest"); + // Select CertificateRequest.signature_algorithms as intersection of client's list and our supported + let sig_algs = + select_certificate_request_sig_algs(server.client_signature_algorithms.as_ref()); + debug!( + "CertificateRequest will advertise {} signature algorithms", + sig_algs.len() + ); + + server + .engine + .create_handshake(MessageType::CertificateRequest, move |body, _| { + handshake_serialize_certificate_request(body, &sig_algs) + })?; + + Ok(Self::SendServerHelloDone) + } + + fn send_server_hello_done(self, server: &mut Server) -> Result { + trace!("Sending ServerHelloDone"); + + server + .engine + .create_handshake(MessageType::ServerHelloDone, |_, _| Ok(()))?; + + let cs = server.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + // PSK: no client certificates + if cs.is_psk() { + return Ok(Self::AwaitClientKeyExchange); + } + + if server.engine.config().require_client_certificate() { + Ok(Self::AwaitCertificate) + } else { + Ok(Self::AwaitClientKeyExchange) + } + } + + fn await_certificate(self, server: &mut Server) -> Result { + let maybe = server + .engine + .next_handshake(MessageType::Certificate, &mut server.defragment_buffer)?; + + let Some(ref handshake) = maybe else { + // Stay in same state + return Ok(self); + }; + + let Body::Certificate(certificate) = &handshake.body else { + unreachable!() + }; + + // Extract certificate ranges before dropping handshake + let cert_ranges: ArrayVec<_, 32> = certificate + .certificate_list + .iter() + .map(|cert| cert.0.clone()) + .collect(); + + drop(maybe); + + if cert_ranges.is_empty() { + // Client didn't provide a certificate (allowed), skip + } else { + // Store and verify via callback + debug!( + "Received client certificate chain with {} certificate(s)", + cert_ranges.len() + ); + for (i, range) in cert_ranges.iter().enumerate() { + let cert_data = &server.defragment_buffer[range.clone()]; + trace!( + "Client Certificate #{} size: {} bytes", + i + 1, + cert_data.len() + ); + server.client_certificates.push(cert_data.to_buf()); + } + + server.local_events.push_back(LocalEvent::PeerCert); + } + + Ok(Self::AwaitClientKeyExchange) + } + + fn await_client_key_exchange(self, server: &mut Server) -> Result { + let maybe = server.engine.next_handshake( + MessageType::ClientKeyExchange, + &mut server.defragment_buffer, + )?; + + let Some(ref handshake) = maybe else { + // Stay in same state + return Ok(self); + }; + + let Body::ClientKeyExchange(ckx) = &handshake.body else { + unreachable!() + }; + + let suite = server.engine.cipher_suite().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + ))?; + + if suite.is_psk() { + // Extract PSK identity range before dropping handshake + let identity_range = match &ckx.exchange_keys { + ExchangeKeys::Psk(keys) => keys.identity_range.clone(), + _ => { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::EcdheClientKeyExchangeInPskPath, + ) + .into()); + } + }; + + drop(maybe); + + let identity = &server.defragment_buffer[identity_range]; + trace!("PSK identity ({} bytes)", identity.len()); + + // Resolve PSK via the configured resolver. On failure we derive a + // random dummy of fixed length so the handshake proceeds identically + // to a valid-identity flow (no timing oracle) and the Finished MAC + // is guaranteed to mismatch — not merely likely to. + let resolved = server + .engine + .config() + .psk_resolver() + .ok_or(Error::PskError(crate::PskError::NoPskResolverConfigured))? + .resolve(identity); + + let (psk, psk_valid) = match resolved { + Some(key) => (key, true), + None => { + let dummy: [u8; DUMMY_PSK_LEN] = server.engine.rng.random(); + (dummy.to_vec(), false) + } + }; + + server.psk_valid = Some(psk_valid); + + let crypto = server.engine.crypto_context_mut(); + crypto.set_psk(psk); + crypto + .compute_psk_pre_master_secret() + .map_err(Error::CryptoError)?; + } else { + // Extract client's public key range before dropping handshake + let public_key_range = match &ckx.exchange_keys { + ExchangeKeys::Ecdh(keys) => keys.public_key_range.clone(), + ExchangeKeys::Psk(_) => { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::PskClientKeyExchangeInEcdhePath, + ) + .into()); + } + }; + + drop(maybe); + + // Get the actual public key data from defragment_buffer + let client_pub = &server.defragment_buffer[public_key_range]; + + // Compute shared secret + let mut buf = server.engine.pop_buffer(); + server + .engine + .crypto_context_mut() + .compute_shared_secret(client_pub, &mut buf) + .map_err(Error::CryptoError)?; + server.engine.push_buffer(buf); + } + + // Capture session hash for EMS now (up to ClientKeyExchange) + let suite_hash = suite.hash_algorithm(); + let mut buf = server.engine.pop_buffer(); + server.engine.transcript_hash(suite_hash, &mut buf); + server.captured_session_hash = Some(buf); + + // Derive master secret and keys (needed to decrypt client's Finished) + let client_random_buf = { + let mut b = Buf::new(); + server.client_random.unwrap().serialize(&mut b); + b + }; + let server_random_buf = { + let mut b = Buf::new(); + // unwrap: is ok because we set the random in handle_timeout + server.random.unwrap().serialize(&mut b); + b + }; + + let session_hash = server + .captured_session_hash + .as_ref() + .ok_or(Error::InvalidState( + crate::InvalidStateError::ExtendedMasterSecretSessionHashMissing, + ))?; + + let mut out = server.engine.pop_buffer(); + let mut scratch = server.engine.pop_buffer(); + server + .engine + .crypto_context_mut() + .derive_extended_master_secret(session_hash, suite_hash, &mut out, &mut scratch) + .map_err(Error::CryptoError)?; + + server + .engine + .crypto_context_mut() + .derive_keys( + suite, + &client_random_buf, + &server_random_buf, + &mut out, + &mut scratch, + ) + .map_err(Error::CryptoError)?; + + server.engine.push_buffer(out); + server.engine.push_buffer(scratch); + + trace!( + "Captured session hash length for EMS: {}", + session_hash.len() + ); + trace!("Derived session keys (EMS) and ready to verify Finished"); + + if !server.client_certificates.is_empty() { + Ok(Self::AwaitCertificateVerify) + } else { + Ok(Self::AwaitChangeCipherSpec) + } + } + + fn await_certificate_verify(self, server: &mut Server) -> Result { + // Get handshake data BEFORE processing CertificateVerify message + // According to TLS spec, signature is over all handshake messages + // up to but not including CertificateVerify + let data = server.engine.transcript().to_buf(); + + let maybe = server.engine.next_handshake( + MessageType::CertificateVerify, + &mut server.defragment_buffer, + )?; + + if maybe.is_none() { + // Stay in same state + return Ok(self); + }; + + // Extract signature data before accessing buffer + let (signature_range, signature_algorithm) = { + let handshake = maybe.as_ref().unwrap(); + let Body::CertificateVerify(cv) = &handshake.body else { + unreachable!() + }; + + (cv.signed.signature_range.clone(), cv.signed.algorithm) + }; + + // Drop maybe to release buffer borrow + drop(maybe); + + // Now access the buffer + let signature_bytes = &server.defragment_buffer[signature_range]; + + if server.client_certificates.is_empty() { + return Err(Error::CertificateError( + crate::CertificateError::NoClientCertificateForVerification, + ) + .into()); + } + + // Create temp DigitallySigned for verification + let temp_signed = crate::dtls12::message::DigitallySigned { + algorithm: signature_algorithm, + signature_range: 0..signature_bytes.len(), + }; + + server + .engine + .crypto_context() + .verify_signature( + &data, + &temp_signed, + signature_bytes, + &server.client_certificates[0], + ) + .map_err(Error::CryptoError)?; + + debug!("Client CertificateVerify verified successfully"); + + Ok(Self::AwaitChangeCipherSpec) + } + + fn await_change_cipher_spec(self, server: &mut Server) -> Result { + let maybe = server.engine.next_record(ContentType::ChangeCipherSpec); + + let Some(_) = maybe else { + // Stay in same state + return Ok(self); + }; + + // Drop any extra CCS resends to avoid being blocked + trace!("Dropping any pending CCS resends from peer"); + server.engine.drop_pending_ccs(); + + // Expect every record to be decrypted from now on. + trace!("Received ChangeCipherSpec; enabling peer encryption"); + server.engine.enable_peer_encryption()?; + + Ok(Self::AwaitFinished) + } + + fn await_finished(self, server: &mut Server) -> Result { + // Generate expected verify data based on current transcript. + // This must be done before next_handshake() below since + // it should not include Finished itself. + let expected = server.engine.generate_verify_data(true /* client */)?; + + let maybe = server + .engine + .next_handshake(MessageType::Finished, &mut server.defragment_buffer)?; + + if maybe.is_none() { + // stay in same state + return Ok(self); + } + + // Extract the range from the handshake + let verify_data_range = if let Some(ref handshake) = maybe { + if let Body::Finished(finished) = &handshake.body { + finished.verify_data_range.clone() + } else { + panic!("Finished message should have been parsed"); + } + } else { + unreachable!() + }; + + // Drop maybe to release the buffer borrow + drop(maybe); + + // Now we can access the buffer + let verify_data = &server.defragment_buffer[verify_data_range]; + // Use constant-time comparison to prevent timing attacks + let is_eq: bool = verify_data.ct_eq(expected.as_slice()).into(); + if !is_eq { + return Err((Error::SecurityError( + crate::SecurityError::ClientFinishedVerificationFailed, + )) + .into()); + } + + // Invariant: full PSK handshakes always set psk_valid in + // await_client_key_exchange before reaching Finished. A violation is a + // state-machine bug, not network input — `assert!` (not debug_assert!) + // because a silent bypass could let a forged-PSK Finished through. + // Loosen when dtls-conn-id lands and abbreviated handshakes legitimately + // skip ClientKeyExchange (reusing a cached master secret). + if server.engine.cipher_suite().is_some_and(|cs| cs.is_psk()) { + assert!( + server.psk_valid.is_some(), + "PSK handshake reached Finished without processing ClientKeyExchange" + ); + } + + // Defense-in-depth for PSK: the random dummy key should already make + // the MAC above fail when the identity was unknown. We additionally + // reject `Some(false)` explicitly so a future refactor that lets the + // dummy path survive the MAC check still fails closed here. + // + // `None` is legitimate for abbreviated (resumption) handshakes, which + // skip ClientKeyExchange and therefore never set psk_valid — those + // paths reuse a cached master_secret and don't consult the resolver. + if server.psk_valid == Some(false) { + return Err((Error::SecurityError( + crate::SecurityError::ClientFinishedVerificationFailed, + )) + .into()); + } + + trace!("Client Finished verified successfully"); + + Ok(Self::SendChangeCipherSpec) + } + + fn send_change_cipher_spec(self, server: &mut Server) -> Result { + trace!("Sending ChangeCipherSpec"); + + // Start/restart flight timer for server Flight 6 (CCS+Finished) + server.engine.flight_begin(6); + + // Send ChangeCipherSpec + server + .engine + .create_record(ContentType::ChangeCipherSpec, 0, true, |body| { + body.push(1); + })?; + + Ok(Self::SendFinished) + } + + fn send_finished(self, server: &mut Server) -> Result { + trace!("Sending Finished message to complete handshake"); + + server + .engine + .create_handshake(MessageType::Finished, |body, engine| { + let verify_data = engine.generate_verify_data(false /* server */)?; + trace!("Finished.verify_data length: {}", verify_data.len()); + // Directly write the verify data without creating Finished struct + body.extend_from_slice(&verify_data); + Ok(()) + })?; + + // Final flight sent; stop periodic retransmission timers per RFC 6347 FINISHED state. + // If this flight need resending, it relies on the client to resend its last flight. + server.engine.flight_stop_resend_timers(); + + // Handshake complete + debug!("Handshake complete; ready for application data"); + server.local_events.push_back(LocalEvent::Connected); + + // Emit SRTP keying material if negotiated + if let Some(profile) = server.negotiated_srtp_profile { + let suite_hash = server.engine.cipher_suite().unwrap().hash_algorithm(); + let mut out = server.engine.pop_buffer(); + let mut scratch = server.engine.pop_buffer(); + if let Ok(keying_material) = server + .engine + .crypto_context() + .extract_srtp_keying_material(profile, suite_hash, &mut out, &mut scratch) + { + server.engine.push_buffer(out); + server.engine.push_buffer(scratch); + debug!( + "SRTP keying material extracted ({} bytes) for profile: {:?}", + keying_material.len(), + profile + ); + // expect should be correct here since we negotiated the profile + let profile = server + .negotiated_srtp_profile + .expect("SRTP profile should be negotiated"); + server + .local_events + .push_back(LocalEvent::KeyingMaterial(keying_material, profile)); + } else { + server.engine.push_buffer(out); + server.engine.push_buffer(scratch); + } + } + + server.engine.release_application_data(); + + Ok(Self::AwaitApplicationData) + } + + fn await_application_data(self, server: &mut Server) -> Result { + if server.engine.close_notify_received() { + // RFC 5246 §7.2.1: respond with a reciprocal close_notify and + // close down immediately, discarding any pending writes. + server.engine.discard_pending_writes(); + server + .engine + .create_record(ContentType::Alert, 1, false, |body| { + body.push(1); // level: warning + body.push(0); // description: close_notify + })?; + return Ok(State::Closed); + } + + // Now send any application data that was queued before we were connected. + if !server.queued_data.is_empty() { + debug!( + "Sending queued application data: {}", + server.queued_data.len() + ); + for data in server.queued_data.drain(..) { + server + .engine + .create_record(ContentType::ApplicationData, 1, false, |body| { + body.extend_from_slice(&data); + })?; + } + } + + Ok(self) + } +} + +fn compute_cookie( + hmac_provider: &dyn crate::crypto::HmacProvider, + secret: &[u8], + client_random: Random, +) -> Result { + // cookie = trunc_32(HMAC(secret, client_random)) + let mut buf = Buf::new(); + client_random.serialize(&mut buf); + let tag = hmac_provider + .hmac_sha256(secret, &buf) + .map_err(Error::CryptoError)?; + let cookie = Cookie::try_new(&tag).map_err(|_| { + Error::CryptoError(crate::CryptoError::OperationFailed( + crate::CryptoOperation::ComputeCookie, + )) + })?; + Ok(cookie) +} + +fn verify_cookie( + hmac_provider: &dyn crate::crypto::HmacProvider, + secret: &[u8], + client_random: Random, + cookie: Cookie, +) -> bool { + if cookie.len() != 32 { + return false; + } + match compute_cookie(hmac_provider, secret, client_random) { + // Use constant-time comparison to prevent timing attacks + Ok(expected) => expected.as_ref().ct_eq(cookie.as_ref()).into(), + Err(_) => false, + } +} + +fn handshake_create_certificate(body: &mut Buf, engine: &mut Engine) -> Result<(), Error> { + let crypto = engine.crypto_context(); + crypto.serialize_client_certificate(body); + Ok(()) +} + +fn handshake_create_server_hello( + body: &mut Buf, + engine: &mut Engine, + random: Random, + session_id: SessionId, + negotiated_srtp_profile: Option, + extension_data: &mut Buf, +) -> Result<(), Error> { + let server_version = ProtocolVersion::DTLS1_2; + + let cs = engine + .cipher_suite() + .ok_or(Error::InvalidState(crate::InvalidStateError::NoCipherSuite))?; + + let srtp_pid = negotiated_srtp_profile.map(|p| match p { + SrtpProfile::AEAD_AES_256_GCM => SrtpProfileId::SRTP_AEAD_AES_256_GCM, + SrtpProfile::AEAD_AES_128_GCM => SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfile::AES128_CM_SHA1_80 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, + }); + + let sh = ServerHello::new( + server_version, + random, + session_id, + cs, + CompressionMethod::Null, + None, + ) + .with_extensions(extension_data, srtp_pid); + + sh.serialize(extension_data, body); + Ok(()) +} + +fn handshake_create_server_key_exchange( + body: &mut Buf, + engine: &mut Engine, + client_random: Random, + server_random: Random, + named_group: NamedGroup, + algorithm: SignatureAndHashAlgorithm, +) -> Result<(), Error> { + let Some(cipher_suite) = engine.cipher_suite() else { + return Err(Error::InvalidState( + crate::InvalidStateError::NoCipherSuiteSelected, + )); + }; + + let key_exchange_algorithm = cipher_suite.as_key_exchange_algorithm(); + debug!("Using key exchange algorithm: {:?}", key_exchange_algorithm); + + // Use hash part from selected algorithm + let hash_alg = algorithm.hash; + + match key_exchange_algorithm { + KeyExchangeAlgorithm::EECDH => { + let (curve_type, named_group) = (CurveType::NamedCurve, named_group); + let mut kx_buf = engine.pop_buffer(); + let pubkey = engine + .crypto_context_mut() + .init_ecdh_server(named_group, &mut kx_buf) + .map_err(Error::CryptoError)?; + + trace!( + "SKE ECDHE: group={:?}, pubkey_len={}", + named_group, + pubkey.len() + ); + + // Build signed_data = client_random || server_random || params(without signature) + let mut signed_data = Buf::new(); + client_random.serialize(&mut signed_data); + server_random.serialize(&mut signed_data); + // Write params directly for signing + signed_data.push(curve_type.as_u8()); + signed_data.extend_from_slice(&named_group.as_u16().to_be_bytes()); + signed_data.push(pubkey.len() as u8); + signed_data.extend_from_slice(pubkey); + + engine.push_buffer(kx_buf); + + let mut signature = engine.pop_buffer(); + + trace!("SKE signature hash: {:?}", hash_alg); + engine + .crypto_context + .sign_data(&signed_data, hash_alg, &mut signature) + .map_err(Error::CryptoError)?; + + // unwrap: safe because init_ecdh_server() above sets key_exchange = Some(...). + // If that failed, we returned Err earlier and never reach this point. + let pubkey = engine + .crypto_context_mut() + .maybe_init_key_exchange() + .unwrap(); + + // For sending, we don't use DigitallySigned struct, just write the params and signature directly + body.push(curve_type.as_u8()); + body.extend_from_slice(&named_group.as_u16().to_be_bytes()); + body.push(pubkey.len() as u8); + body.extend_from_slice(pubkey); + + // Write signature + body.extend_from_slice(&algorithm.as_u16().to_be_bytes()); + body.extend_from_slice(&(signature.len() as u16).to_be_bytes()); + body.extend_from_slice(&signature); + + engine.push_buffer(signature); + + Ok(()) + } + _ => Err(Error::SecurityError( + crate::SecurityError::UnsupportedKeyExchangeAlgorithm, + )), + } +} + +fn handshake_serialize_certificate_request( + body: &mut Buf, + sig_algs: &SignatureAndHashAlgorithmVec, +) -> Result<(), Error> { + // Only advertise ECDSA_SIGN (the only supported client cert type) + let mut cert_types = CertificateTypeVec::new(); + cert_types.push(ClientCertificateType::ECDSA_SIGN); + + // If intersection is empty (e.g., client didn't advertise), fall back to our supported set + // Build the selected list with the capacity expected by CertificateRequest + let mut selected = SignatureAndHashAlgorithmVec::new(); + if sig_algs.is_empty() { + let fallback = SignatureAndHashAlgorithm::supported(); + for alg in fallback.iter() { + selected.push(*alg); + } + } else { + for alg in sig_algs.iter() { + selected.push(*alg); + } + } + + let cert_auths: ArrayVec = ArrayVec::new(); + + let cr = CertificateRequest::new(cert_types, selected, cert_auths); + cr.serialize(&[], body); + Ok(()) +} + +fn select_named_group( + client_groups: Option<&NamedGroupVec>, + server_groups: &[NamedGroup], +) -> Option { + if let Some(groups) = client_groups { + // Server preference order from Config::kx_groups() + for sg in server_groups { + if groups.iter().any(|g| g == sg) { + return Some(*sg); + } + } + // Client advertised supported_groups, but there is no overlap. + return None; + } + + // Fallback only when client did not advertise supported_groups: + // pick the first server-configured group. + server_groups.first().copied() +} + +fn select_ske_signature_algorithm( + client_algs: Option<&SignatureAndHashAlgorithmVec>, + our_sig: SignatureAlgorithm, + our_hash: HashAlgorithm, + supported_hashes: &[HashAlgorithm], +) -> SignatureAndHashAlgorithm { + // Prefer the key's native hash first, then fall back to the other + let hash_pref = match our_hash { + HashAlgorithm::SHA384 => [HashAlgorithm::SHA384, HashAlgorithm::SHA256], + _ => [HashAlgorithm::SHA256, HashAlgorithm::SHA384], + }; + + if let Some(list) = client_algs { + for h in hash_pref.iter() { + // Only consider hash algorithms the backend can actually sign with + if !supported_hashes.contains(h) { + continue; + } + if let Some(chosen) = list + .iter() + .find(|alg| alg.signature == our_sig && alg.hash == *h) + { + return *chosen; + } + } + } + + // Fallback: use the key's native hash + SignatureAndHashAlgorithm::new(our_hash, our_sig) +} + +fn select_certificate_request_sig_algs( + client_algs: Option<&SignatureAndHashAlgorithmVec>, +) -> SignatureAndHashAlgorithmVec { + // Only select algorithms supported by dimpl's signature verifiers. + let ours = SignatureAndHashAlgorithm::supported(); + + // Build intersection preserving client preference order + let mut out = ArrayVec::new(); + if let Some(list) = client_algs { + for alg in list.iter() { + if ours + .iter() + .any(|a| a.hash == alg.hash && a.signature == alg.signature) + { + out.push(*alg); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn named_group_vec(groups: &[NamedGroup]) -> NamedGroupVec { + let mut out = NamedGroupVec::new(); + for g in groups { + out.push(*g); + } + out + } + + #[test] + fn select_named_group_prefers_x25519_when_available() { + let client = named_group_vec(&[ + NamedGroup::Secp256r1, + NamedGroup::X25519, + NamedGroup::Secp384r1, + ]); + let provider = [NamedGroup::X25519, NamedGroup::Secp256r1]; + + let selected = select_named_group(Some(&client), &provider); + + assert_eq!(selected, Some(NamedGroup::X25519)); + } + + #[test] + fn select_named_group_respects_provider_capabilities() { + let client = named_group_vec(&[NamedGroup::X25519, NamedGroup::Secp256r1]); + let provider = [NamedGroup::Secp256r1]; + + let selected = select_named_group(Some(&client), &provider); + + assert_eq!(selected, Some(NamedGroup::Secp256r1)); + } + + #[test] + fn select_named_group_falls_back_to_provider_when_client_missing() { + let provider = [NamedGroup::Secp384r1]; + + let selected = select_named_group(None, &provider); + + assert_eq!(selected, Some(NamedGroup::Secp384r1)); + } + + #[test] + fn select_named_group_rejects_when_client_has_no_overlap() { + let client = named_group_vec(&[NamedGroup::X25519]); + let provider = [NamedGroup::Secp256r1]; + + let selected = select_named_group(Some(&client), &provider); + + assert_eq!(selected, None); + } + + #[test] + fn certificate_request_does_not_select_rsa_signatures() { + let mut client = SignatureAndHashAlgorithmVec::new(); + client.push(SignatureAndHashAlgorithm::new( + HashAlgorithm::SHA256, + SignatureAlgorithm::ECDSA, + )); + client.push(SignatureAndHashAlgorithm::new( + HashAlgorithm::SHA256, + SignatureAlgorithm::RSA, + )); + + let selected = select_certificate_request_sig_algs(Some(&client)); + + assert_eq!(selected.len(), 1); + assert_eq!(selected[0].signature, SignatureAlgorithm::ECDSA); + assert_eq!(selected[0].hash, HashAlgorithm::SHA256); + } + + #[test] + fn certificate_request_rejects_rsa_only_signatures() { + let mut client = SignatureAndHashAlgorithmVec::new(); + client.push(SignatureAndHashAlgorithm::new( + HashAlgorithm::SHA256, + SignatureAlgorithm::RSA, + )); + + let selected = select_certificate_request_sig_algs(Some(&client)); + + assert!(selected.is_empty()); + } +} diff --git a/third_party/dimpl/src/dtls13/client.rs b/third_party/dimpl/src/dtls13/client.rs new file mode 100644 index 0000000..47fdb4f --- /dev/null +++ b/third_party/dimpl/src/dtls13/client.rs @@ -0,0 +1,1720 @@ +// DTLS 1.3 Client Handshake Flow (RFC 9147): +// +// 1. Client sends ClientHello (plaintext, epoch 0) +// 2. Server may respond with HelloRetryRequest (special ServerHello with magic random) +// - If so, Client replaces transcript with message_hash and sends new ClientHello +// 3. Server sends ServerHello (plaintext, epoch 0) +// - Client derives handshake secrets, installs recv handshake keys, enables peer encryption +// 4. Server sends EncryptedExtensions (encrypted, epoch 2) +// 5. Server sends CertificateRequest (optional, encrypted, epoch 2) +// 6. Server sends Certificate (encrypted, epoch 2) +// 7. Server sends CertificateVerify (encrypted, epoch 2) +// 8. Server sends Finished (encrypted, epoch 2) +// - Client derives application secrets, installs application keys +// - Client installs send handshake keys for its own flight +// 9. Client sends Certificate (if requested, encrypted, epoch 2) +// 10. Client sends CertificateVerify (if cert present, encrypted, epoch 2) +// 11. Client sends Finished (encrypted, epoch 2) +// 12. Handshake complete, application data flows on epoch 3 +// +// This implementation is a Sans-IO DTLS 1.3 client. + +use std::collections::VecDeque; +use std::time::Instant; + +use arrayvec::ArrayVec; +use subtle::ConstantTimeEq; + +use crate::buffer::Buf; +use crate::buffer::ToBuf; +use crate::crypto::{ActiveKeyExchange, SrtpProfile}; +use crate::dtls13::Server; +use crate::dtls13::engine::Engine; +use crate::dtls13::message::Asn1Cert; +use crate::dtls13::message::Body; +use crate::dtls13::message::Certificate; +use crate::dtls13::message::CertificateEntry; +use crate::dtls13::message::ClientHello; +use crate::dtls13::message::CompressionMethod; +use crate::dtls13::message::ContentType; +use crate::dtls13::message::Cookie; +use crate::dtls13::message::DistinguishedName; +use crate::dtls13::message::Dtls13CipherSuite; +use crate::dtls13::message::Extension; +use crate::dtls13::message::ExtensionType; +use crate::dtls13::message::KeyShareClientHello; +use crate::dtls13::message::KeyShareEntry; +use crate::dtls13::message::KeyShareHelloRetryRequest; +use crate::dtls13::message::KeyShareServerHello; +use crate::dtls13::message::KeyUpdateRequest; +use crate::dtls13::message::MessageType; +use crate::dtls13::message::NamedGroup; +use crate::dtls13::message::ProtocolVersion; +use crate::dtls13::message::Random; +use crate::dtls13::message::SessionId; +use crate::dtls13::message::SignatureAlgorithmsExtension; +use crate::dtls13::message::SignatureScheme; +use crate::dtls13::message::SupportedGroupsExtension; +use crate::dtls13::message::SupportedVersionsClientHello; +use crate::dtls13::message::SupportedVersionsServerHello; +use crate::dtls13::message::UseSrtpExtension; +use crate::dtls13::message::parse_cookie_extension; +use crate::{Error, InternalError, KeyingMaterial, Output}; + +/// DTLS 1.3 client +pub struct Client { + /// Current client state. + state: State, + + /// Engine in common between server and client. + engine: Engine, + + /// Random unique data. Used for ClientHello. + random: Option, + + /// Legacy session ID echoed from ServerHello. + session_id: Option, + + /// Storage for extension data + extension_data: Buf, + + /// The negotiated SRTP profile (if any) + negotiated_srtp_profile: Option, + + /// Server certificates + server_certificates: Vec, + + /// Buffer for defragmenting handshakes + defragment_buffer: Buf, + + /// Whether the server requested client authentication + client_auth_requested: bool, + + /// Saved certificate_request_context from server's CertificateRequest + cert_request_context: Option, + + /// Cookie received from HRR, to echo in the retry ClientHello + saved_cookie: Option, + + /// The last now we seen + last_now: Instant, + + /// Local events + local_events: VecDeque, + + /// Data that is sent before we are connected. + queued_data: Vec, + + /// Whether we need to respond with our own KeyUpdate + pending_key_update_response: bool, + + /// Active key exchange state (ECDHE) + active_key_exchange: Option>, + + /// Whether we received a HelloRetryRequest + hello_retry: bool, + + /// Group selected by HRR for retry + hrr_selected_group: Option, + + /// Saved handshake secret for deriving application secrets + handshake_secret: Option, + + /// Client handshake traffic secret (for client Finished) + client_hs_traffic_secret: Option, + + /// Server handshake traffic secret (for server Finished verification) + server_hs_traffic_secret: Option, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum LocalEvent { + PeerCert, + Connected, + KeyingMaterial(ArrayVec, SrtpProfile), +} + +impl Client { + pub(crate) fn new_with_engine(mut engine: Engine, now: Instant) -> Client { + engine.set_client(true); + + Client { + state: State::SendClientHello, + engine, + random: None, + session_id: None, + extension_data: Buf::new(), + negotiated_srtp_profile: None, + server_certificates: Vec::with_capacity(3), + defragment_buffer: Buf::new(), + client_auth_requested: false, + cert_request_context: None, + saved_cookie: None, + last_now: now, + local_events: VecDeque::new(), + queued_data: Vec::new(), + pending_key_update_response: false, + active_key_exchange: None, + hello_retry: false, + hrr_selected_group: None, + handshake_secret: None, + client_hs_traffic_secret: None, + server_hs_traffic_secret: None, + } + } + + /// Create a client from a hybrid ClientHello probe. + /// + /// Injects the hybrid's transcript and ECDHE state into a fresh engine, + /// then starts in `AwaitServerHello`. The engine's handshake sequence + /// number is advanced to 1 (one CH has been sent). The hybrid CH was + /// already sent on the wire by `ClientPending`, so no record is + /// enqueued for output. + pub(crate) fn new_from_hybrid( + hybrid: crate::auto::HybridClientHello, + config: std::sync::Arc, + certificate: crate::DtlsCertificate, + now: Instant, + ) -> Result { + let mut engine = Engine::new(config, certificate); + engine.set_client(true); + + // Inject transcript + sequence state from the hybrid CH that was + // already sent on the wire by ClientPending. + engine.inject_hybrid_client_hello(&hybrid.transcript_bytes); + + let mut client = Client { + state: State::AwaitServerHello, + engine, + random: Some(hybrid.random), + session_id: None, + extension_data: Buf::new(), + negotiated_srtp_profile: None, + server_certificates: Vec::with_capacity(3), + defragment_buffer: Buf::new(), + client_auth_requested: false, + cert_request_context: None, + saved_cookie: None, + last_now: now, + local_events: VecDeque::new(), + queued_data: Vec::new(), + pending_key_update_response: false, + active_key_exchange: Some(hybrid.active_key_exchange), + hello_retry: false, + hrr_selected_group: None, + handshake_secret: None, + client_hs_traffic_secret: None, + server_hs_traffic_secret: None, + }; + client.handle_timeout(now)?; + Ok(client) + } + + pub fn into_server(self) -> Server { + Server::new_with_engine(self.engine, self.last_now, false) + } + + pub(crate) fn state_name(&self) -> &'static str { + self.state.name() + } + + pub fn is_closing(&self) -> bool { + (matches!(self.state, State::HalfClosedLocal | State::Closed) && !self.is_closed()) + || self.engine.close_notify_pending() + } + + pub fn is_closed(&self) -> bool { + self.state == State::Closed + && self.local_events.is_empty() + && !self.engine.has_pending_close_output() + } + + pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { + match self + .engine + .parse_packet(packet) + .and_then(|_| self.make_progress()) + { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { + if let Some(event) = self.local_events.pop_front() { + return event.into_output(buf, &self.server_certificates); + } + self.engine.poll_output(buf, self.last_now) + } + + /// Explicitly start the handshake process by sending a ClientHello + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + self.last_now = now; + if self.random.is_none() { + self.random = Some(self.engine.random()); + } + self.engine.handle_timeout(now)?; + match self.make_progress() { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + fn initiate_key_update(&mut self) -> Result<(), Error> { + self.engine + .create_key_update(KeyUpdateRequest::UpdateRequested) + } + + /// Send application data when the client is connected. + pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { + if self.state == State::Closed || self.state == State::HalfClosedLocal { + return Err(Error::ConnectionClosed); + } + + if self.state != State::AwaitApplicationData { + self.queued_data.push(data.to_buf()); + return Ok(()); + } + + let epoch = self.engine.app_send_epoch(); + self.engine.create_ciphertext_record( + ContentType::ApplicationData, + epoch, + false, + |body| { + body.extend_from_slice(data); + }, + )?; + + Ok(()) + } + + /// Initiate graceful shutdown by sending a `close_notify` alert. + pub fn close(&mut self) -> Result<(), Error> { + if self.state == State::Closed || self.state == State::HalfClosedLocal { + return Ok(()); + } + if self.state != State::AwaitApplicationData { + self.engine.abort(); + self.state = State::Closed; + return Ok(()); + } + let epoch = self.engine.app_send_epoch(); + self.engine + .create_ciphertext_record(ContentType::Alert, epoch, false, |body| { + body.push(1); // level: legacy (ignored in DTLS 1.3) + body.push(0); // description: close_notify + })?; + self.engine.cancel_flights(); + self.state = State::HalfClosedLocal; + Ok(()) + } + + fn make_progress(&mut self) -> Result<(), InternalError> { + loop { + let prev_state = self.state; + + let new_state = prev_state.make_progress(self)?; + if prev_state != new_state { + self.state = new_state; + trace!("{:?} -> {:?}", prev_state, new_state); + } else { + break; + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + SendClientHello, + AwaitServerHello, + AwaitEncryptedExtensions, + AwaitCertificateRequest, + AwaitCertificate, + AwaitCertificateVerify, + AwaitFinished, + SendCertificate, + SendCertificateVerify, + SendFinished, + AwaitApplicationData, + HalfClosedLocal, + Closed, +} + +impl State { + fn name(&self) -> &'static str { + match self { + State::SendClientHello => "SendClientHello", + State::AwaitServerHello => "AwaitServerHello", + State::AwaitEncryptedExtensions => "AwaitEncryptedExtensions", + State::AwaitCertificateRequest => "AwaitCertificateRequest", + State::AwaitCertificate => "AwaitCertificate", + State::AwaitCertificateVerify => "AwaitCertificateVerify", + State::AwaitFinished => "AwaitFinished", + State::SendCertificate => "SendCertificate", + State::SendCertificateVerify => "SendCertificateVerify", + State::SendFinished => "SendFinished", + State::AwaitApplicationData => "AwaitApplicationData", + State::HalfClosedLocal => "HalfClosedLocal", + State::Closed => "Closed", + } + } + + fn make_progress(self, client: &mut Client) -> Result { + match self { + State::SendClientHello => self.send_client_hello(client), + State::AwaitServerHello => self.await_server_hello(client), + State::AwaitEncryptedExtensions => self.await_encrypted_extensions(client), + State::AwaitCertificateRequest => self.await_certificate_request(client), + State::AwaitCertificate => self.await_certificate(client), + State::AwaitCertificateVerify => self.await_certificate_verify(client), + State::AwaitFinished => self.await_finished(client), + State::SendCertificate => self.send_certificate(client), + State::SendCertificateVerify => self.send_certificate_verify(client), + State::SendFinished => self.send_finished(client), + State::AwaitApplicationData => self.await_application_data(client), + State::HalfClosedLocal => self.half_closed_local(client), + State::Closed => Ok(self), + } + } + + fn send_client_hello(self, client: &mut Client) -> Result { + // unwrap: is ok because we set the random in handle_timeout + let random = client.random.unwrap(); + + // Determine flight number: 1 for initial CH, 3 for HRR retry + let flight_no = if client.hello_retry { 3 } else { 1 }; + client.engine.flight_begin(flight_no); + + // Generate key exchange for the first supported group (or HRR-selected group) + let group = if let Some(hrr_group) = client.hrr_selected_group { + hrr_group + } else { + // Use the first supported group from config (filtered) + client + .engine + .config() + .kx_groups() + .next() + .map(|g| g.name()) + .ok_or(Error::CryptoError( + crate::CryptoError::NoSupportedKeyExchangeGroups, + ))? + }; + + let kx_group = client + .engine + .find_kx_group(group) + .ok_or(Error::CryptoError( + crate::CryptoError::KeyExchangeGroupNotFound(group), + ))?; + + let key_exchange = if let Some(key_exchange) = client.active_key_exchange.take() { + key_exchange + } else { + let kx_buf = client.engine.pop_buffer(); + kx_group + .start_exchange(kx_buf) + .map_err(Error::CryptoError)? + }; + + // Build the key_share extension data into extension_data buffer + client.extension_data.clear(); + + // Serialize extensions into extension_data + let pub_key = key_exchange.pub_key(); + let pub_key_start = client.extension_data.len(); + client.extension_data.extend_from_slice(pub_key); + let pub_key_end = client.extension_data.len(); + + client.active_key_exchange = Some(key_exchange); + + // Store cookie data in extension_data if we have one from HRR + let cookie_range = if let Some(ref cookie) = client.saved_cookie { + let cookie_start = client.extension_data.len(); + client.extension_data.extend_from_slice(cookie); + let cookie_end = client.extension_data.len(); + Some(cookie_start..cookie_end) + } else { + None + }; + + client + .engine + .create_handshake(MessageType::ClientHello, |body, engine| { + handshake_create_client_hello( + body, + engine, + random, + group, + pub_key_start..pub_key_end, + cookie_range.clone(), + &client.extension_data, + ) + })?; + + Ok(Self::AwaitServerHello) + } + + fn await_server_hello(self, client: &mut Client) -> Result { + // Save transcript length so we can roll back if a stale HRR + // retransmission arrives after we already processed one. + let transcript_len_before = client.engine.transcript.len(); + + let maybe = client + .engine + .next_handshake(MessageType::ServerHello, &mut client.defragment_buffer)?; + + let Some(handshake) = maybe else { + return Ok(self); + }; + + let Body::ServerHello(ref server_hello) = handshake.body else { + unreachable!() + }; + + // Check for HelloRetryRequest (magic random) + if server_hello.is_hello_retry_request() { + if client.hello_retry { + client.engine.transcript.resize(transcript_len_before, 0); + return Err(Error::SecurityError( + crate::SecurityError::UnexpectedSecondHelloRetryRequest, + ) + .into()); + } + + debug!("Received HelloRetryRequest"); + + // Extract selected group and cookie from HRR extensions + if let Some(ref extensions) = server_hello.extensions { + for ext in extensions { + match ext.extension_type { + ExtensionType::KeyShare => { + let ext_data = ext.extension_data(&client.defragment_buffer); + if let Ok((_, hrr_ks)) = KeyShareHelloRetryRequest::parse(ext_data) { + client.hrr_selected_group = Some(hrr_ks.selected_group); + } + } + ExtensionType::Cookie => { + let ext_data = ext.extension_data(&client.defragment_buffer); + parse_cookie_extension(ext_data).map_err(InternalError::from)?; + let mut cookie = Buf::new(); + cookie.extend_from_slice(ext_data); + client.saved_cookie = Some(cookie); + } + _ => {} + } + } + } + + // Validate HRR cipher suite + if !client + .engine + .is_cipher_suite_allowed(server_hello.cipher_suite) + { + return Err((Error::SecurityError( + crate::SecurityError::HrrSelectedDisallowedCipherSuite, + )) + .into()); + } + client.engine.set_cipher_suite(server_hello.cipher_suite); + + // Validate HRR supported_versions + let mut hrr_version_ok = false; + if let Some(ref extensions) = server_hello.extensions { + for ext in extensions { + if ext.extension_type == ExtensionType::SupportedVersions { + let ext_data = ext.extension_data(&client.defragment_buffer); + if let Ok((_, sv)) = SupportedVersionsServerHello::parse(ext_data) { + hrr_version_ok = sv.selected_version == ProtocolVersion::DTLS1_3; + } + } + } + } + if !hrr_version_ok { + return Err( + (Error::SecurityError(crate::SecurityError::HrrDidNotSelectDtls13)).into(), + ); + } + + // Replace transcript with message_hash per RFC 8446 Section 4.4.1. + // The HRR was already appended to the transcript by next_handshake(). + // We must hash only CH1, then re-append the HRR bytes. + client + .engine + .replace_transcript_with_message_hash(transcript_len_before); + client.engine.advance_peer_handshake_seq(); + client.engine.reset_for_hello_retry(); + client.hello_retry = true; + + // Per RFC 9846 Section 4.2.2: a retry may replace key_share only when HRR + // contains key_share. Keep the original exchange for cookie-only + // retries so ClientHello2 and the eventual shared secret use the + // same key pair as ClientHello1. + if client.hrr_selected_group.is_some() { + client.active_key_exchange = None; + } + + return Ok(Self::SendClientHello); + } + + // Validate legacy_version (must be DTLS 1.2) + if server_hello.legacy_version != ProtocolVersion::DTLS1_2 { + return Err(Error::SecurityError( + crate::SecurityError::ServerHelloLegacyVersionNotDtls12, + ) + .into()); + } + + // Validate legacy_compression_method (must be null) + if server_hello.legacy_compression_method != CompressionMethod::Null { + return Err((Error::SecurityError( + crate::SecurityError::ServerHelloCompressionMustBeNull, + )) + .into()); + } + + debug!( + "Received ServerHello with cipher suite: {:?}", + server_hello.cipher_suite + ); + + // Validate cipher suite + let cs = server_hello.cipher_suite; + if cs.is_unknown() { + return Err((Error::SecurityError( + crate::SecurityError::ServerSelectedUnknownCipherSuite, + )) + .into()); + } + + if !client.engine.is_cipher_suite_allowed(cs) { + return Err(Error::SecurityError( + crate::SecurityError::ServerSelectedDisallowedDtls13CipherSuite(cs), + ) + .into()); + } + + client.engine.set_cipher_suite(cs); + client.session_id = Some(server_hello.legacy_session_id); + + // Validate supported_versions extension + let mut supported_version_ok = false; + let mut server_key_share: Option<(NamedGroup, std::ops::Range)> = None; + + let Some(ref extensions) = server_hello.extensions else { + return Err((Error::IncompleteServerHello).into()); + }; + + for ext in extensions { + match ext.extension_type { + ExtensionType::SupportedVersions => { + let ext_data = ext.extension_data(&client.defragment_buffer); + if let Ok((_, sv)) = SupportedVersionsServerHello::parse(ext_data) { + if sv.selected_version == ProtocolVersion::DTLS1_3 { + supported_version_ok = true; + } + } + } + ExtensionType::KeyShare => { + let ext_data = ext.extension_data(&client.defragment_buffer); + if let Ok((_, ks)) = KeyShareServerHello::parse(ext_data, 0) { + // The key_exchange data is at offset 0 within ext_data, but + // we stored it into defragment_buffer. We need the actual bytes. + let ke_bytes = ks.entry.key_exchange(ext_data); + // Store the group and a copy of the key exchange bytes + let ke_start = client.extension_data.len(); + client.extension_data.extend_from_slice(ke_bytes); + let ke_end = client.extension_data.len(); + server_key_share = Some((ks.entry.group, ke_start..ke_end)); + } + } + _ => {} + } + } + + if !supported_version_ok { + return Err( + Error::SecurityError(crate::SecurityError::ServerDidNotNegotiateDtls13).into(), + ); + } + + let Some((server_group, ke_range)) = server_key_share else { + return Err(Error::SecurityError(crate::SecurityError::ServerMissingKeyShare).into()); + }; + + // Complete ECDHE key exchange + let key_exchange = client + .active_key_exchange + .take() + .ok_or(Error::InvalidState( + crate::InvalidStateError::NoActiveKeyExchange, + ))?; + + if key_exchange.group() != server_group { + return Err( + Error::SecurityError(crate::SecurityError::ServerKeyShareGroupMismatch { + expected: key_exchange.group(), + actual: server_group, + }) + .into(), + ); + } + + let peer_pub_key = &client.extension_data[ke_range]; + let mut shared_secret = client.engine.pop_buffer(); + key_exchange + .complete(peer_pub_key, &mut shared_secret) + .map_err(Error::CryptoError)?; + + // Derive handshake secrets + let (c_hs_traffic, s_hs_traffic, handshake_secret) = + client.engine.derive_handshake_secrets(&shared_secret)?; + + // Save handshake secret for later application key derivation + client.handshake_secret = Some(handshake_secret); + client.engine.push_buffer(shared_secret); + + // Save traffic secrets for Finished verification and client flight + let mut s_hs_copy = Buf::new(); + s_hs_copy.extend_from_slice(&s_hs_traffic); + client.server_hs_traffic_secret = Some(s_hs_copy); + let mut c_hs_copy = Buf::new(); + c_hs_copy.extend_from_slice(&c_hs_traffic); + client.client_hs_traffic_secret = Some(c_hs_copy); + + // Install handshake keys (recv for server messages, send installed later) + client + .engine + .install_handshake_keys(&c_hs_traffic, &s_hs_traffic)?; + + // Enable peer encryption for server's epoch 2 messages + client.engine.enable_peer_encryption()?; + + client.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitEncryptedExtensions) + } + + fn await_encrypted_extensions(self, client: &mut Client) -> Result { + let maybe = client.engine.next_handshake( + MessageType::EncryptedExtensions, + &mut client.defragment_buffer, + )?; + + let Some(handshake) = maybe else { + return Ok(self); + }; + + let Body::EncryptedExtensions(ref ee) = handshake.body else { + unreachable!() + }; + + // Process extensions + for ext in &ee.extensions { + if ext.extension_type == ExtensionType::UseSrtp { + let ext_data = ext.extension_data(&client.defragment_buffer); + let (_, use_srtp) = + UseSrtpExtension::parse(ext_data).map_err(InternalError::from)?; + if !use_srtp.profiles.is_empty() { + client.negotiated_srtp_profile = Some(use_srtp.profiles[0].into()); + trace!( + "EncryptedExtensions UseSRTP; selected profile: {:?}", + client.negotiated_srtp_profile + ); + } + } + } + + client.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitCertificateRequest) + } + + fn await_certificate_request(self, client: &mut Client) -> Result { + // CertificateRequest is optional. Check if Certificate is available instead. + let has_cert = client + .engine + .has_complete_handshake(MessageType::Certificate); + + if has_cert { + return Ok(Self::AwaitCertificate); + } + + let maybe = client.engine.next_handshake( + MessageType::CertificateRequest, + &mut client.defragment_buffer, + )?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + // Parse CertificateRequest body + let Body::CertificateRequest(ref range) = handshake.body else { + unreachable!() + }; + let cr_range = range.clone(); + drop(maybe); + let cr_data = &client.defragment_buffer[cr_range.clone()]; + let context = parse_certificate_request(cr_data, cr_range.start)?; + if let Some(ctx) = context { + client.cert_request_context = Some(ctx); + } + + // CertificateRequest received - we'll send client Certificate + CertificateVerify + debug!("Received CertificateRequest; enabling client authentication path"); + client.client_auth_requested = true; + + client.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitCertificate) + } + + fn await_certificate(self, client: &mut Client) -> Result { + let maybe = client + .engine + .next_handshake(MessageType::Certificate, &mut client.defragment_buffer)?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + let Body::Certificate(ref certificate) = handshake.body else { + unreachable!() + }; + + if !certificate.context_range.is_empty() { + return Err(Error::CertificateError( + crate::CertificateError::ServerCertificateContextMustBeEmpty, + ) + .into()); + } + + if certificate.certificate_list.is_empty() { + return Err((Error::CertificateError( + crate::CertificateError::NoServerCertificateReceived, + )) + .into()); + } + + debug!( + "Received Certificate message with {} certificate(s)", + certificate.certificate_list.len() + ); + + // Extract certificate data before dropping handshake + let cert_ranges: ArrayVec<_, 32> = certificate + .certificate_list + .iter() + .map(|entry| entry.cert.as_slice(&client.defragment_buffer).to_vec()) + .collect(); + + drop(maybe); + + for (i, cert_data) in cert_ranges.iter().enumerate() { + trace!("Certificate #{} size: {} bytes", i + 1, cert_data.len()); + let mut buf = Buf::new(); + buf.extend_from_slice(cert_data); + client.server_certificates.push(buf); + } + + // Emit PeerCert event + if !client.server_certificates.is_empty() { + client.local_events.push_back(LocalEvent::PeerCert); + } + + client.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitCertificateVerify) + } + + fn await_certificate_verify(self, client: &mut Client) -> Result { + // Compute transcript hash BEFORE consuming CertificateVerify. + // Per RFC 8446 §4.4.3, the hash covers all messages up to but NOT + // including CertificateVerify. next_handshake() will append CV to + // the transcript, so we must capture the hash first. + let mut transcript_hash = Buf::new(); + client.engine.transcript_hash(&mut transcript_hash); + + let maybe = client.engine.next_handshake( + MessageType::CertificateVerify, + &mut client.defragment_buffer, + )?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + let Body::CertificateVerify(ref cv) = handshake.body else { + unreachable!() + }; + + let scheme = cv.signed.scheme; + let signature = cv.signed.signature(&client.defragment_buffer); + + // RFC 8446 §4.4.3: The receiver MUST verify that the signature algorithm + // is one that was offered in the signature_algorithms extension. + if !SignatureScheme::supported().contains(&scheme) { + return Err( + Error::SecurityError(crate::SecurityError::SignatureSchemeNotOffered(scheme)) + .into(), + ); + } + + // Build the signed content per RFC 8446 Section 4.4.3: + // 0x20 * 64 || "TLS 1.3, server CertificateVerify\0" || transcript_hash + let mut signed_content = Buf::new(); + signed_content.extend_from_slice(&[0x20u8; 64]); + signed_content.extend_from_slice(b"TLS 1.3, server CertificateVerify\0"); + signed_content.extend_from_slice(&transcript_hash); + + // Copy signature data since we need to drop handshake reference + let mut signature_copy = ArrayVec::::new(); + signature_copy + .try_extend_from_slice(signature) + .map_err(|_| Error::SecurityError(crate::SecurityError::SignatureTooLarge))?; + + drop(maybe); + + // Verify the signature + let cert_der = client + .server_certificates + .first() + .ok_or(Error::CertificateError( + crate::CertificateError::NoServerCertificateForVerification, + ))?; + + #[cfg(feature = "_crypto-common")] + verify_scheme_curve(scheme, cert_der)?; + + let (hash_alg, sig_alg) = signature_scheme_to_components(scheme)?; + + client.engine.verify_signature( + cert_der, + &signed_content, + &signature_copy, + hash_alg, + sig_alg, + )?; + + trace!("Server CertificateVerify verified: {:?}", scheme); + + client.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitFinished) + } + + fn await_finished(self, client: &mut Client) -> Result { + // Compute expected verify_data BEFORE consuming Finished + // (verify_data uses transcript hash up to but not including Finished) + let server_hs_secret = + client + .server_hs_traffic_secret + .as_ref() + .ok_or(Error::InvalidState( + crate::InvalidStateError::NoServerHandshakeTrafficSecret, + ))?; + let expected_verify_data = client.engine.compute_verify_data(server_hs_secret)?; + + let maybe = client + .engine + .next_handshake(MessageType::Finished, &mut client.defragment_buffer)?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + let Body::Finished(ref finished) = handshake.body else { + unreachable!() + }; + + let verify_data = finished.verify_data(&client.defragment_buffer); + + trace!( + "Finished.verify_data received len={}, expected len={}", + verify_data.len(), + expected_verify_data.len() + ); + + // Constant-time comparison + let is_eq: bool = verify_data.ct_eq(&*expected_verify_data).into(); + if !is_eq { + return Err((Error::SecurityError( + crate::SecurityError::ServerFinishedVerificationFailed, + )) + .into()); + } + + trace!("Server Finished verified successfully"); + + drop(maybe); + + client.engine.advance_peer_handshake_seq(); + + // Derive application secrets from handshake secret + transcript through server Finished + let handshake_secret = client.handshake_secret.as_ref().ok_or(Error::InvalidState( + crate::InvalidStateError::NoHandshakeSecretForApplicationKeyDerivation, + ))?; + + let (c_ap_traffic, s_ap_traffic) = + client.engine.derive_application_secrets(handshake_secret)?; + + // Install application keys + client + .engine + .install_application_keys(&c_ap_traffic, &s_ap_traffic)?; + + // Note: send handshake keys were already installed by install_handshake_keys() + // after ServerHello. Do NOT reinstall them here — that would reset hs_send_seq + // to 0, colliding with ACK records already sent on epoch 2. + + if client.client_auth_requested { + Ok(Self::SendCertificate) + } else { + Ok(Self::SendFinished) + } + } + + fn send_certificate(self, client: &mut Client) -> Result { + debug!("Sending Certificate"); + + // Start a new flight for the client's Certificate/CertificateVerify/Finished. + // This clears the old ClientHello flight from flight_saved_records. + client.engine.flight_begin(5); + + let has_cert = !client.engine.certificate_der().is_empty(); + + if has_cert { + let context = client.cert_request_context.as_deref().unwrap_or(&[]); + let mut context_copy = ArrayVec::::new(); + // unwrap: cert_request_context is u8-length-prefixed, max 255 bytes + context_copy.try_extend_from_slice(context).unwrap(); + + client + .engine + .create_handshake(MessageType::Certificate, |body, engine| { + handshake_create_certificate(body, engine, &context_copy) + })?; + + Ok(Self::SendCertificateVerify) + } else { + // No client certificate: send empty Certificate and skip CertificateVerify + let context = client.cert_request_context.as_deref().unwrap_or(&[]); + let mut context_copy = ArrayVec::::new(); + // unwrap: cert_request_context is u8-length-prefixed, max 255 bytes + context_copy.try_extend_from_slice(context).unwrap(); + + client + .engine + .create_handshake(MessageType::Certificate, |body, _engine| { + // certificate_request_context + body.push(context_copy.len() as u8); + body.extend_from_slice(&context_copy); + // empty certificate_list (3-byte zero length) + body.extend_from_slice(&[0, 0, 0]); + Ok(()) + })?; + + Ok(Self::SendFinished) + } + } + + fn send_certificate_verify(self, client: &mut Client) -> Result { + debug!("Sending CertificateVerify"); + + client + .engine + .create_handshake(MessageType::CertificateVerify, |body, engine| { + handshake_create_certificate_verify( + body, + engine, + b"TLS 1.3, client CertificateVerify\0", + ) + })?; + + Ok(Self::SendFinished) + } + + fn send_finished(self, client: &mut Client) -> Result { + trace!("Sending Finished message to complete handshake"); + + // When the server did NOT request client authentication, we skip + // send_certificate (which calls flight_begin(5)). Start flight 5 + // here so the old ClientHello flight records are cleared before + // building the Finished retransmission set. + if !client.client_auth_requested { + client.engine.flight_begin(5); + } + + let client_hs_secret = + client + .client_hs_traffic_secret + .as_ref() + .ok_or(Error::InvalidState( + crate::InvalidStateError::NoClientHandshakeTrafficSecretForFinished, + ))?; + let mut client_hs_secret_copy = Buf::new(); + client_hs_secret_copy.extend_from_slice(client_hs_secret); + let client_hs_secret = client_hs_secret_copy; + + client + .engine + .create_handshake(MessageType::Finished, |body, engine| { + let verify_data = engine.compute_verify_data(&client_hs_secret)?; + body.extend_from_slice(&verify_data); + Ok(()) + })?; + + // Don't stop flight timers here - the server needs to receive our Finished. + // Timers will stop when we receive an ACK from the server confirming it + // received our epoch-2 flight. + + // Emit Connected event + client.local_events.push_back(LocalEvent::Connected); + + // Extract and emit SRTP keying material if negotiated + if let Some(profile) = client.negotiated_srtp_profile { + if let Ok((keying_material, profile)) = + client.engine.extract_srtp_keying_material(profile) + { + debug!( + "SRTP keying material extracted ({} bytes) for profile: {:?}", + keying_material.len(), + profile + ); + client + .local_events + .push_back(LocalEvent::KeyingMaterial(keying_material, profile)); + } + } + + client.engine.release_application_data(); + + debug!("Handshake complete; ready for application data"); + + Ok(Self::AwaitApplicationData) + } + + fn await_application_data(self, client: &mut Client) -> Result { + // Auto-trigger KeyUpdate when AEAD encryption limit is reached + if client.engine.needs_key_update() && !client.engine.is_key_update_in_flight() { + client.initiate_key_update()?; + } + + // Send queued application data + if !client.queued_data.is_empty() { + let epoch = client.engine.app_send_epoch(); + debug!( + "Sending queued application data: {}", + client.queued_data.len() + ); + for data in client.queued_data.drain(..) { + client.engine.create_ciphertext_record( + ContentType::ApplicationData, + epoch, + false, + |body| { + body.extend_from_slice(&data); + }, + )?; + } + } + + // Send pending KeyUpdate response before processing new KeyUpdates + if client.pending_key_update_response { + client + .engine + .create_key_update(KeyUpdateRequest::UpdateNotRequested)?; + client.pending_key_update_response = false; + } + + // Check for incoming KeyUpdate + if client.engine.has_complete_handshake(MessageType::KeyUpdate) { + let maybe = client.engine.next_handshake_no_transcript( + MessageType::KeyUpdate, + &mut client.defragment_buffer, + )?; + + if let Some(handshake) = maybe { + let Body::KeyUpdate(request) = handshake.body else { + unreachable!() + }; + + // Install new recv keys + client.engine.update_recv_keys()?; + + // ACK the KeyUpdate record + client.engine.send_ack()?; + + // If peer requested us to update, schedule our own KeyUpdate + if request == KeyUpdateRequest::UpdateRequested + && !client.engine.is_key_update_in_flight() + { + client.pending_key_update_response = true; + } + + client.engine.advance_peer_handshake_seq(); + debug!("Received KeyUpdate (request={:?})", request); + } + } + + Ok(self) + } + + fn half_closed_local(self, client: &mut Client) -> Result { + // Write half is closed: drain incoming KeyUpdate to keep recv keys in sync, + // but do not send our own KeyUpdate response. + if client.engine.has_complete_handshake(MessageType::KeyUpdate) { + let maybe = client.engine.next_handshake_no_transcript( + MessageType::KeyUpdate, + &mut client.defragment_buffer, + )?; + if let Some(handshake) = maybe { + let Body::KeyUpdate(_) = handshake.body else { + unreachable!() + }; + client.engine.update_recv_keys()?; + client.engine.advance_peer_handshake_seq(); + } + } + + if client.engine.close_notify_received() { + return Ok(State::Closed); + } + + Ok(self) + } +} + +// ========================================================================= +// Helper Functions +// ========================================================================= + +fn handshake_create_client_hello( + body: &mut Buf, + engine: &mut Engine, + random: Random, + kx_group: NamedGroup, + pub_key_range: std::ops::Range, + cookie_range: Option>, + extension_data: &Buf, +) -> Result<(), Error> { + let legacy_version = ProtocolVersion::DTLS1_2; + let legacy_session_id = SessionId::empty(); + // DTLS 1.3: legacy_cookie MUST be zero length + let legacy_cookie = Cookie::empty(); + + // Cipher suites from config (filtered) + let cipher_suites: ArrayVec = engine + .config() + .dtls13_cipher_suites() + .map(|cs| cs.suite()) + .take(3) + .collect(); + + debug!( + "Sending ClientHello: offering {} cipher suites", + cipher_suites.len() + ); + + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + // Build extensions + let mut extensions: ArrayVec = ArrayVec::new(); + let mut ext_buf = Buf::new(); + + // 1. supported_versions extension (DTLS 1.3) + let sv_start = ext_buf.len(); + let mut versions = ArrayVec::new(); + versions.push(ProtocolVersion::DTLS1_3); + let sv = SupportedVersionsClientHello { versions }; + sv.serialize(&mut ext_buf); + let sv_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::SupportedVersions, + extension_data_range: sv_start..sv_end, + }); + + // 2. supported_groups extension + let sg_start = ext_buf.len(); + let groups: ArrayVec = engine.config().kx_groups().map(|g| g.name()).collect(); + let sg = SupportedGroupsExtension { groups }; + sg.serialize(&mut ext_buf); + let sg_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::SupportedGroups, + extension_data_range: sg_start..sg_end, + }); + + // 3. key_share extension + let ks_start = ext_buf.len(); + let mut entries = ArrayVec::new(); + entries.push(KeyShareEntry { + group: kx_group, + key_exchange_range: pub_key_range, + }); + let ks = KeyShareClientHello { entries }; + ks.serialize(extension_data, &mut ext_buf); + let ks_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::KeyShare, + extension_data_range: ks_start..ks_end, + }); + + // 4. signature_algorithms extension + let sa_start = ext_buf.len(); + let sa = SignatureAlgorithmsExtension::default(); + sa.serialize(&mut ext_buf); + let sa_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::SignatureAlgorithms, + extension_data_range: sa_start..sa_end, + }); + + // 5. use_srtp extension + let srtp_start = ext_buf.len(); + let use_srtp = UseSrtpExtension::default(); + use_srtp.serialize(&mut ext_buf); + let srtp_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::UseSrtp, + extension_data_range: srtp_start..srtp_end, + }); + + // 6. cookie extension (echo from HRR if present) + if let Some(cookie_range) = cookie_range { + let cookie_start = ext_buf.len(); + // Cookie data already includes the u16 length prefix from the HRR + ext_buf.extend_from_slice(&extension_data[cookie_range]); + let cookie_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::Cookie, + extension_data_range: cookie_start..cookie_end, + }); + } + + // 7. padding extension (RFC 7685) — pad ClientHello to fill the MTU, + // reducing the server-to-client amplification factor. + let mtu = engine.config().mtu(); + let record_header = 13; // DTLSPlaintext header + let handshake_header = 12; // DTLS handshake header + let body_without_padding = 2 // legacy_version + + 32 // random + + 1 + legacy_session_id.len() + + 1 + legacy_cookie.len() + + 2 + cipher_suites.len() * 2 + + 1 + compression_methods.len() + + 2 // extensions_len + + extensions.len() * 4 // type(2) + len(2) per extension + + ext_buf.len(); // all extension data + let total_without_padding = record_header + handshake_header + body_without_padding; + let deficit = mtu.saturating_sub(total_without_padding); + if deficit >= 4 { + let pad_data_len = deficit - 4; + let pad_start = ext_buf.len(); + for _ in 0..pad_data_len { + ext_buf.push(0); + } + let pad_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::Padding, + extension_data_range: pad_start..pad_end, + }); + } + + let mut client_hello = ClientHello::new( + legacy_version, + random, + legacy_session_id, + legacy_cookie, + cipher_suites, + compression_methods, + ); + client_hello.extensions = extensions; + + client_hello.serialize(&ext_buf, body); + Ok(()) +} + +pub(crate) fn handshake_create_certificate( + body: &mut Buf, + engine: &mut Engine, + context: &[u8], +) -> Result<(), Error> { + // Build a source buffer: context bytes then cert DER + let mut src = Buf::new(); + let context_start = src.len(); + src.extend_from_slice(context); + let context_end = src.len(); + + let cert_start = src.len(); + src.extend_from_slice(engine.certificate_der()); + let cert_end = src.len(); + + let mut certificate_list = ArrayVec::new(); + certificate_list.push(CertificateEntry { + cert: Asn1Cert(cert_start..cert_end), + extensions_range: 0..0, + }); + + let certificate = Certificate { + context_range: context_start..context_end, + certificate_list, + }; + + certificate.serialize(&src, body); + Ok(()) +} + +pub(crate) fn handshake_create_certificate_verify( + body: &mut Buf, + engine: &mut Engine, + context_string: &[u8], +) -> Result<(), Error> { + // Build signed content: 0x20*64 || context_string || transcript_hash + let mut signed_content = Buf::new(); + signed_content.extend_from_slice(&[0x20u8; 64]); + signed_content.extend_from_slice(context_string); + + let mut transcript_hash = Buf::new(); + engine.transcript_hash(&mut transcript_hash); + signed_content.extend_from_slice(&transcript_hash); + + // Sign with our private key + let hash_alg = engine.signing_key().hash_algorithm(); + let sig_alg = engine.signing_key().algorithm(); + + let mut signature = Buf::new(); + engine + .signing_key() + .sign(&signed_content, hash_alg, &mut signature) + .map_err(Error::CryptoError)?; + + // Determine the SignatureScheme from hash_alg + sig_alg + let scheme = match (sig_alg, hash_alg) { + (crate::types::SignatureAlgorithm::ECDSA, crate::types::HashAlgorithm::SHA256) => { + SignatureScheme::ECDSA_SECP256R1_SHA256 + } + (crate::types::SignatureAlgorithm::ECDSA, crate::types::HashAlgorithm::SHA384) => { + SignatureScheme::ECDSA_SECP384R1_SHA384 + } + (crate::types::SignatureAlgorithm::RSA, crate::types::HashAlgorithm::SHA256) => { + SignatureScheme::RSA_PSS_RSAE_SHA256 + } + _ => { + return Err(Error::CryptoError( + crate::CryptoError::UnsupportedSignaturePair { + signature: sig_alg, + hash: hash_alg, + }, + )); + } + }; + + // Write CertificateVerify: scheme(2) + signature_len(2) + signature + body.extend_from_slice(&scheme.as_u16().to_be_bytes()); + body.extend_from_slice(&(signature.len() as u16).to_be_bytes()); + body.extend_from_slice(&signature); + + Ok(()) +} + +/// Map a TLS 1.3 SignatureScheme to the (HashAlgorithm, SignatureAlgorithm) pair +/// needed by the SignatureVerifier trait. +pub(crate) fn signature_scheme_to_components( + scheme: SignatureScheme, +) -> Result< + ( + crate::types::HashAlgorithm, + crate::types::SignatureAlgorithm, + ), + Error, +> { + use crate::types::{HashAlgorithm, SignatureAlgorithm}; + match scheme { + SignatureScheme::ECDSA_SECP256R1_SHA256 => { + Ok((HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA)) + } + SignatureScheme::ECDSA_SECP384R1_SHA384 => { + Ok((HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA)) + } + SignatureScheme::ECDSA_SECP521R1_SHA512 => { + Ok((HashAlgorithm::SHA512, SignatureAlgorithm::ECDSA)) + } + SignatureScheme::ED25519 => Err(Error::SecurityError( + crate::SecurityError::UnsupportedSignatureScheme(scheme), + )), + SignatureScheme::RSA_PSS_RSAE_SHA256 => { + Ok((HashAlgorithm::SHA256, SignatureAlgorithm::RSA)) + } + SignatureScheme::RSA_PSS_RSAE_SHA384 => { + Ok((HashAlgorithm::SHA384, SignatureAlgorithm::RSA)) + } + SignatureScheme::RSA_PSS_RSAE_SHA512 => { + Ok((HashAlgorithm::SHA512, SignatureAlgorithm::RSA)) + } + SignatureScheme::RSA_PSS_PSS_SHA256 => Ok((HashAlgorithm::SHA256, SignatureAlgorithm::RSA)), + SignatureScheme::RSA_PSS_PSS_SHA384 => Ok((HashAlgorithm::SHA384, SignatureAlgorithm::RSA)), + SignatureScheme::RSA_PSS_PSS_SHA512 => Ok((HashAlgorithm::SHA512, SignatureAlgorithm::RSA)), + SignatureScheme::RSA_PKCS1_SHA256 + | SignatureScheme::RSA_PKCS1_SHA384 + | SignatureScheme::RSA_PKCS1_SHA512 => Err(Error::SecurityError( + crate::SecurityError::UnsupportedSignatureScheme(scheme), + )), + _ => Err(Error::SecurityError( + crate::SecurityError::UnsupportedSignatureScheme(scheme), + )), + } +} + +/// RFC 8446 §4.4.3: For ECDSA schemes, verify the curve in the [`SignatureScheme`] +/// matches the certificate's public key curve. +#[cfg(feature = "_crypto-common")] +pub(crate) fn verify_scheme_curve(scheme: SignatureScheme, cert_der: &[u8]) -> Result<(), Error> { + if let Some(expected_group) = scheme.named_group() { + let cert_group = + crate::crypto::cert_named_group(cert_der).map_err(Error::CertificateError)?; + if expected_group != cert_group { + return Err(Error::SecurityError( + crate::SecurityError::SignatureSchemeCertificateCurveMismatch { + scheme, + expected: expected_group, + actual: cert_group, + }, + )); + } + } + Ok(()) +} + +/// Parse a TLS 1.3 CertificateRequest message (RFC 8446 Section 4.3.2). +/// +/// Extracts the certificate_request_context and parses extensions including +/// certificate_authorities. Returns the context if non-empty. +fn parse_certificate_request(cr_data: &[u8], base_offset: usize) -> Result, Error> { + if cr_data.is_empty() { + return Ok(None); + } + + // certificate_request_context<0..255> + let context_len = cr_data[0] as usize; + let mut pos = 1; + let mut context = None; + if context_len > 0 { + if cr_data.len() < 1 + context_len { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::CertificateRequestContextTruncated, + )); + } + let mut ctx = Buf::new(); + ctx.extend_from_slice(&cr_data[pos..pos + context_len]); + context = Some(ctx); + pos += context_len; + } + + // extensions<2..2^16-1> + if cr_data.len() < pos + 2 { + return Ok(context); + } + let ext_len = u16::from_be_bytes([cr_data[pos], cr_data[pos + 1]]) as usize; + pos += 2; + + let ext_end = pos + ext_len; + if cr_data.len() < ext_end { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::CertificateRequestExtensionsTruncated, + )); + } + + // Parse individual extensions + while pos + 4 <= ext_end { + let ext_type = u16::from_be_bytes([cr_data[pos], cr_data[pos + 1]]); + let ext_data_len = u16::from_be_bytes([cr_data[pos + 2], cr_data[pos + 3]]) as usize; + pos += 4; + + if pos + ext_data_len > ext_end { + break; + } + + if ext_type == ExtensionType::CertificateAuthorities.as_u16() { + // Parse certificate_authorities: DistinguishedName<3..2^16-1> + let ca_data = &cr_data[pos..pos + ext_data_len]; + if ca_data.len() >= 2 { + let list_len = u16::from_be_bytes([ca_data[0], ca_data[1]]) as usize; + let list_data = &ca_data[2..]; + if list_data.len() >= list_len { + let ca_base = base_offset + pos + 2; + let mut rest = &list_data[..list_len]; + while !rest.is_empty() { + let offset = + ca_base + (rest.as_ptr() as usize - list_data.as_ptr() as usize); + match DistinguishedName::parse(rest, offset) { + Ok((r, _dn)) => rest = r, + Err(_) => break, + } + } + } + } + } + + pos += ext_data_len; + } + + Ok(context) +} + +// ========================================================================= +// Standard Trait Impls +// ========================================================================= + +impl LocalEvent { + pub fn into_output<'a>(self, buf: &'a mut [u8], peer_certs: &[Buf]) -> Output<'a> { + match self { + LocalEvent::PeerCert => { + let l = peer_certs[0].len(); + assert!( + l <= buf.len(), + "Output buffer too small for peer certificate" + ); + buf[..l].copy_from_slice(&peer_certs[0]); + Output::PeerCert(&buf[..l]) + } + LocalEvent::Connected => Output::Connected, + LocalEvent::KeyingMaterial(m, profile) => { + Output::KeyingMaterial(KeyingMaterial::new(&m), profile) + } + } + } +} + +#[cfg(all(test, feature = "rcgen"))] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::Config; + use crate::certificate::generate_self_signed_certificate; + use crate::{CryptoError, SecurityError}; + + #[derive(Debug)] + struct TestKeyExchange { + group: NamedGroup, + } + + impl ActiveKeyExchange for TestKeyExchange { + fn pub_key(&self) -> &[u8] { + &[] + } + + fn complete(self: Box, _peer_pub: &[u8], _out: &mut Buf) -> Result<(), CryptoError> { + unreachable!("mismatched server key share should fail before completing ECDHE") + } + + fn group(&self) -> NamedGroup { + self.group + } + } + + fn client() -> Client { + let cert = generate_self_signed_certificate().expect("generate cert"); + let engine = Engine::new(Arc::new(Config::default()), cert); + Client::new_with_engine(engine, Instant::now()) + } + + fn epoch0_handshake_packet(msg_type: MessageType, message_seq: u16, body: &[u8]) -> Vec { + let handshake_len = 12 + body.len(); + let mut packet = Vec::new(); + packet.push(ContentType::Handshake.as_u8()); + packet.extend_from_slice(&[0xfe, 0xfd]); + packet.extend_from_slice(&0u16.to_be_bytes()); + packet.extend_from_slice(&0u64.to_be_bytes()[2..]); + packet.extend_from_slice(&(handshake_len as u16).to_be_bytes()); + packet.push(msg_type.as_u8()); + packet.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); + packet.extend_from_slice(&message_seq.to_be_bytes()); + packet.extend_from_slice(&0u32.to_be_bytes()[1..]); + packet.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]); + packet.extend_from_slice(body); + packet + } + + fn server_hello_with_key_share(group: NamedGroup) -> Vec { + let mut key_share = Vec::new(); + key_share.extend_from_slice(&group.as_u16().to_be_bytes()); + key_share.extend_from_slice(&1u16.to_be_bytes()); + key_share.push(0); + + let mut extensions = Vec::new(); + extensions.extend_from_slice(&ExtensionType::SupportedVersions.as_u16().to_be_bytes()); + extensions.extend_from_slice(&2u16.to_be_bytes()); + extensions.extend_from_slice(&ProtocolVersion::DTLS1_3.as_u16().to_be_bytes()); + extensions.extend_from_slice(&ExtensionType::KeyShare.as_u16().to_be_bytes()); + extensions.extend_from_slice(&(key_share.len() as u16).to_be_bytes()); + extensions.extend_from_slice(&key_share); + + let mut body = Vec::new(); + body.extend_from_slice(&ProtocolVersion::DTLS1_2.as_u16().to_be_bytes()); + body.extend_from_slice(&[7; 32]); + body.push(0); // legacy_session_id + body.extend_from_slice(&Dtls13CipherSuite::AES_128_GCM_SHA256.as_u16().to_be_bytes()); + body.push(CompressionMethod::Null.as_u8()); + body.extend_from_slice(&(extensions.len() as u16).to_be_bytes()); + body.extend_from_slice(&extensions); + body + } + + #[test] + fn empty_server_certificate_is_certificate_error() { + let mut client = client(); + client.engine.advance_peer_handshake_seq(); // ServerHello + client.engine.advance_peer_handshake_seq(); // EncryptedExtensions + + client + .engine + .parse_packet(&epoch0_handshake_packet( + MessageType::Certificate, + 2, + &[0, 0, 0, 0], + )) + .expect("queue empty Certificate"); + + let err = State::AwaitCertificate + .await_certificate(&mut client) + .expect_err("empty server Certificate should fail"); + + assert!(matches!( + err, + crate::InternalError::Fatal(Error::CertificateError(_)) + )); + } + + #[test] + fn server_key_share_group_mismatch_reports_expected_and_actual_groups() { + let mut client = client(); + client.active_key_exchange = Some(Box::new(TestKeyExchange { + group: NamedGroup::X25519, + })); + + client + .engine + .parse_packet(&epoch0_handshake_packet( + MessageType::ServerHello, + 0, + &server_hello_with_key_share(NamedGroup::Secp256r1), + )) + .expect("queue mismatched ServerHello"); + + let err = State::AwaitServerHello + .await_server_hello(&mut client) + .expect_err("mismatched server key share group should fail"); + + assert!(matches!( + err, + crate::InternalError::Fatal(Error::SecurityError( + SecurityError::ServerKeyShareGroupMismatch { + expected: NamedGroup::X25519, + actual: NamedGroup::Secp256r1, + } + )) + )); + } +} diff --git a/third_party/dimpl/src/dtls13/engine.rs b/third_party/dimpl/src/dtls13/engine.rs new file mode 100644 index 0000000..6d82216 --- /dev/null +++ b/third_party/dimpl/src/dtls13/engine.rs @@ -0,0 +1,2860 @@ +use std::mem; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::{Duration, Instant}; + +use arrayvec::ArrayVec; + +use super::queue::{QueueRx, QueueTx}; +use crate::buffer::{Buf, BufferPool, TmpBuf}; +use crate::crypto::Aad; +use crate::crypto::Cipher; +use crate::crypto::HmacProvider; +use crate::crypto::Nonce; +use crate::crypto::SigningKey; +use crate::crypto::SupportedDtls13CipherSuite; +use crate::crypto::SupportedKxGroup; +use crate::crypto::prf_hkdf; +use crate::dtls13::incoming::{Incoming, Record, RecordHandler}; +use crate::dtls13::message::Body; +use crate::dtls13::message::ContentType; +use crate::dtls13::message::Dtls13CipherSuite; +use crate::dtls13::message::Dtls13Record; +use crate::dtls13::message::Handshake; +use crate::dtls13::message::Header; +use crate::dtls13::message::KeyUpdateRequest; +use crate::dtls13::message::MessageType; +use crate::dtls13::message::Sequence; +use crate::timer::ExponentialBackoff; +use crate::types::{HashAlgorithm, Random}; +use crate::window::ReplayWindow; +use crate::{Config, DtlsCertificate, Error, InternalError, Output, SeededRng}; + +const MAX_DEFRAGMENT_PACKETS: usize = 50; + +/// Maximum DTLS sequence number (2^48 - 1). Per RFC 9147 §4.2, +/// implementations MUST NOT allow the sequence number to wrap. +const MAX_SEQUENCE_NUMBER: u64 = (1u64 << 48) - 1; + +pub struct Engine { + /// Configuration options. + config: Arc, + + /// Saved certificate + certificate: DtlsCertificate, + + /// Seedable random number generator for deterministic testing + rng: SeededRng, + + /// Pool of buffers + buffers_free: BufferPool, + + /// Counters for sending DTLSPlaintext during epoch 0. + sequence_epoch_0: Sequence, + + /// Queue of incoming packets. + queue_rx: QueueRx, + + /// Queue of outgoing packets. + queue_tx: QueueTx, + + /// The cipher suite in use. Set by ServerHello. + cipher_suite: Option, + + /// Handshake send keys (epoch 2) + hs_send_keys: Option, + + /// Handshake receive keys (epoch 2) + hs_recv_keys: Option, + + /// Expected next receive sequence number for epoch 2 (handshake) + hs_expected_recv_seq: u64, + + /// Application send epoch (3 initially, increments on KeyUpdate) + app_send_epoch: u16, + + /// Sequence number for handshake epoch (epoch 2) sending + hs_send_seq: u64, + + /// Sequence number within current send epoch + app_send_seq: u64, + + /// Application send keys (only latest epoch; replaced on KeyUpdate) + app_send_keys: Option, + + /// Previous application send keys, retained for KeyUpdate retransmission. + prev_app_send_keys: Option, + + /// Epoch of the previous send keys. + prev_app_send_epoch: u16, + + /// Next sequence number on the previous send epoch (for retransmissions). + prev_app_send_seq: u64, + + /// Application receive keys. Multiple epochs may coexist due to KeyUpdate. + app_recv_keys: ArrayVec, + + /// Whether the remote peer has enabled encryption + peer_encryption_enabled: bool, + + /// Signing key for CertificateVerify + signing_key: Box, + + /// Whether this engine is for a client (true) or server (false) + is_client: bool, + + /// Expected peer handshake sequence number + peer_handshake_seq_no: u16, + + /// Next handshake message sequence number for sending + next_handshake_seq_no: u16, + + /// Handshakes collected for hash computation. + /// TLS 1.3 transcript: msg_type(1) + length(3), no DTLS framing. + pub(crate) transcript: Buf, + + /// Anti-replay window for handshake epoch (epoch 2) + hs_replay: ReplayWindow, + + /// Record numbers of received handshake records, for ACK generation. + /// Each entry is (epoch, sequence_number). + received_record_numbers: ArrayVec<(u64, u64), 32>, + + /// Deadline for sending a handshake ACK (epoch 2). + /// Set when we detect gaps or partial flights during handshake. + handshake_ack_deadline: Option, + + /// When true, the next record must start a fresh datagram instead of + /// appending to the current last buffer in queue_tx. + datagram_sealed: bool, + + /// The records that have been sent in the current flight. + flight_saved_records: ArrayVec, + + /// Flight backoff + flight_backoff: ExponentialBackoff, + + /// Timeout for the current flight + flight_timeout: Timeout, + + /// Global timeout for the entire connect operation. + connect_timeout: Timeout, + + /// Whether we are ready to release application data from poll_output. + release_app_data: bool, + + /// Exporter master secret for TLS 1.3 exporters (RFC 8446 Section 7.5). + exporter_master_secret: Option, + + /// Number of AEAD encryptions on the current application send keys. + app_send_record_count: u64, + + /// Jittered threshold for the current key epoch. When `app_send_record_count` + /// reaches this value, a KeyUpdate is triggered. Randomized to + /// `[3/4 * configured_limit, configured_limit]` to prevent both sides from + /// initiating KeyUpdate simultaneously when using the same config. + aead_encryption_threshold: u64, + + /// Set when app_send_record_count reaches aead_encryption_threshold. + needs_key_update: bool, + + /// A locally sent KeyUpdate is awaiting its ACK. Send keys are rotated only + /// after that ACK arrives, so application data continues on the old epoch. + key_update_in_flight: bool, + + /// Sequence number of the received close_notify alert, if any. + /// Per RFC 9147 §5.10, any data with an epoch/sequence number pair + /// after this must be discarded; earlier records are still valid. + close_notify_sequence: Option, + + /// Whether [`Output::CloseNotify`] has already been emitted. + close_notify_reported: bool, +} + +struct EpochKeys { + cipher: Box, + iv: [u8; 12], + traffic_secret: Buf, + sn_key: Buf, +} + +struct RecvEpochEntry { + epoch: u16, + keys: EpochKeys, + expected_recv_seq: u64, + replay: ReplayWindow, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Timeout { + Disabled, + Unarmed, + Armed(Instant), +} + +#[derive(Debug)] +struct Entry { + content_type: ContentType, + epoch: u16, + send_seq: u64, + fragment: Buf, + acked: bool, +} + +enum PollOutput<'a> { + Data(&'a [u8]), + BufferTooSmall { needed: usize }, + None(&'a mut [u8]), +} + +impl Engine { + pub fn new(config: Arc, certificate: DtlsCertificate) -> Self { + let mut rng = SeededRng::new(config.rng_seed()); + + let flight_backoff = + ExponentialBackoff::new(config.flight_start_rto(), config.flight_retries(), &mut rng); + + let signing_key = config + .crypto_provider() + .key_provider + .load_private_key(&certificate.private_key) + .expect("Failed to load private key"); + + let aead_encryption_threshold = + jittered_aead_threshold(config.aead_encryption_limit(), &mut rng); + + Self { + config, + certificate, + rng, + buffers_free: BufferPool::default(), + sequence_epoch_0: Sequence::new(0), + queue_rx: QueueRx::new(), + queue_tx: QueueTx::new(), + cipher_suite: None, + hs_send_keys: None, + hs_recv_keys: None, + hs_expected_recv_seq: 0, + app_send_epoch: 3, + hs_send_seq: 0, + app_send_seq: 0, + app_send_keys: None, + prev_app_send_keys: None, + prev_app_send_epoch: 0, + prev_app_send_seq: 0, + app_recv_keys: ArrayVec::new(), + peer_encryption_enabled: false, + signing_key, + is_client: false, + peer_handshake_seq_no: 0, + next_handshake_seq_no: 0, + transcript: Buf::new(), + hs_replay: ReplayWindow::new(), + received_record_numbers: ArrayVec::new(), + handshake_ack_deadline: None, + datagram_sealed: false, + flight_saved_records: ArrayVec::new(), + flight_backoff, + flight_timeout: Timeout::Unarmed, + connect_timeout: Timeout::Unarmed, + release_app_data: false, + exporter_master_secret: None, + app_send_record_count: 0, + aead_encryption_threshold, + needs_key_update: false, + key_update_in_flight: false, + close_notify_sequence: None, + close_notify_reported: false, + } + } + + pub fn into_fallback(self) -> (Arc, DtlsCertificate) { + (self.config, self.certificate) + } + + pub fn set_client(&mut self, is_client: bool) { + self.is_client = is_client; + } + + /// Inject a pre-built hybrid ClientHello into this engine. + /// + /// Inject the transcript and state from a hybrid ClientHello that was + /// already sent on the wire by [`ClientPending`]. + /// + /// Sets the transcript, advances the handshake sequence number to 1, + /// and bumps the epoch-0 record sequence so subsequent records don't + /// collide. Does **not** enqueue the record for output — the hybrid + /// CH was already transmitted. + pub fn inject_hybrid_client_hello(&mut self, transcript_bytes: &[u8]) { + self.transcript.extend_from_slice(transcript_bytes); + self.next_handshake_seq_no = 1; + // Advance past the record sequence used by the hybrid CH. + // Defense-in-depth: guard against epoch-0 sequence overflow. + if self.sequence_epoch_0.sequence_number < MAX_SEQUENCE_NUMBER { + self.sequence_epoch_0.sequence_number += 1; + } + } + + pub fn config(&self) -> &Config { + &self.config + } + + pub fn cipher_suite(&self) -> Option { + self.cipher_suite + } + + pub fn set_cipher_suite(&mut self, cipher_suite: Dtls13CipherSuite) { + self.cipher_suite = Some(cipher_suite); + } + + pub fn app_send_epoch(&self) -> u16 { + self.app_send_epoch + } + + pub fn is_key_update_in_flight(&self) -> bool { + self.key_update_in_flight + } + + /// Returns true if the AEAD encryption limit has been reached and a + /// KeyUpdate should be initiated. Clears the flag after returning true. + pub fn needs_key_update(&mut self) -> bool { + if self.needs_key_update { + self.needs_key_update = false; + true + } else { + false + } + } + + pub fn is_cipher_suite_allowed(&self, suite: Dtls13CipherSuite) -> bool { + self.config + .dtls13_cipher_suites() + .any(|cs| cs.suite() == suite) + } + + pub fn certificate_der(&self) -> &[u8] { + &self.certificate.certificate + } + + pub fn signing_key(&mut self) -> &mut dyn SigningKey { + &mut *self.signing_key + } + + pub fn parse_packet(&mut self, packet: &[u8]) -> Result<(), InternalError> { + let cs = self.cipher_suite; + let incoming = Incoming::parse_packet(packet, self, cs)?; + if let Some(incoming) = incoming { + self.insert_incoming(incoming)?; + } + + Ok(()) + } + + fn insert_incoming(&mut self, incoming: Incoming) -> Result<(), Error> { + if self.queue_rx.len() >= self.config.max_queue_rx() { + warn!( + "Receive queue full (max {}): {:?}", + self.config.max_queue_rx(), + self.queue_rx + ); + return Err(Error::ReceiveQueueFull); + } + + if incoming.first().first_handshake().is_some() { + self.insert_incoming_handshake(incoming) + } else { + self.insert_incoming_non_handshake(incoming) + } + } + + fn insert_incoming_handshake(&mut self, incoming: Incoming) -> Result<(), Error> { + let first_record = incoming.first(); + let handshake = first_record + .first_handshake() + .expect("caller ensures handshake"); + + let key_current = ( + handshake.header.message_seq, + handshake.header.fragment_offset, + ); + + let maybe_dupe_seq = incoming + .records() + .iter() + .filter_map(|r| r.first_handshake()) + .filter_map(|h| h.dupe_triggers_resend()) + .next(); + + if let Some(dupe_seq) = maybe_dupe_seq { + if dupe_seq < self.peer_handshake_seq_no { + self.flight_resend("dupe triggers resend")?; + } + } + + // Drop old duplicates we've already processed + if handshake.header.message_seq < self.peer_handshake_seq_no { + return Ok(()); + } + + // Reject new handshakes after initial handshake is complete, + // but allow KeyUpdate (a post-handshake message). + if self.release_app_data + && handshake.header.message_seq >= self.peer_handshake_seq_no + && handshake.header.msg_type != MessageType::KeyUpdate + { + return Err(Error::RenegotiationAttempt); + } + + let search_result = self.queue_rx.binary_search_by(|item| { + let key_other = item + .first() + .first_handshake() + .as_ref() + .map(|h| (h.header.message_seq, h.header.fragment_offset)) + .unwrap_or((u16::MAX, u32::MAX)); + key_other.cmp(&key_current) + }); + + match search_result { + Err(index) => { + // Track received record numbers for ACK generation + for record in incoming.records().iter() { + let seq = record.record().sequence; + if seq.epoch >= 2 && record.record().content_type == ContentType::Handshake { + let _ = self + .received_record_numbers + .try_push((seq.epoch as u64, seq.sequence_number)); + } + } + self.queue_rx.insert(index, incoming); + } + Ok(index) => { + // Duplicate message_seq + fragment_offset. Replace if either: + // (a) the existing entry was already consumed (handled), so a + // fresh retransmission (e.g., CH2 after HRR) can be processed. + // (b) the existing entry looks corrupted: its total `length` + // differs from `fragment_length` while the new entry's match, + // indicating the retransmission corrected a bit-flip. + let existing = &self.queue_rx[index]; + let should_replace = existing.first().is_handled() || { + let existing_corrupt = existing + .first() + .first_handshake() + .map(|h| h.header.length != h.header.fragment_length) + .unwrap_or(false); + let incoming_ok = incoming + .first() + .first_handshake() + .map(|h| h.header.length == h.header.fragment_length) + .unwrap_or(false); + existing_corrupt && incoming_ok + }; + if should_replace { + for record in incoming.records().iter() { + let seq = record.record().sequence; + if seq.epoch >= 2 && record.record().content_type == ContentType::Handshake + { + let _ = self + .received_record_numbers + .try_push((seq.epoch as u64, seq.sequence_number)); + } + } + self.queue_rx[index] = incoming; + } + } + } + + Ok(()) + } + + fn insert_incoming_non_handshake(&mut self, incoming: Incoming) -> Result<(), Error> { + let first = incoming.first(); + let seq_current = first.record().sequence; + + let search_result = self + .queue_rx + .binary_search_by_key(&seq_current, |item| item.first().record().sequence); + + match search_result { + Err(index) => self.queue_rx.insert(index, incoming), + Ok(_) => { + // Duplicate - silently drop. For encrypted records (epoch >= 2) the replay + // window filters most duplicates, but undecrypted ciphertext records can + // reach here before enable_peer_encryption is called. + } + } + + Ok(()) + } + + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + if self.connect_timeout == Timeout::Unarmed { + debug!( + "Connect timeout in: {:.03}s", + self.config.handshake_timeout().as_secs_f32() + ); + let timeout = now + self.config.handshake_timeout(); + self.connect_timeout = Timeout::Armed(timeout); + } + if self.flight_timeout == Timeout::Unarmed { + debug!( + "Flight timeout in: {:.03}s", + self.flight_backoff.rto().as_secs_f32() + ); + let timeout = now + self.flight_backoff.rto(); + self.flight_timeout = Timeout::Armed(timeout); + } + + if let Timeout::Armed(connect_timeout) = self.connect_timeout { + if now >= connect_timeout { + return Err(Error::Timeout(crate::TimeoutError::Connect)); + } + } + + let Timeout::Armed(flight_timeout) = self.flight_timeout else { + return Ok(()); + }; + + if now >= flight_timeout { + if self.flight_backoff.can_retry() { + self.flight_backoff.attempt(&mut self.rng); + debug!( + "Re-arm flight timeout due to resend in {}", + self.flight_backoff.rto().as_secs_f32() + ); + let timeout = now + self.flight_backoff.rto(); + self.flight_timeout = Timeout::Armed(timeout); + self.flight_resend("flight timeout")?; + } else { + return Err(Error::Timeout(crate::TimeoutError::Handshake)); + } + } + + // During handshake, schedule/flush ACKs to help peer with selective retransmission + self.maybe_schedule_handshake_ack(now); + self.maybe_flush_handshake_ack(now)?; + + Ok(()) + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8], now: Instant) -> Output<'a> { + self.purge_handled_queue_rx(); + + let buf = match self.poll_app_data(buf) { + PollOutput::Data(p) => return Output::ApplicationData(p), + PollOutput::BufferTooSmall { needed } => return Output::BufferTooSmall { needed }, + PollOutput::None(b) => b, + }; + + self.maybe_schedule_handshake_ack(now); + + match self.poll_packet_tx(buf) { + PollOutput::Data(p) => return Output::Packet(p), + PollOutput::BufferTooSmall { needed } => return Output::BufferTooSmall { needed }, + PollOutput::None(_) => {} + } + + if self.close_notify_sequence.is_some() && !self.close_notify_reported { + self.close_notify_reported = true; + return Output::CloseNotify; + } + + let next_timeout = self.poll_timeout(now); + + Output::Timeout(next_timeout) + } + + fn poll_app_data<'a>(&mut self, buf: &'a mut [u8]) -> PollOutput<'a> { + if !self.release_app_data { + return PollOutput::None(buf); + } + + let mut unhandled = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .filter(|r| r.record().content_type == ContentType::ApplicationData) + .skip_while(|r| r.is_handled()); + + let Some(next) = unhandled.next() else { + return PollOutput::None(buf); + }; + + let record_buffer = next.buffer(); + let fragment = next.record().fragment(record_buffer); + let len = fragment.len(); + + if len > buf.len() { + return PollOutput::BufferTooSmall { needed: len }; + } + + buf[..len].copy_from_slice(fragment); + next.set_handled(); + + PollOutput::Data(&buf[..len]) + } + + fn purge_handled_queue_rx(&mut self) { + while let Some(peek) = self.queue_rx.front() { + let fully_handled = peek.records().iter().all(|r| r.is_handled()); + + if fully_handled { + let incoming = self.queue_rx.pop_front().unwrap(); + incoming + .into_records() + .for_each(|r| self.buffers_free.push(r.into_buffer())); + } else { + break; + } + } + } + + fn poll_packet_tx<'a>(&mut self, buf: &'a mut [u8]) -> PollOutput<'a> { + let Some(p) = self.queue_tx.front() else { + return PollOutput::None(buf); + }; + + if p.len() > buf.len() { + return PollOutput::BufferTooSmall { needed: p.len() }; + } + + let p = self + .queue_tx + .pop_front() + .expect("queue front checked above"); + let len = p.len(); + buf[..len].copy_from_slice(&p); + + PollOutput::Data(&buf[..len]) + } + + /// Prevent subsequent records from being appended to the current last + /// datagram in queue_tx. The next record will start a fresh datagram. + fn seal_current_datagram(&mut self) { + self.datagram_sealed = true; + } + + fn poll_timeout(&self, now: Instant) -> Instant { + if self.connect_timeout == Timeout::Disabled + && self.flight_timeout == Timeout::Disabled + && self.handshake_ack_deadline.is_none() + { + const DISTANT_FUTURE: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60); + return now + DISTANT_FUTURE; + } + + let mut timeout = match (self.connect_timeout, self.flight_timeout) { + (Timeout::Armed(c), Timeout::Armed(f)) => { + if c < f { + c + } else { + f + } + } + (Timeout::Armed(c), _) => c, + (_, Timeout::Armed(f)) => f, + _ => now + Duration::from_secs(10 * 365 * 24 * 60 * 60), + }; + + if let Some(deadline) = self.handshake_ack_deadline { + if deadline < timeout { + timeout = deadline; + } + } + + timeout + } + + pub fn flight_begin(&mut self, flight_no: u8) { + debug!("Begin flight {}", flight_no); + self.flight_backoff.reset(&mut self.rng); + self.flight_clear_resends(); + self.flight_timeout = Timeout::Unarmed; + } + + pub fn flight_stop_resend_timers(&mut self) { + debug!("Stop connect and flight timeouts"); + self.flight_timeout = Timeout::Disabled; + self.connect_timeout = Timeout::Disabled; + } + + fn flight_clear_resends(&mut self) { + for entry in self.flight_saved_records.drain(..) { + self.buffers_free.push(entry.fragment); + } + } + + pub fn flight_resend(&mut self, reason: &str) -> Result<(), Error> { + debug!("Resending flight due to {}", reason); + let mut records = mem::take(&mut self.flight_saved_records); + + // Mark the current last datagram as "sealed" so resent records + // go into fresh datagrams. Without this, can_append would pack + // resent records into the same datagram as the original flight, + // which causes duplicate handshake fragments at the receiver. + self.seal_current_datagram(); + + for entry in &mut records { + // Selective retransmission: skip records that have been ACKed + if entry.acked { + continue; + } + + if entry.epoch == 0 { + // Capture the sequence number the retransmitted record will use + let new_seq = self.sequence_epoch_0.sequence_number; + self.create_plaintext_record(entry.content_type, false, |fragment| { + fragment.extend_from_slice(&entry.fragment); + })?; + entry.send_seq = new_seq; + } else { + // Capture the sequence number the retransmitted record will use + let new_seq = if entry.epoch == 2 { + self.hs_send_seq + } else if self.prev_app_send_keys.is_some() + && entry.epoch == self.prev_app_send_epoch + { + self.prev_app_send_seq + } else { + self.app_send_seq + }; + self.create_ciphertext_record( + entry.content_type, + entry.epoch, + false, + |fragment| { + fragment.extend_from_slice(&entry.fragment); + }, + )?; + entry.send_seq = new_seq; + } + } + + self.flight_saved_records = records; + + Ok(()) + } + + pub fn has_complete_handshake(&mut self, wanted: MessageType) -> bool { + self.has_complete_handshake_with_seq(wanted, self.peer_handshake_seq_no) + } + + fn has_complete_handshake_with_seq(&mut self, wanted: MessageType, expected_seq: u16) -> bool { + let mut skip_handled = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + .take(MAX_DEFRAGMENT_PACKETS) + .flat_map(|r| r.handshakes().iter()) + .skip_while(|h| h.is_handled()) + .peekable(); + + let maybe_first_handshake = skip_handled.peek(); + + let Some(first) = maybe_first_handshake else { + return false; + }; + + if first.header.message_seq != expected_seq { + return false; + } + + if first.header.msg_type != wanted { + return false; + } + + let wanted_seq = first.header.message_seq; + let wanted_length = first.header.length; + let mut last_fragment_end = 0; + + for h in skip_handled { + if wanted_seq != h.header.message_seq { + continue; + } + + // Overlap-tolerant: only reject if there's an actual gap + if h.header.fragment_offset > last_fragment_end { + return false; + } + let end = h.header.fragment_offset + h.header.fragment_length; + if end > last_fragment_end { + last_fragment_end = end; + } + + if last_fragment_end == wanted_length { + return true; + } + } + + false + } + + pub fn next_handshake( + &mut self, + wanted: MessageType, + defragment_buffer: &mut Buf, + ) -> Result, InternalError> { + self.next_handshake_with_options(wanted, defragment_buffer, false) + } + + pub(crate) fn next_client_hello_for_auto_sense( + &mut self, + defragment_buffer: &mut Buf, + ) -> Result, InternalError> { + self.next_handshake_with_options(MessageType::ClientHello, defragment_buffer, true) + } + + fn next_handshake_with_options( + &mut self, + wanted: MessageType, + defragment_buffer: &mut Buf, + allow_unknown_client_hello_suites: bool, + ) -> Result, InternalError> { + if !self.has_complete_handshake(wanted) { + return Ok(None); + } + + let iter = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + .flat_map(|r| r.handshakes().iter().map(move |h| (h, r.buffer()))) + .skip_while(|(h, _)| h.is_handled()); + + let handshake = if allow_unknown_client_hello_suites { + Handshake::defragment_allow_unknown_client_hello_suites( + iter, + defragment_buffer, + self.cipher_suite, + Some(&mut self.transcript), + ) + } else { + Handshake::defragment( + iter, + defragment_buffer, + self.cipher_suite, + Some(&mut self.transcript), + ) + }?; + + Ok(Some(handshake)) + } + + /// Like `next_handshake` but does NOT update the transcript hash. + /// Used for post-handshake messages like KeyUpdate. + pub fn next_handshake_no_transcript( + &mut self, + wanted: MessageType, + defragment_buffer: &mut Buf, + ) -> Result, InternalError> { + if !self.has_complete_handshake(wanted) { + return Ok(None); + } + + let iter = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + .flat_map(|r| r.handshakes().iter().map(move |h| (h, r.buffer()))) + .skip_while(|(h, _)| h.is_handled()); + + let handshake = Handshake::defragment( + iter, + defragment_buffer, + self.cipher_suite, + None, // no transcript update + )?; + + Ok(Some(handshake)) + } + + /// Advance the expected peer handshake sequence number. + /// + /// Must be called by the caller of `next_handshake` / `next_handshake_no_transcript` + /// AFTER all validation of the handshake body succeeds. This prevents stale + /// retransmissions from advancing the counter before validation can reject them. + pub fn advance_peer_handshake_seq(&mut self) { + self.peer_handshake_seq_no += 1; + } + + /// Create a DTLSPlaintext record (epoch 0, unencrypted). + pub fn create_plaintext_record( + &mut self, + content_type: ContentType, + save_fragment: bool, + f: F, + ) -> Result<(), Error> + where + F: FnOnce(&mut Buf), + { + let mut fragment = self.buffers_free.pop(); + f(&mut fragment); + + let current_seq = self.sequence_epoch_0.sequence_number; + + if save_fragment { + let mut clone = self.buffers_free.pop(); + clone.extend_from_slice(&fragment); + self.flight_saved_records.push(Entry { + content_type, + epoch: 0, + send_seq: current_seq, + fragment: clone, + acked: false, + }); + } + + let record_wire_len = Dtls13Record::PLAINTEXT_HEADER_LEN + fragment.len(); + + let can_append = !self.datagram_sealed + && self + .queue_tx + .back() + .map(|b| b.len() + record_wire_len <= self.config.mtu()) + .unwrap_or(false); + + if !can_append && self.queue_tx.len() >= self.config.max_queue_tx() { + warn!( + "Transmit queue full (max {}): {:?}", + self.config.max_queue_tx(), + self.queue_tx + ); + return Err(Error::TransmitQueueFull); + } + + let sequence = self.sequence_epoch_0; + + let record = Dtls13Record { + content_type, + sequence, + length: fragment.len() as u16, + fragment_range: 0..fragment.len(), + }; + + if self.sequence_epoch_0.sequence_number >= MAX_SEQUENCE_NUMBER { + return Err(Error::CryptoError( + crate::CryptoError::Epoch0SequenceNumberExhausted, + )); + } + self.sequence_epoch_0.sequence_number += 1; + + if can_append { + let last = self.queue_tx.back_mut().unwrap(); + record.serialize(&fragment, last); + } else { + self.datagram_sealed = false; + let mut buffer = self.buffers_free.pop(); + buffer.clear(); + record.serialize(&fragment, &mut buffer); + self.queue_tx.push_back(buffer); + } + + self.buffers_free.push(fragment); + + Ok(()) + } + + /// Create a DTLSCiphertext record (epoch >= 2, encrypted). + /// + /// The plaintext fragment is wrapped as DTLSInnerPlaintext: + /// `content || content_type(1) || zeros*` before AEAD encryption. + pub fn create_ciphertext_record( + &mut self, + content_type: ContentType, + epoch: u16, + save_fragment: bool, + f: F, + ) -> Result<(), Error> + where + F: FnOnce(&mut Buf), + { + let mut fragment = self.buffers_free.pop(); + f(&mut fragment); + + // Determine sequence number for this record + let seq = if epoch == 2 { + self.hs_send_seq + } else if self.prev_app_send_keys.is_some() && epoch == self.prev_app_send_epoch { + self.prev_app_send_seq + } else { + self.app_send_seq + }; + + if save_fragment { + let mut clone = self.buffers_free.pop(); + clone.extend_from_slice(&fragment); + self.flight_saved_records.push(Entry { + content_type, + epoch, + send_seq: seq, + fragment: clone, + acked: false, + }); + } + + // Build DTLSInnerPlaintext: content || content_type(1) + // (no zero padding for now) + fragment.push(content_type.as_u8()); + + let suite = self.suite_provider(); + let tag_len = suite.tag_len(); + + // Get the send keys for this epoch + let keys = if epoch == 2 { + self.hs_send_keys.as_mut() + } else if self.prev_app_send_keys.is_some() && epoch == self.prev_app_send_epoch { + self.prev_app_send_keys.as_mut() + } else { + self.app_send_keys.as_mut() + }; + + let Some(keys) = keys else { + return Err(Error::CryptoError( + crate::CryptoError::SendKeysNotAvailable { epoch }, + )); + }; + + // Construct the nonce: iv XOR padded_seq + let nonce = Nonce::xor(&keys.iv, seq); + + // Build the unified header for AAD + // Always use S=1 (2-byte seq) and L=1 (length present) + let epoch_bits = (epoch & 0x03) as u8; + let flags: u8 = 0b0010_0000 + | 0b0000_1000 // S=1 + | 0b0000_0100 // L=1 + | epoch_bits; + + let ciphertext_len = fragment.len() + tag_len; + + let mut header_buf = [0u8; 5]; + header_buf[0] = flags; + header_buf[1..3].copy_from_slice(&(seq as u16).to_be_bytes()); + header_buf[3..5].copy_from_slice(&(ciphertext_len as u16).to_be_bytes()); + + let aad = Aad::new_dtls13(&header_buf); + + // Save sn_key before losing mutable borrow of keys + let mut sn_key = [0u8; 32]; + let sn_key_len = keys.sn_key.len(); + sn_key[..sn_key_len].copy_from_slice(&keys.sn_key); + + // Encrypt in place (appends tag) + keys.cipher + .encrypt(&mut fragment, aad, nonce) + .map_err(Error::CryptoError)?; + + // Record number encryption (RFC 9147 Section 4.2.3): + // mask = AES-ECB(sn_key, ciphertext_sample) + // XOR mask[0..2] over the sequence number bytes in the header + let sn_mask = if fragment.len() >= 16 { + // unwrap: we checked length >= 16 + let ciphertext_sample: [u8; 16] = fragment[..16].try_into().unwrap(); + suite.encrypt_sn(&sn_key[..sn_key_len], &ciphertext_sample) + } else { + [0u8; 16] // degenerate case: no masking if ciphertext too short + }; + + // Unified header: flags(1) + seq(2) + length(2) = 5 bytes + let record_wire_len = 5 + fragment.len(); + + let can_append = !self.datagram_sealed + && self + .queue_tx + .back() + .map(|b| b.len() + record_wire_len <= self.config.mtu()) + .unwrap_or(false); + + if !can_append && self.queue_tx.len() >= self.config.max_queue_tx() { + warn!( + "Transmit queue full (max {}): {:?}", + self.config.max_queue_tx(), + self.queue_tx + ); + return Err(Error::TransmitQueueFull); + } + + // Build the record for serialization + let record = Dtls13Record { + content_type: ContentType::ApplicationData, + sequence: Sequence { + epoch, + sequence_number: seq, + }, + length: fragment.len() as u16, + fragment_range: 0..fragment.len(), + }; + + // Increment send sequence, guarding against 48-bit overflow (RFC 9147 §4.2) + if epoch == 2 { + if self.hs_send_seq >= MAX_SEQUENCE_NUMBER { + return Err(Error::CryptoError( + crate::CryptoError::SendSequenceNumberExhausted { epoch }, + )); + } + self.hs_send_seq += 1; + } else if self.prev_app_send_keys.is_some() && epoch == self.prev_app_send_epoch { + if self.prev_app_send_seq >= MAX_SEQUENCE_NUMBER { + return Err(Error::CryptoError( + crate::CryptoError::SendSequenceNumberExhausted { epoch }, + )); + } + self.prev_app_send_seq += 1; + } else { + if self.app_send_seq >= MAX_SEQUENCE_NUMBER { + return Err(Error::CryptoError( + crate::CryptoError::SendSequenceNumberExhausted { epoch }, + )); + } + self.app_send_seq += 1; + + // Track AEAD encryptions on current application keys + if epoch >= 3 { + self.app_send_record_count += 1; + if self.app_send_record_count >= self.aead_encryption_threshold { + self.needs_key_update = true; + } + } + } + + if can_append { + let last = self.queue_tx.back_mut().unwrap(); + let header_start = last.len(); + record.serialize(&fragment, last); + // Apply record number encryption: XOR mask over seq bytes + // Seq bytes are at offset header_start+1..header_start+3 + last[header_start + 1] ^= sn_mask[0]; + last[header_start + 2] ^= sn_mask[1]; + } else { + self.datagram_sealed = false; + let mut buffer = self.buffers_free.pop(); + buffer.clear(); + record.serialize(&fragment, &mut buffer); + // Apply record number encryption: XOR mask over seq bytes + buffer[1] ^= sn_mask[0]; + buffer[2] ^= sn_mask[1]; + self.queue_tx.push_back(buffer); + } + + self.buffers_free.push(fragment); + + Ok(()) + } + + /// Create a handshake message and wrap it in a DTLS record. + pub fn create_handshake(&mut self, msg_type: MessageType, f: F) -> Result<(), Error> + where + F: FnOnce(&mut Buf, &mut Self) -> Result<(), Error>, + { + let mut body_buffer = self.buffers_free.pop(); + + f(&mut body_buffer, self)?; + + let handshake_header = Header { + msg_type, + length: body_buffer.len() as u32, + message_seq: self.next_handshake_seq_no, + fragment_offset: 0, + fragment_length: body_buffer.len() as u32, + }; + + // Write TLS 1.3 transcript: msg_type(1) + length(3) + body (no DTLS framing) + self.transcript.push(msg_type.as_u8()); + self.transcript + .extend_from_slice(&handshake_header.length.to_be_bytes()[1..]); + self.transcript + .extend_from_slice(&body_buffer[..handshake_header.length as usize]); + + self.next_handshake_seq_no += 1; + + let epoch = epoch_for_message(msg_type); + let total_len = body_buffer.len(); + let mut offset: usize = 0; + + let handshake_header_len = 12usize; + let tag_len = if epoch >= 2 { + self.suite_provider().tag_len() + } else { + 0 + }; + // Per-record protection overhead on the wire: tag + 1 byte inner + // content type (the DTLS 1.3 record protection layer's expansion). + let protection_overhead = if epoch >= 2 { tag_len + 1 } else { 0 }; + + while offset < total_len || (total_len == 0 && offset == 0) { + let already_used_in_current = self.queue_tx.back().map(|b| b.len()).unwrap_or(0); + let available_in_current = self.config.mtu().saturating_sub(already_used_in_current); + + let record_header_len = if epoch == 0 { + Dtls13Record::PLAINTEXT_HEADER_LEN + } else { + 5 // unified header: flags(1) + seq(2) + length(2) + }; + + let fixed_overhead = record_header_len + handshake_header_len + protection_overhead; + + let available_for_body = if available_in_current > fixed_overhead { + available_in_current - fixed_overhead + } else { + self.config.mtu().saturating_sub(fixed_overhead) + }; + + let remaining_body_bytes = total_len.saturating_sub(offset); + + let chunk_len = if total_len == 0 { + 0 + } else { + remaining_body_bytes.min(available_for_body) + }; + + let frag_range = if chunk_len == 0 { + 0..0 + } else { + offset..offset + chunk_len + }; + + let frag_handshake = Handshake { + header: Header { + msg_type, + length: handshake_header.length, + message_seq: handshake_header.message_seq, + fragment_offset: offset as u32, + fragment_length: chunk_len as u32, + }, + body: Body::Fragment(frag_range), + handled: AtomicBool::new(false), + }; + + if epoch == 0 { + self.create_plaintext_record(ContentType::Handshake, true, |fragment| { + frag_handshake.serialize(&body_buffer, fragment); + })?; + } else { + self.create_ciphertext_record(ContentType::Handshake, epoch, true, |fragment| { + frag_handshake.serialize(&body_buffer, fragment); + })?; + } + + if total_len == 0 { + break; + } + + offset += chunk_len; + } + + self.buffers_free.push(body_buffer); + + Ok(()) + } + + /// Release application data from the incoming queue. + /// + /// Also clears handshake receive keys to prevent epoch collision: + /// after 3+ KeyUpdates the app recv epoch's low 2 bits can match + /// the handshake epoch (2), causing records to be routed to stale + /// handshake keys instead of the correct application keys. + pub fn release_application_data(&mut self) { + self.release_app_data = true; + self.hs_recv_keys = None; + } + + pub fn release_application_data_retaining_handshake_keys(&mut self) { + self.release_app_data = true; + } + + /// Whether a close_notify alert has been received from the peer. + pub fn close_notify_received(&self) -> bool { + self.close_notify_sequence.is_some() + } + + /// Whether a received close_notify still needs to be surfaced. + pub fn close_notify_pending(&self) -> bool { + self.close_notify_sequence.is_some() && !self.close_notify_reported + } + + /// Whether close-related output remains to be polled. + pub fn has_pending_close_output(&self) -> bool { + !self.queue_tx.is_empty() || self.close_notify_pending() + } + + /// Cancel in-flight retransmissions without clearing the transmit queue. + /// Used by close() to stop retransmitting control records while still + /// allowing the queued close_notify alert to be sent. + pub fn cancel_flights(&mut self) { + self.flight_saved_records.clear(); + self.flight_timeout = Timeout::Disabled; + self.connect_timeout = Timeout::Disabled; + self.handshake_ack_deadline = None; + } + + /// Abort the connection: flush all queued output, retransmission state, and + /// disable timers so that no further packets are emitted. + pub fn abort(&mut self) { + self.queue_tx.clear(); + self.flight_saved_records.clear(); + self.flight_timeout = Timeout::Disabled; + self.connect_timeout = Timeout::Disabled; + self.handshake_ack_deadline = None; + } + + /// Send an ACK record listing received handshake record numbers. + /// + /// ACK format: record_numbers_length(2) + N * (epoch(8) + sequence(8)) + pub fn send_ack(&mut self) -> Result<(), Error> { + self.send_ack_inner(false) + } + + pub fn send_ack_retransmittable(&mut self) -> Result<(), Error> { + if !self.received_record_numbers.is_empty() { + self.flight_clear_resends(); + } + self.send_ack_inner(true) + } + + fn send_ack_inner(&mut self, save_fragment: bool) -> Result<(), Error> { + if self.received_record_numbers.is_empty() { + return Ok(()); + } + + let entries = mem::take(&mut self.received_record_numbers); + let epoch = if self.app_send_keys.is_some() { + self.app_send_epoch + } else { + 2 + }; + + self.create_ciphertext_record(ContentType::Ack, epoch, save_fragment, |fragment| { + // record_numbers_length: 2 bytes, value = entries.len() * 16 + let len = (entries.len() * 16) as u16; + fragment.extend_from_slice(&len.to_be_bytes()); + for &(ep, seq) in &entries { + fragment.extend_from_slice(&ep.to_be_bytes()); + fragment.extend_from_slice(&seq.to_be_bytes()); + } + })?; + + Ok(()) + } + + /// Process an incoming ACK record, marking acknowledged flight entries. + fn process_ack(&mut self, ack_data: &[u8]) -> Result<(), Error> { + if ack_data.len() < 2 { + return Ok(()); + } + + let record_numbers_len = u16::from_be_bytes([ack_data[0], ack_data[1]]) as usize; + let entries_data = &ack_data[2..]; + + if entries_data.len() != record_numbers_len || record_numbers_len % 16 != 0 { + return Ok(()); + } + + let num_entries = record_numbers_len / 16; + for i in 0..num_entries { + let offset = i * 16; + if offset + 16 > entries_data.len() { + break; + } + let ack_epoch = u64::from_be_bytes( + // unwrap: bounds checked above + entries_data[offset..offset + 8].try_into().unwrap(), + ); + let ack_seq = u64::from_be_bytes( + // unwrap: bounds checked above + entries_data[offset + 8..offset + 16].try_into().unwrap(), + ); + + // Mark matching flight entries as acknowledged + for entry in &mut self.flight_saved_records { + if entry.epoch as u64 == ack_epoch && entry.send_seq == ack_seq { + entry.acked = true; + } + } + } + + // If all epoch-2 records in the flight are ACKed, stop retransmitting. + // This happens when the peer ACKs our handshake flight. + let has_epoch2 = self.flight_saved_records.iter().any(|e| e.epoch == 2); + let all_epoch2_acked = self + .flight_saved_records + .iter() + .filter(|e| e.epoch == 2) + .all(|e| e.acked); + if has_epoch2 && all_epoch2_acked { + debug!("Handshake flight ACKed; stopping retransmission"); + self.flight_timeout = Timeout::Disabled; + self.flight_clear_resends(); + } + + // Rotate send keys only after the peer ACKs our KeyUpdate. Until then, + // application data continues on the old/current application epoch. + if self.key_update_in_flight + && !self.flight_saved_records.is_empty() + && self.flight_saved_records.iter().all(|e| e.acked) + { + debug!("KeyUpdate ACKed; rotating send keys"); + self.update_send_keys()?; + self.prev_app_send_keys = None; + self.key_update_in_flight = false; + self.flight_clear_resends(); + self.flight_timeout = Timeout::Disabled; + } + + Ok(()) + } + + // ========================================================================= + // Handshake ACK Scheduling (RFC 9147 Section 7) + // ========================================================================= + + /// Whether we're in the DTLS 1.3 handshake phase where ACK scheduling applies. + /// + /// True when handshake send keys are installed but application keys are not yet. + /// This corresponds to the client receiving the server's encrypted flight. + fn handshake_in_progress(&self) -> bool { + self.hs_send_keys.is_some() && self.app_send_keys.is_none() && !self.release_app_data + } + + /// Check if the incoming handshake queue needs help (missing fragments/messages). + fn handshake_ack_help_needed(&self) -> bool { + let mut skip_handled = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + .take(MAX_DEFRAGMENT_PACKETS) + .flat_map(|r| r.handshakes().iter()) + .skip_while(|h| h.is_handled()) + .peekable(); + + let Some(first) = skip_handled.peek() else { + return false; + }; + + // If we're not seeing the expected message_seq, we're missing earlier fragments. + if first.header.message_seq != self.peer_handshake_seq_no { + return true; + } + + // Check if the current message is complete + let wanted_seq = first.header.message_seq; + let wanted_length = first.header.length; + let mut last_fragment_end = 0; + + for h in skip_handled { + if wanted_seq != h.header.message_seq { + continue; + } + // Overlap-tolerant: only flag help needed if there's an actual gap + if h.header.fragment_offset > last_fragment_end { + return true; + } + let end = h.header.fragment_offset + h.header.fragment_length; + if end > last_fragment_end { + last_fragment_end = end; + } + if last_fragment_end == wanted_length { + return false; + } + } + + true + } + + /// Check if there's a gap in the incoming handshake data that requires + /// an immediate ACK to help the peer retransmit. + fn has_gap_in_incoming_handshake(&self) -> bool { + let mut skip_handled = self + .queue_rx + .iter() + .flat_map(|i| i.records().iter()) + .skip_while(|r| r.is_handled()) + .take(MAX_DEFRAGMENT_PACKETS) + .flat_map(|r| r.handshakes().iter()) + .skip_while(|h| h.is_handled()) + .peekable(); + + let Some(first) = skip_handled.peek() else { + return false; + }; + + // Gap: not seeing the expected message_seq + if first.header.message_seq != self.peer_handshake_seq_no { + return true; + } + + // Check for fragment gaps within the expected message + let wanted_seq = first.header.message_seq; + let wanted_length = first.header.length; + let mut last_fragment_end = 0; + + for h in skip_handled { + if wanted_seq != h.header.message_seq { + continue; + } + // Overlap-tolerant: only flag a gap if there's an actual gap + if h.header.fragment_offset > last_fragment_end { + return true; + } + let end = h.header.fragment_offset + h.header.fragment_length; + if end > last_fragment_end { + last_fragment_end = end; + } + if last_fragment_end == wanted_length { + return false; + } + } + + false + } + + /// Schedule a handshake ACK if we detect gaps or partial flights. + fn maybe_schedule_handshake_ack(&mut self, now: Instant) { + if !self.handshake_in_progress() { + self.handshake_ack_deadline = None; + return; + } + + if self.handshake_ack_deadline.is_some() { + return; + } + + if !self.handshake_ack_help_needed() { + return; + } + + // If we detect a gap (missing fragments/messages), send ACK immediately. + // Otherwise, use RTO/4 delay to allow piggybacking on the next flight. + let delay = if self.has_gap_in_incoming_handshake() { + Duration::from_millis(0) + } else { + let rto = self.flight_backoff.rto(); + if rto > Duration::from_millis(0) { + rto / 4 + } else { + Duration::from_millis(0) + } + }; + + self.handshake_ack_deadline = Some(now + delay); + } + + /// Flush a scheduled handshake ACK if the deadline has passed. + fn maybe_flush_handshake_ack(&mut self, now: Instant) -> Result<(), Error> { + let Some(deadline) = self.handshake_ack_deadline else { + return Ok(()); + }; + + if now < deadline { + return Ok(()); + } + + // Collect record numbers for epoch-2 handshake records we have received. + let mut record_numbers = ArrayVec::<(u64, u64), 32>::new(); + for incoming in self.queue_rx.iter() { + for r in incoming.records().iter() { + if r.record().sequence.epoch == 2 + && r.record().content_type == ContentType::Handshake + { + let seq = r.record().sequence; + let _ = record_numbers.try_push((seq.epoch as u64, seq.sequence_number)); + } + } + } + + self.handshake_ack_deadline = None; + + if record_numbers.is_empty() { + return Ok(()); + } + + self.send_handshake_ack_epoch2(&record_numbers) + } + + /// Send a handshake ACK on epoch 2 listing received epoch-2 record numbers. + fn send_handshake_ack_epoch2(&mut self, record_numbers: &[(u64, u64)]) -> Result<(), Error> { + if !self.handshake_in_progress() { + return Ok(()); + } + + self.create_ciphertext_record(ContentType::Ack, 2, false, |fragment| { + let len = (record_numbers.len() * 16) as u16; + fragment.extend_from_slice(&len.to_be_bytes()); + for &(epoch, seq) in record_numbers { + fragment.extend_from_slice(&epoch.to_be_bytes()); + fragment.extend_from_slice(&seq.to_be_bytes()); + } + })?; + + Ok(()) + } + + /// Pop a buffer from the buffer pool for temporary use + pub(crate) fn pop_buffer(&mut self) -> Buf { + self.buffers_free.pop() + } + + /// Return a buffer to the buffer pool + pub(crate) fn push_buffer(&mut self, buf: Buf) { + self.buffers_free.push(buf); + } + + // ========================================================================= + // Key Schedule + // ========================================================================= + + fn hmac(&self) -> &dyn HmacProvider { + self.config.crypto_provider().hmac_provider + } + + fn hash_algorithm(&self) -> HashAlgorithm { + // unwrap: cipher_suite must be set before key schedule operations + self.cipher_suite.unwrap().hash_algorithm() + } + + fn suite_provider(&self) -> &'static dyn SupportedDtls13CipherSuite { + let suite = self.cipher_suite.unwrap(); + *self + .config + .crypto_provider() + .dtls13_cipher_suites + .iter() + .find(|cs| cs.suite() == suite) + .expect("cipher suite not found in provider") + } + + /// Derive the early secret: HKDF-Extract(0, 0) [no PSK support] + pub fn derive_early_secret(&mut self) -> Result { + let hash = self.hash_algorithm(); + let hash_len = hash.output_len(); + let zeros = [0u8; 48]; + let zeros = &zeros[..hash_len]; + let mut early_secret = self.buffers_free.pop(); + prf_hkdf::hkdf_extract(self.hmac(), hash, zeros, zeros, &mut early_secret) + .map_err(Error::CryptoError)?; + Ok(early_secret) + } + + /// Derive handshake secrets from ECDHE shared secret + transcript hash through ServerHello. + /// + /// Returns (client_handshake_traffic_secret, server_handshake_traffic_secret, handshake_secret) + pub fn derive_handshake_secrets( + &mut self, + shared_secret: &[u8], + ) -> Result<(Buf, Buf, Buf), Error> { + // Call derive_early_secret first (needs &mut self) before borrowing hmac + let early_secret = self.derive_early_secret()?; + + let hash = self.hash_algorithm(); + let hash_len = hash.output_len(); + let hmac = self.hmac(); + + // Derive-Secret(early_secret, "derived", "") + let empty_hash = self.transcript_hash_of(b""); + let mut derived = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &early_secret, + b"derived", + &empty_hash, + &mut derived, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // handshake_secret = HKDF-Extract(derived, shared_secret) + let mut handshake_secret = Buf::new(); + prf_hkdf::hkdf_extract(hmac, hash, &derived, shared_secret, &mut handshake_secret) + .map_err(Error::CryptoError)?; + + // Get transcript hash up to and including ServerHello + let mut transcript_hash = Buf::new(); + self.transcript_hash(&mut transcript_hash); + + // client_handshake_traffic_secret + let mut c_hs_traffic = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &handshake_secret, + b"c hs traffic", + &transcript_hash, + &mut c_hs_traffic, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // server_handshake_traffic_secret + let mut s_hs_traffic = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &handshake_secret, + b"s hs traffic", + &transcript_hash, + &mut s_hs_traffic, + hash_len, + ) + .map_err(Error::CryptoError)?; + + Ok((c_hs_traffic, s_hs_traffic, handshake_secret)) + } + + /// Install handshake keys (epoch 2) from the traffic secrets. + pub fn install_handshake_keys( + &mut self, + client_traffic_secret: &Buf, + server_traffic_secret: &Buf, + ) -> Result<(), Error> { + let (send_secret, recv_secret) = if self.is_client { + (client_traffic_secret, server_traffic_secret) + } else { + (server_traffic_secret, client_traffic_secret) + }; + + self.hs_send_keys = Some(self.derive_epoch_keys(send_secret)?); + self.hs_recv_keys = Some(self.derive_epoch_keys(recv_secret)?); + + // Reset send sequence for epoch 2 + self.hs_send_seq = 0; + + Ok(()) + } + + /// Derive application secrets from transcript hash through server Finished. + /// + /// Returns (client_app_traffic_secret, server_app_traffic_secret) + pub fn derive_application_secrets( + &mut self, + handshake_secret: &[u8], + ) -> Result<(Buf, Buf), Error> { + let hash = self.hash_algorithm(); + let hash_len = hash.output_len(); + let hmac = self.hmac(); + + // Derive-Secret(handshake_secret, "derived", "") + let empty_hash = self.transcript_hash_of(b""); + let mut derived = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + handshake_secret, + b"derived", + &empty_hash, + &mut derived, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // master_secret = HKDF-Extract(derived, 0) + let zeros = [0u8; 48]; + let zeros = &zeros[..hash_len]; + let mut master_secret = Buf::new(); + prf_hkdf::hkdf_extract(hmac, hash, &derived, zeros, &mut master_secret) + .map_err(Error::CryptoError)?; + + // Get transcript hash up to and including server Finished + let mut transcript_hash = Buf::new(); + self.transcript_hash(&mut transcript_hash); + + // exporter_master_secret = Derive-Secret(master_secret, "exp master", transcript_hash) + let mut exp_master = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &master_secret, + b"exp master", + &transcript_hash, + &mut exp_master, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // client_application_traffic_secret_0 + let mut c_ap_traffic = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &master_secret, + b"c ap traffic", + &transcript_hash, + &mut c_ap_traffic, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // server_application_traffic_secret_0 + let mut s_ap_traffic = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &master_secret, + b"s ap traffic", + &transcript_hash, + &mut s_ap_traffic, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // Store exporter master secret (deferred to avoid borrow conflict with hmac) + self.exporter_master_secret = Some(exp_master); + + Ok((c_ap_traffic, s_ap_traffic)) + } + + /// Install application keys (epoch 3) from the traffic secrets. + pub fn install_application_keys( + &mut self, + client_traffic_secret: &Buf, + server_traffic_secret: &Buf, + ) -> Result<(), Error> { + let (send_secret, recv_secret) = if self.is_client { + (client_traffic_secret, server_traffic_secret) + } else { + (server_traffic_secret, client_traffic_secret) + }; + + self.app_send_keys = Some(self.derive_epoch_keys(send_secret)?); + + let recv_keys = self.derive_epoch_keys(recv_secret)?; + self.app_recv_keys.push(RecvEpochEntry { + epoch: 3, + keys: recv_keys, + expected_recv_seq: 0, + replay: ReplayWindow::new(), + }); + + self.app_send_epoch = 3; + self.app_send_seq = 0; + + Ok(()) + } + + /// Derive the next application traffic secret from the current one. + /// Per RFC 8446 Section 7.2: application_traffic_secret_N+1 = + /// HKDF-Expand-Label(application_traffic_secret_N, "traffic upd", "", Hash.length) + fn derive_next_traffic_secret(&self, current: &Buf) -> Result { + let hash = self.hash_algorithm(); + let hash_len = hash.output_len(); + let hmac = self.hmac(); + + let mut next = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + current, + b"traffic upd", + &[], + &mut next, + hash_len, + ) + .map_err(Error::CryptoError)?; + + Ok(next) + } + + /// Rotate send keys: move current app send keys → prev, derive new ones. + fn update_send_keys(&mut self) -> Result<(), Error> { + let current_keys = self.app_send_keys.take().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCurrentAppSendKeysForKeyUpdate, + ))?; + + let next_secret = self.derive_next_traffic_secret(¤t_keys.traffic_secret)?; + let new_keys = self.derive_epoch_keys(&next_secret)?; + + // Save old keys for retransmission + self.prev_app_send_keys = Some(current_keys); + self.prev_app_send_epoch = self.app_send_epoch; + self.prev_app_send_seq = self.app_send_seq; + + // Install new keys + self.app_send_keys = Some(new_keys); + self.app_send_epoch += 1; + self.app_send_seq = 0; + self.app_send_record_count = 0; + self.aead_encryption_threshold = + jittered_aead_threshold(self.config.aead_encryption_limit(), &mut self.rng); + self.needs_key_update = false; + + debug!("Send keys updated to epoch {}", self.app_send_epoch); + + Ok(()) + } + + /// Install new receive keys from the current recv epoch's traffic secret. + /// Derives the next secret, creates keys, and adds a new RecvEpochEntry. + /// Returns the new epoch number. + pub fn update_recv_keys(&mut self) -> Result { + // Find the latest recv epoch entry + let latest = self.app_recv_keys.last().ok_or(Error::InvalidState( + crate::InvalidStateError::NoCurrentAppRecvKeysForKeyUpdate, + ))?; + + let next_secret = self.derive_next_traffic_secret(&latest.keys.traffic_secret)?; + let new_epoch = latest.epoch + 1; + let new_keys = self.derive_epoch_keys(&next_secret)?; + + // Evict oldest if full + if self.app_recv_keys.is_full() { + self.app_recv_keys.remove(0); + } + + self.app_recv_keys.push(RecvEpochEntry { + epoch: new_epoch, + keys: new_keys, + expected_recv_seq: 0, + replay: ReplayWindow::new(), + }); + + debug!("Recv keys updated to epoch {}", new_epoch); + + Ok(new_epoch) + } + + /// Create and send a KeyUpdate handshake message. + /// + /// Arms the flight timer for retransmission. The KeyUpdate is sent on + /// the current app epoch. Send keys rotate only after its ACK arrives. + pub fn create_key_update(&mut self, request: KeyUpdateRequest) -> Result<(), Error> { + // Set up retransmission + self.flight_backoff.reset(&mut self.rng); + self.flight_clear_resends(); + self.flight_timeout = Timeout::Unarmed; + + let msg_seq = self.next_handshake_seq_no; + self.next_handshake_seq_no += 1; + + let epoch = self.app_send_epoch; + + // Build the handshake message manually (12-byte DTLS header + 1-byte body) + self.create_ciphertext_record(ContentType::Handshake, epoch, true, |fragment| { + // DTLS handshake header (12 bytes): + // msg_type(1) + length(3) + message_seq(2) + fragment_offset(3) + fragment_length(3) + fragment.push(MessageType::KeyUpdate.as_u8()); + fragment.extend_from_slice(&1u32.to_be_bytes()[1..]); // length = 1 + fragment.extend_from_slice(&msg_seq.to_be_bytes()); // message_seq + fragment.extend_from_slice(&0u32.to_be_bytes()[1..]); // fragment_offset = 0 + fragment.extend_from_slice(&1u32.to_be_bytes()[1..]); // fragment_length = 1 + // Body: 1 byte + fragment.push(request.as_u8()); + })?; + + self.key_update_in_flight = true; + + debug!( + "KeyUpdate sent (request={:?}) on epoch {}, awaiting ACK before rotating send keys", + request, epoch + ); + + Ok(()) + } + + /// Install send handshake keys for client flight (after receiving server Finished). + /// Reset handshake state for a new ClientHello after HelloRetryRequest. + pub fn reset_for_hello_retry(&mut self) { + // Per RFC 9147, message_seq increments across HRR (CH1=0, HRR=0, + // CH2=1, SH=1), so neither peer nor own handshake sequence numbers + // are reset. Only reset epoch 2 record sequence (unused at HRR time). + self.hs_send_seq = 0; + self.handshake_ack_deadline = None; + // Drain handled items so stale retransmissions with the same + // message_seq can be accepted after the sequence number reset. + self.queue_rx.retain(|item| !item.first().is_handled()); + } + + /// Derive epoch keys (cipher + IV + sn_key) from a traffic secret. + fn derive_epoch_keys(&self, traffic_secret: &Buf) -> Result { + let hash = self.hash_algorithm(); + let suite = self.suite_provider(); + let hmac = self.hmac(); + + // key = HKDF-Expand-Label(secret, "key", "", key_length) + let mut key = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + traffic_secret, + b"key", + &[], + &mut key, + suite.key_len(), + ) + .map_err(Error::CryptoError)?; + + // iv = HKDF-Expand-Label(secret, "iv", "", iv_length) + let mut iv_buf = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + traffic_secret, + b"iv", + &[], + &mut iv_buf, + suite.iv_len(), + ) + .map_err(Error::CryptoError)?; + + // sn_key = HKDF-Expand-Label(secret, "sn", "", key_length) + let mut sn_key = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + traffic_secret, + b"sn", + &[], + &mut sn_key, + suite.key_len(), + ) + .map_err(Error::CryptoError)?; + + let cipher = suite.create_cipher(&key).map_err(Error::CryptoError)?; + + let mut iv = [0u8; 12]; + iv.copy_from_slice(&iv_buf); + + let mut secret = Buf::new(); + secret.extend_from_slice(traffic_secret); + + Ok(EpochKeys { + cipher, + iv, + traffic_secret: secret, + sn_key, + }) + } + + /// Compute verify_data for Finished messages. + /// + /// finished_key = HKDF-Expand-Label(traffic_secret, "finished", "", Hash.len) + /// verify_data = HMAC(finished_key, transcript_hash) + /// + /// We use `hkdf_extract(salt=finished_key, IKM=transcript_hash)` to compute + /// the HMAC because HKDF-Extract is defined as HMAC-Hash(salt, IKM) (RFC 5869 + /// §2.2). This gives us a generic HMAC that works for any hash algorithm + /// (SHA-256, SHA-384) without needing a separate per-algorithm HMAC API. + pub fn compute_verify_data(&self, traffic_secret: &[u8]) -> Result { + let hash = self.hash_algorithm(); + let hash_len = hash.output_len(); + let hmac = self.hmac(); + + // finished_key = HKDF-Expand-Label(secret, "finished", "", Hash.len) + let mut finished_key = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + traffic_secret, + b"finished", + &[], + &mut finished_key, + hash_len, + ) + .map_err(Error::CryptoError)?; + + let mut transcript_hash = Buf::new(); + self.transcript_hash(&mut transcript_hash); + + // HMAC(finished_key, transcript_hash) via HKDF-Extract(salt=key, IKM=data) + let mut verify_data = Buf::new(); + prf_hkdf::hkdf_extract( + hmac, + hash, + &finished_key, + &transcript_hash, + &mut verify_data, + ) + .map_err(Error::CryptoError)?; + + Ok(verify_data) + } + + // ========================================================================= + // Transcript Management + // ========================================================================= + + pub fn transcript_hash(&self, out: &mut Buf) { + let hash = self.hash_algorithm(); + let mut ctx = self + .config + .crypto_provider() + .hash_provider + .create_hash(hash); + ctx.update(&self.transcript); + ctx.clone_and_finalize(out); + } + + /// Compute transcript hash of arbitrary data (e.g. empty for "derived" label). + fn transcript_hash_of(&self, data: &[u8]) -> Buf { + let hash = self.hash_algorithm(); + let mut ctx = self + .config + .crypto_provider() + .hash_provider + .create_hash(hash); + ctx.update(data); + let mut out = Buf::new(); + ctx.clone_and_finalize(&mut out); + out + } + + /// Replace transcript with message_hash for HelloRetryRequest. + /// + /// Per RFC 8446 Section 4.4.1: Hash replaces transcript with + /// message_hash = 0xFE || 00 00 Hash.length || Hash(CH1) + /// + /// `split_at` is the byte offset that separates the portion to hash (CH1) + /// from the tail to preserve (HRR bytes appended by next_handshake). + /// The transcript becomes: message_hash(CH1) || transcript[split_at..]. + pub fn replace_transcript_with_message_hash(&mut self, split_at: usize) { + let hash = self.hash_algorithm(); + let mut hash_ctx = self + .config + .crypto_provider() + .hash_provider + .create_hash(hash); + hash_ctx.update(&self.transcript[..split_at]); + let mut hash_value = Buf::new(); + hash_ctx.clone_and_finalize(&mut hash_value); + + // Build new transcript: message_hash || tail + let mut new_transcript = self.buffers_free.pop(); + // message_hash construct: msg_type=0xFE, length(3)=hash_len + new_transcript.push(0xFE); + let hash_len = hash_value.len() as u32; + new_transcript.extend_from_slice(&hash_len.to_be_bytes()[1..]); + new_transcript.extend_from_slice(&hash_value); + // Append the preserved tail (HRR bytes) + new_transcript.extend_from_slice(&self.transcript[split_at..]); + + let old = mem::replace(&mut self.transcript, new_transcript); + self.buffers_free.push(old); + } + + // ========================================================================= + // Peer Encryption Management + // ========================================================================= + + pub fn enable_peer_encryption(&mut self) -> Result<(), InternalError> { + debug!("Peer encryption enabled"); + self.peer_encryption_enabled = true; + + // Re-parse any buffered epoch 2+ records + let maybe_index = self + .queue_rx + .iter() + .position(|i| i.records().iter().any(|r| r.record().sequence.epoch >= 2)); + + let Some(index) = maybe_index else { + return Ok(()); + }; + + let all = self.queue_rx.split_off(index); + + for incoming in all { + let unhandled = incoming.into_records().filter(|r| !r.is_handled()); + + for record in unhandled { + let buf = record.into_buffer(); + self.parse_packet(&buf)?; + self.buffers_free.push(buf); + } + } + + Ok(()) + } + + // ========================================================================= + // Key Exchange Helpers + // ========================================================================= + + pub fn find_kx_group( + &self, + group: crate::types::NamedGroup, + ) -> Option<&'static dyn SupportedKxGroup> { + self.config.kx_groups().find(|g| g.name() == group) + } + + // ========================================================================= + // Signature Verification + // ========================================================================= + + pub fn verify_signature( + &self, + cert_der: &[u8], + data: &[u8], + signature: &[u8], + hash_alg: HashAlgorithm, + sig_alg: crate::types::SignatureAlgorithm, + ) -> Result<(), Error> { + self.config + .crypto_provider() + .signature_verification + .verify_signature(cert_der, data, signature, hash_alg, sig_alg) + .map_err(Error::CryptoError) + } + + // ========================================================================= + // Extract SRTP Keying Material + // ========================================================================= + + pub fn extract_srtp_keying_material( + &self, + profile: crate::crypto::SrtpProfile, + ) -> Result<(ArrayVec, crate::crypto::SrtpProfile), Error> { + let hash = self.hash_algorithm(); + let hash_len = hash.output_len(); + let hmac = self.hmac(); + + let exp_master = self + .exporter_master_secret + .as_ref() + .ok_or(Error::CryptoError( + crate::CryptoError::ExporterMasterSecretNotDerived, + ))?; + + let total_len = profile.keying_material_len(); + + // RFC 8446 Section 7.5: + // 1. derived_secret = Derive-Secret(exporter_master_secret, label, "") + let empty_hash = self.transcript_hash_of(b""); + let mut derived = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + exp_master, + b"EXTRACTOR-dtls_srtp", + &empty_hash, + &mut derived, + hash_len, + ) + .map_err(Error::CryptoError)?; + + // 2. result = HKDF-Expand-Label(derived_secret, "exporter", Hash(context), length) + let context_hash = self.transcript_hash_of(b""); + let mut keying_material_buf = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &derived, + b"exporter", + &context_hash, + &mut keying_material_buf, + total_len, + ) + .map_err(Error::CryptoError)?; + + let mut keying_material = ArrayVec::new(); + for &b in keying_material_buf.iter().take(total_len) { + keying_material.push(b); + } + + Ok((keying_material, profile)) + } + + pub fn random(&mut self) -> Random { + Random::new(&mut self.rng) + } + + pub fn random_arr(&mut self) -> [u8; N] { + self.rng.random() + } +} + +// ========================================================================= +// Helper Functions +// ========================================================================= + +/// Pick a random AEAD encryption threshold in `[3/4 * limit, limit]`. +/// +/// Jittering prevents both sides from triggering KeyUpdate simultaneously +/// when they share the same configured limit. +fn jittered_aead_threshold(limit: u64, rng: &mut SeededRng) -> u64 { + let quarter = limit / 4; + if quarter == 0 { + return limit; + } + let offset: u64 = rng.random::() % (quarter + 1); + limit - quarter + offset +} + +/// Determine the epoch for a handshake message type. +/// +/// In DTLS 1.3, ClientHello and ServerHello are sent as plaintext (epoch 0). +/// All other handshake messages are encrypted (epoch 2). +fn epoch_for_message(msg_type: MessageType) -> u16 { + match msg_type { + MessageType::ClientHello | MessageType::ServerHello => 0, + _ => 2, + } +} + +/// Reconstruct a full sequence number from a partial value (RFC 9147 Section 4.2.2). +/// +/// Uses a sliding window centered on the expected sequence to find the full +/// 48-bit sequence that is closest to `expected`. +fn reconstruct_sequence(partial: u64, expected: u64, bits: u32) -> u64 { + let mask = (1u64 << bits) - 1; + let window = 1u64 << bits; + let half = window / 2; + + let received_partial = partial & mask; + let expected_partial = expected & mask; + + let diff = (received_partial as i64) - (expected_partial as i64); + let diff = if diff > half as i64 { + diff - window as i64 + } else if diff < -(half as i64) { + diff + window as i64 + } else { + diff + }; + + // Clamp to 0 to avoid underflow for very early sequence numbers + (expected as i64 + diff).max(0) as u64 +} + +// ========================================================================= +// RecordHandler Implementation +// ========================================================================= + +impl RecordHandler for Engine { + fn classify_record(&mut self, record: Record) -> Result, Error> { + if let Some(cn_seq) = self.close_notify_sequence { + if record.record().sequence > cn_seq { + self.push_buffer(record.into_buffer()); + return Ok(None); + } + } + + let epoch = record.record().sequence.epoch; + if epoch == 0 + && self.peer_encryption_enabled + && matches!( + record.record().content_type, + ContentType::Ack | ContentType::Alert + ) + { + // Plaintext ACKs and alerts after peer encryption is enabled are + // unauthenticated and must not be acted on. Mirrors DTLS 1.2. + self.push_buffer(record.into_buffer()); + return Ok(None); + } + + match record.record().content_type { + ContentType::Ack => { + let fragment = record.record().fragment(record.buffer()); + self.process_ack(fragment)?; + self.push_buffer(record.into_buffer()); + Ok(None) + } + ContentType::Alert => { + // RFC 8446 §6: TLS 1.3 ignores the AlertLevel byte; severity is + // implicit in the description (only close_notify and user_canceled + // are non-fatal). + let description = { + let fragment = record.record().fragment(record.buffer()); + fragment.get(1).copied() + }; + let sequence = record.record().sequence; + self.push_buffer(record.into_buffer()); + + match description { + Some(0) => { + self.close_notify_sequence.get_or_insert(sequence); + Ok(None) + } + Some(90) => Ok(None), + Some(description) => { + Err(Error::SecurityError(crate::SecurityError::FatalAlert { + description, + })) + } + None => Ok(None), + } + } + ContentType::ChangeCipherSpec => { + trace!("Discarding CCS record"); + self.push_buffer(record.into_buffer()); + Ok(None) + } + _ => Ok(Some(record)), + } + } + + fn is_peer_encryption_enabled(&self) -> bool { + self.peer_encryption_enabled + } + + fn resolve_epoch(&self, epoch_bits: u8) -> u16 { + // Map 2-bit epoch field to full epoch. + // In practice during handshake, epoch_bits=2 maps to epoch 2. + // After KeyUpdate, epoch_bits cycles: 3→0→1→2→3→... + let epoch_bits = epoch_bits as u16; + + // Check application recv epochs - return the newest (last) match + // when multiple epochs share the same 2-bit value (e.g. epoch 3 and 7). + let mut best = None; + for entry in &self.app_recv_keys { + if (entry.epoch & 0x03) == epoch_bits { + best = Some(entry.epoch); + } + } + + if self.hs_recv_keys.is_some() && (2 & 0x03) == epoch_bits && !self.release_app_data { + return 2; + } + + if let Some(epoch) = best { + return epoch; + } + + if self.hs_recv_keys.is_some() && (2 & 0x03) == epoch_bits { + return 2; + } + + // Default to the epoch bits value + epoch_bits + } + + fn resolve_sequence(&self, epoch: u16, seq_bits: u64, s_flag: bool) -> u64 { + let expected = if epoch == 2 { + self.hs_expected_recv_seq + } else { + self.app_recv_keys + .iter() + .find(|e| e.epoch == epoch) + .map(|e| e.expected_recv_seq) + .unwrap_or(0) + }; + + let bits: u32 = if s_flag { 16 } else { 8 }; + reconstruct_sequence(seq_bits, expected, bits) + } + + fn replay_check(&self, seq: Sequence) -> bool { + // Route to the correct per-epoch replay window + if seq.epoch == 2 { + self.hs_replay.check(seq.sequence_number) + } else { + match self.app_recv_keys.iter().find(|e| e.epoch == seq.epoch) { + Some(entry) => entry.replay.check(seq.sequence_number), + None => false, // no keys for this epoch + } + } + } + + fn replay_update(&mut self, seq: Sequence) { + // Update the replay window for this epoch + if seq.epoch == 2 { + self.hs_replay.update(seq.sequence_number); + } else if let Some(entry) = self.app_recv_keys.iter_mut().find(|e| e.epoch == seq.epoch) { + entry.replay.update(seq.sequence_number); + } + + // Advance expected receive sequence for this epoch + let next = seq.sequence_number + 1; + if seq.epoch == 2 { + if next > self.hs_expected_recv_seq { + self.hs_expected_recv_seq = next; + } + } else { + for entry in &mut self.app_recv_keys { + if entry.epoch == seq.epoch { + if next > entry.expected_recv_seq { + entry.expected_recv_seq = next; + } + break; + } + } + } + } + + fn min_protected_fragment_len(&self) -> usize { + self.suite_provider().min_protected_fragment_len() + } + + fn decrypt_record( + &mut self, + header: &[u8], + seq: Sequence, + ciphertext: &mut TmpBuf, + ) -> Result<(), Error> { + // Find the right keys based on epoch + let keys = if seq.epoch == 2 { + self.hs_recv_keys.as_mut() + } else { + // Look up in app recv keys + self.app_recv_keys + .iter_mut() + .find(|e| e.epoch == seq.epoch) + .map(|e| &mut e.keys) + }; + + let Some(keys) = keys else { + return Err(Error::CryptoError( + crate::CryptoError::RecvKeysNotAvailable { epoch: seq.epoch }, + )); + }; + + // Construct nonce: iv XOR padded_seq + let nonce = Nonce::xor(&keys.iv, seq.sequence_number); + + // AAD is the raw header bytes + let aad = Aad::new_dtls13(header); + + keys.cipher + .decrypt(ciphertext, aad, nonce) + .map_err(Error::CryptoError)?; + + Ok(()) + } + + fn decrypt_sequence_number( + &self, + epoch: u16, + seq_bytes: &mut [u8], + ciphertext_sample: &[u8; 16], + ) { + // Find the sn_key for this epoch + let sn_key = if epoch == 2 { + self.hs_recv_keys.as_ref().map(|k| &k.sn_key) + } else { + self.app_recv_keys + .iter() + .find(|e| e.epoch == epoch) + .map(|e| &e.keys.sn_key) + }; + + let Some(sn_key) = sn_key else { + return; // No keys yet, leave seq bytes as-is + }; + + let mask = self.suite_provider().encrypt_sn(sn_key, ciphertext_sample); + for (i, byte) in seq_bytes.iter_mut().enumerate() { + *byte ^= mask[i]; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(feature = "rcgen")] + use crate::certificate::generate_self_signed_certificate; + + #[cfg(feature = "rcgen")] + fn test_engine() -> Engine { + let cert = generate_self_signed_certificate().expect("gen cert"); + let config = Arc::new(Config::builder().build().expect("build config")); + Engine::new(config, cert) + } + + struct PassthroughRecordHandler; + + impl RecordHandler for PassthroughRecordHandler { + fn classify_record(&mut self, record: Record) -> Result, Error> { + Ok(Some(record)) + } + + fn is_peer_encryption_enabled(&self) -> bool { + true + } + + fn resolve_epoch(&self, _epoch_bits: u8) -> u16 { + 2 + } + + fn resolve_sequence(&self, _epoch: u16, seq_bits: u64, _s_flag: bool) -> u64 { + seq_bits + } + + fn replay_check(&self, _seq: Sequence) -> bool { + true + } + + fn replay_update(&mut self, _seq: Sequence) {} + + fn min_protected_fragment_len(&self) -> usize { + 0 + } + + fn decrypt_record( + &mut self, + _header: &[u8], + _seq: Sequence, + _ciphertext: &mut TmpBuf, + ) -> Result<(), Error> { + Ok(()) + } + + fn decrypt_sequence_number( + &self, + _epoch: u16, + _seq_bytes: &mut [u8], + _ciphertext_sample: &[u8; 16], + ) { + } + } + + fn encrypted_key_update_record(seq: u16) -> Vec { + let mut fragment = Vec::new(); + fragment.push(MessageType::KeyUpdate.as_u8()); + fragment.extend_from_slice(&1u32.to_be_bytes()[1..]); + fragment.extend_from_slice(&0u16.to_be_bytes()); + fragment.extend_from_slice(&0u32.to_be_bytes()[1..]); + fragment.extend_from_slice(&1u32.to_be_bytes()[1..]); + fragment.push(KeyUpdateRequest::UpdateRequested.as_u8()); + fragment.push(ContentType::Handshake.as_u8()); + + let mut packet = Vec::new(); + packet.push( + 0b0010_0000 + | 0b0000_1000 // 2-byte sequence number. + | 0b0000_0100 // explicit length. + | 0b0000_0010, // epoch bits resolved by PassthroughRecordHandler. + ); + packet.extend_from_slice(&seq.to_be_bytes()); + packet.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); + packet.extend_from_slice(&fragment); + packet + } + + fn encrypted_application_data_record(seq: u16, data: &[u8]) -> Vec { + let mut fragment = Vec::new(); + fragment.extend_from_slice(data); + fragment.push(ContentType::ApplicationData.as_u8()); + + let mut packet = Vec::new(); + packet.push( + 0b0010_0000 + | 0b0000_1000 // 2-byte sequence number. + | 0b0000_0100 // explicit length. + | 0b0000_0010, // epoch bits resolved by PassthroughRecordHandler. + ); + packet.extend_from_slice(&seq.to_be_bytes()); + packet.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); + packet.extend_from_slice(&fragment); + packet + } + + fn parsed_key_update(seq: u16) -> Incoming { + Incoming::parse_packet( + &encrypted_key_update_record(seq), + &mut PassthroughRecordHandler, + Some(Dtls13CipherSuite::AES_128_GCM_SHA256), + ) + .expect("parse key update packet") + .expect("packet contains a record") + } + + fn parsed_key_update_with_app_data(key_update_seq: u16, app_seq: u16) -> Incoming { + let mut packet = encrypted_key_update_record(key_update_seq); + packet.extend_from_slice(&encrypted_application_data_record(app_seq, b"app-data")); + Incoming::parse_packet( + &packet, + &mut PassthroughRecordHandler, + Some(Dtls13CipherSuite::AES_128_GCM_SHA256), + ) + .expect("parse coalesced packet") + .expect("packet contains records") + } + + /// Issue 2: Epoch-0 sequence number must have an overflow guard. + /// + /// Per RFC 9147 §4.2, implementations MUST NOT allow the sequence number + /// to exceed MAX_SEQUENCE_NUMBER (2^48 - 1). This test sets the counter + /// to MAX and verifies that `create_plaintext_record` returns an error. + #[test] + #[cfg(feature = "rcgen")] + fn epoch_0_sequence_number_rejects_overflow() { + let mut engine = test_engine(); + + // Set epoch-0 sequence to MAX — the next increment should be rejected + engine.sequence_epoch_0.sequence_number = MAX_SEQUENCE_NUMBER; + + let result = engine.create_plaintext_record(ContentType::Handshake, false, |buf| { + buf.extend_from_slice(b"test") + }); + assert!( + result.is_err(), + "epoch-0 must reject sequence overflow at MAX_SEQUENCE_NUMBER" + ); + } + + /// Issue 3: `derive_handshake_secrets` must return the handshake_secret + /// alongside the traffic secrets, eliminating the need for a separate + /// `derive_handshake_secret` method. + #[test] + #[cfg(feature = "rcgen")] + fn derive_handshake_secrets_returns_handshake_secret() { + let mut engine = test_engine(); + engine.set_cipher_suite(Dtls13CipherSuite::AES_128_GCM_SHA256); + + // Simulate some transcript content (normally built during handshake) + engine + .transcript + .extend_from_slice(b"dummy transcript for test"); + + let shared_secret = [0x42u8; 32]; + + // derive_handshake_secrets returns a 3-tuple: + // (client_hs_traffic, server_hs_traffic, handshake_secret) + let (c_hs_traffic, _s_hs_traffic, handshake_secret) = + engine.derive_handshake_secrets(&shared_secret).unwrap(); + + // Verify the handshake_secret can reproduce the same c_hs_traffic + let hash = engine.hash_algorithm(); + let hash_len = hash.output_len(); + let hmac = engine.hmac(); + + let mut transcript_hash = Buf::new(); + engine.transcript_hash(&mut transcript_hash); + + let mut c_hs_manual = Buf::new(); + prf_hkdf::hkdf_expand_label_dtls13( + hmac, + hash, + &handshake_secret, + b"c hs traffic", + &transcript_hash, + &mut c_hs_manual, + hash_len, + ) + .expect("hkdf_expand_label_dtls13"); + + assert_eq!( + c_hs_manual.as_ref(), + c_hs_traffic.as_ref(), + "handshake_secret from derive_handshake_secrets() must reproduce \ + the same traffic secrets" + ); + } + + /// Issue 4: `derive_early_secret` must use the buffer pool. + /// + /// `derive_early_secret` takes `&mut self` and allocates its output buffer + /// via `self.buffers_free.pop()`, reusing pooled allocations instead of + /// creating a fresh `Buf::new()`. + #[test] + #[cfg(feature = "rcgen")] + fn derive_early_secret_uses_buffer_pool() { + let mut engine = test_engine(); + engine.set_cipher_suite(Dtls13CipherSuite::AES_128_GCM_SHA256); + + // Pre-fill the pool with a buffer that has allocated capacity. + // BufferPool::push clears contents but retains the allocation. + let mut marked = Buf::new(); + marked.extend_from_slice(&[0xAA; 256]); + engine.buffers_free.push(marked); + + // derive_early_secret takes &mut self and uses the buffer pool. + let early_secret = engine.derive_early_secret().unwrap(); + + // The returned buffer should have pooled capacity (>= 256), + // not 0 from Buf::new(). + assert!( + early_secret.into_vec().capacity() >= 256, + "derive_early_secret must use the buffer pool, returning a buffer with pooled capacity" + ); + } + + #[test] + #[cfg(feature = "rcgen")] + fn ack_tracking_full_does_not_panic_on_handshake_replacement() { + let mut engine = test_engine(); + + let first = parsed_key_update(0); + engine + .insert_incoming(first) + .expect("insert initial key update"); + engine.queue_rx[0] + .first() + .first_handshake() + .expect("initial key update handshake") + .set_handled(); + + engine.received_record_numbers.clear(); + for sequence in 0..engine.received_record_numbers.capacity() { + engine.received_record_numbers.push((2, sequence as u64)); + } + + let replacement = parsed_key_update(1); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + engine + .insert_incoming(replacement) + .expect("replace handled key update") + })); + + assert!( + result.is_ok(), + "full ACK bookkeeping must not panic when a handled handshake is replaced" + ); + assert_eq!(engine.queue_rx.len(), 1); + assert_eq!( + engine.queue_rx[0].first().record().sequence.sequence_number, + 1 + ); + assert_eq!( + engine.received_record_numbers.len(), + engine.received_record_numbers.capacity(), + "overflowing ACK bookkeeping should keep existing entries and drop the extra one" + ); + } + + #[test] + #[cfg(feature = "rcgen")] + fn ack_tracking_ignores_non_handshake_records_in_coalesced_datagram() { + let mut engine = test_engine(); + + let incoming = parsed_key_update_with_app_data(7, 8); + assert_eq!(incoming.records().len(), 2); + assert_eq!( + incoming.records()[0].record().content_type, + ContentType::Handshake + ); + assert_eq!( + incoming.records()[1].record().content_type, + ContentType::ApplicationData + ); + + engine + .insert_incoming(incoming) + .expect("insert coalesced datagram"); + + assert_eq!( + engine.received_record_numbers.as_slice(), + &[(2, 7)], + "ACK bookkeeping must include only handshake records" + ); + } + + #[test] + #[cfg(feature = "rcgen")] + fn malformed_ack_record_number_vector_is_ignored() { + let mut engine = test_engine(); + engine.flight_saved_records.push(Entry { + content_type: ContentType::Handshake, + epoch: 2, + send_seq: 7, + fragment: Buf::new(), + acked: false, + }); + + let mut malformed_ack = Vec::new(); + malformed_ack.extend_from_slice(&17u16.to_be_bytes()); + malformed_ack.extend_from_slice(&2u64.to_be_bytes()); + malformed_ack.extend_from_slice(&7u64.to_be_bytes()); + malformed_ack.push(0); + + engine.process_ack(&malformed_ack).unwrap(); + + assert!( + !engine.flight_saved_records[0].acked, + "malformed ACK vector length must not partially acknowledge records" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/incoming.rs b/third_party/dimpl/src/dtls13/incoming.rs new file mode 100644 index 0000000..6dfeb6f --- /dev/null +++ b/third_party/dimpl/src/dtls13/incoming.rs @@ -0,0 +1,633 @@ +use std::ops::Deref; +use std::sync::atomic::{AtomicBool, Ordering}; + +use arrayvec::ArrayVec; +use std::fmt; + +use crate::buffer::{Buf, TmpBuf}; +use crate::dtls13::message::{ContentType, Dtls13CipherSuite, Dtls13Record, Handshake, Sequence}; +use crate::{Error, InternalError}; + +/// Holds both the UDP packet and the parsed result of that packet. +pub struct Incoming { + // Box is here to reduce the size of the Incoming struct + // to be passed in register instead of using memmove. + records: Box, +} + +impl Incoming { + pub fn records(&self) -> &Records { + &self.records + } + + pub fn first(&self) -> &Record { + // Invariant: Every Incoming must have at least one Record + // or the parser of Incoming returns None. + &self.records()[0] + } + + pub fn into_records(self) -> impl Iterator { + self.records.records.into_iter() + } +} + +impl Incoming { + /// Parse an incoming UDP packet + /// + /// * `packet` is the data from the UDP socket. + /// * `decrypt` provides the decryption operations for encrypted records. + /// * `cs` is the negotiated cipher suite, if any. + /// + /// Will surface parser errors. + pub fn parse_packet( + packet: &[u8], + decrypt: &mut dyn RecordHandler, + cs: Option, + ) -> Result, InternalError> { + // Parse records directly from packet, copying each record ONCE into its own buffer + let records = Records::parse(packet, decrypt, cs)?; + + // We need at least one Record to be valid. For replayed frames, we discard + // the records, hence this might be None + if records.records.is_empty() { + return Ok(None); + } + + let records = Box::new(records); + + Ok(Some(Incoming { records })) + } +} + +/// A number of records parsed from a single UDP packet. +#[derive(Debug)] +pub struct Records { + pub records: ArrayVec, +} + +impl Records { + pub fn parse( + mut packet: &[u8], + decrypt: &mut dyn RecordHandler, + cs: Option, + ) -> Result { + let mut parsed_records: ArrayVec = ArrayVec::new(); + + // Find record boundaries and copy each record ONCE from the packet + while !packet.is_empty() { + let record_end = if Dtls13Record::is_ciphertext_header(packet[0]) { + // CID bit set means we can't determine record boundaries (unsupported). + // Discard the rest of the datagram. + if packet[0] & 0x10 != 0 { + break; + } + + // Unified header: variable length + if packet.len() < 2 { + return Err(InternalError::parse_incomplete()); + } + + let flags = packet[0]; + let s_flag = flags & 0b0000_1000 != 0; + let l_flag = flags & 0b0000_0100 != 0; + let seq_len = if s_flag { 2 } else { 1 }; + let len_len = if l_flag { 2 } else { 0 }; + let header_len = 1 + seq_len + len_len; + + if packet.len() < header_len { + return Err(InternalError::parse_incomplete()); + } + + if l_flag { + let len_offset = 1 + seq_len; + // unwrap: header_len check above ensures 2 bytes at len_offset + let length_bytes: [u8; 2] = + packet[len_offset..len_offset + 2].try_into().unwrap(); + let length = u16::from_be_bytes(length_bytes) as usize; + header_len + length + } else { + // No length field: record consumes the rest of the datagram + packet.len() + } + } else { + // Plaintext: fixed 13-byte header + if packet.len() < Dtls13Record::PLAINTEXT_HEADER_LEN { + return Err(InternalError::parse_incomplete()); + } + + // unwrap: PLAINTEXT_HEADER_LEN check above ensures 2 bytes at offset + let length_bytes: [u8; 2] = packet[Dtls13Record::PLAINTEXT_LENGTH_OFFSET] + .try_into() + .unwrap(); + let length = u16::from_be_bytes(length_bytes) as usize; + Dtls13Record::PLAINTEXT_HEADER_LEN + length + }; + + if packet.len() < record_end { + return Err(InternalError::parse_incomplete()); + } + + // This is the ONLY copy: packet -> record buffer + let record_slice = &packet[..record_end]; + let record = Record::parse(record_slice, decrypt, cs)?; + if let Some(record) = record { + if parsed_records.try_push(record).is_err() { + return Err(InternalError::too_many_records()); + } + } else { + trace!("Discarding replayed rec"); + } + + packet = &packet[record_end..]; + } + + let mut records = ArrayVec::new(); + for record in parsed_records { + if let Some(record) = decrypt.classify_record(record)? { + records + .try_push(record) + .expect("filtered records cannot exceed parsed records"); + } + } + + Ok(Records { records }) + } +} + +impl Deref for Records { + type Target = [Record]; + + fn deref(&self) -> &Self::Target { + &self.records + } +} + +pub struct Record { + buffer: Buf, + // Box is here to reduce the size of the Record struct + // to be passed in register instead of using memmove. + parsed: Box, +} + +impl Record { + /// The first parse pass only parses the record header which is unencrypted. + /// Copies record data from UDP packet ONCE into a pooled buffer. + pub fn parse( + record_slice: &[u8], + decrypt: &mut dyn RecordHandler, + cs: Option, + ) -> Result, InternalError> { + // ONLY COPY: UDP packet slice -> pooled buffer + let mut buffer = Buf::new(); + buffer.extend_from_slice(record_slice); + + let is_ciphertext = Dtls13Record::is_ciphertext_header(buffer[0]); + + // Decrypt record number in-place before parsing (RFC 9147 Section 4.2.3) + if is_ciphertext && decrypt.is_peer_encryption_enabled() { + let flags = buffer[0]; + let s_flag = flags & 0b0000_1000 != 0; + let l_flag = flags & 0b0000_0100 != 0; + let seq_len: usize = if s_flag { 2 } else { 1 }; + let len_len: usize = if l_flag { 2 } else { 0 }; + let header_len = 1 + seq_len + len_len; + + if buffer.len() >= header_len + 16 { + // unwrap: bounds checked above + let ciphertext_sample: [u8; 16] = + buffer[header_len..header_len + 16].try_into().unwrap(); + + // Resolve epoch from 2-bit field (doesn't depend on seq bytes) + let epoch_bits = flags & 0x03; + let full_epoch = decrypt.resolve_epoch(epoch_bits); + + // Decrypt sequence bytes in place + decrypt.decrypt_sequence_number( + full_epoch, + &mut buffer[1..1 + seq_len], + &ciphertext_sample, + ); + } + } + + let parsed = match ParsedRecord::parse(&buffer, cs) { + Ok(p) => p, + Err(e) => { + trace!("Discarding record: parse failed: {}", e); + return Ok(None); + } + }; + let parsed = Box::new(parsed); + let record = Record { buffer, parsed }; + + // Plaintext records (epoch 0) are not encrypted + if !is_ciphertext || !decrypt.is_peer_encryption_enabled() { + return Ok(Some(record)); + } + + // Resolve the full epoch from the 2-bit value in the unified header + let epoch_bits = record.record().sequence.epoch as u8; + let full_epoch = decrypt.resolve_epoch(epoch_bits); + + // Resolve the full sequence number from the (now decrypted) partial value + let seq_bits = record.record().sequence.sequence_number; + let s_flag = record_slice[0] & 0b0000_1000 != 0; + let full_seq = decrypt.resolve_sequence(full_epoch, seq_bits, s_flag); + + let full_sequence = Sequence { + epoch: full_epoch, + sequence_number: full_seq, + }; + + // Anti-replay check (read-only, does not update window) + if !decrypt.replay_check(full_sequence) { + return Ok(None); + } + + // Save the raw header bytes for AAD before mutating the buffer. + // Max unified header without CID: flags(1) + seq(2) + length(2) = 5 bytes. + let header_end = record.record().fragment_range.start; + + // Reject protected records whose encrypted fragment is shorter than + // the per-suite minimum — they cannot hold a valid ciphertext + tag, + // so decryption would necessarily fail. Catching it here keeps the + // cipher impls' bounds-checking from being the only line of defence. + if record.buffer.len() - header_end < decrypt.min_protected_fragment_len() { + return Ok(None); + } + let mut header_buf = [0u8; 5]; + header_buf[..header_end].copy_from_slice(&record.buffer[..header_end]); + + // Extract the buffer for decryption + let mut buffer = record.buffer; + + // The encrypted part starts right after the unified header. + let ciphertext = &mut buffer[header_end..]; + + let new_len = { + let mut buffer = TmpBuf::new(ciphertext); + + // This decrypts in place. + // RFC 9147 §4.5.2: failed-to-decrypt ciphertext records MUST be silently discarded. + match decrypt.decrypt_record(&header_buf[..header_end], full_sequence, &mut buffer) { + Ok(()) => {} + Err(e) => { + trace!("Discarding ciphertext record: decryption failed: {}", e); + return Ok(None); + } + } + + buffer.len() + }; + + // Decryption succeeded — now commit the replay window update. + // RFC 9147 §4.5.1: "The window MUST NOT be updated due to a received + // record until that record has been deprotected successfully." + decrypt.replay_update(full_sequence); + + // Recover inner content type from DTLSInnerPlaintext + let decrypted = &buffer[header_end..header_end + new_len]; + let (inner_content_type, content_len) = match recover_inner_content_type(decrypted) { + Ok(v) => v, + Err(e) => { + trace!("Discarding record: invalid inner content type: {}", e); + return Ok(None); + } + }; + + let parsed = ParsedRecord::parse_decrypted( + Dtls13Record { + content_type: inner_content_type, + sequence: full_sequence, + length: content_len as u16, + fragment_range: header_end..(header_end + content_len), + }, + &buffer, + cs, + ); + let parsed = Box::new(parsed); + + Ok(Some(Record { buffer, parsed })) + } + + pub fn record(&self) -> &Dtls13Record { + &self.parsed.record + } + + pub fn handshakes(&self) -> &[Handshake] { + &self.parsed.handshakes + } + + pub fn first_handshake(&self) -> Option<&Handshake> { + self.parsed.handshakes.first() + } + + pub fn is_handled(&self) -> bool { + if self.parsed.handshakes.is_empty() { + self.parsed.handled.load(Ordering::Relaxed) + } else { + self.parsed.handshakes.iter().all(|h| h.is_handled()) + } + } + + pub fn set_handled(&self) { + // Handshakes should be empty because we set_handled() on them individually + // during defragmentation. set_handled() on the record is only for non-handshakes. + assert!(self.parsed.handshakes.is_empty()); + self.parsed.handled.store(true, Ordering::Relaxed); + } + + pub fn buffer(&self) -> &[u8] { + &self.buffer + } + + pub(crate) fn into_buffer(self) -> Buf { + self.buffer + } +} + +pub struct ParsedRecord { + record: Dtls13Record, + handshakes: ArrayVec, + handled: AtomicBool, +} + +impl ParsedRecord { + pub fn parse( + input: &[u8], + cipher_suite: Option, + ) -> Result { + let (_, record) = Dtls13Record::parse(input, 0)?; + + let handshakes = if record.content_type == ContentType::Handshake { + let fragment_offset = record.fragment_range.start; + parse_handshakes(record.fragment(input), fragment_offset, cipher_suite) + } else { + ArrayVec::new() + }; + + Ok(ParsedRecord { + record, + handshakes, + handled: AtomicBool::new(false), + }) + } + + /// Build a ParsedRecord from an already-constructed record (after decryption). + pub fn parse_decrypted( + record: Dtls13Record, + input: &[u8], + cipher_suite: Option, + ) -> ParsedRecord { + let handshakes = if record.content_type == ContentType::Handshake { + let fragment_offset = record.fragment_range.start; + parse_handshakes(record.fragment(input), fragment_offset, cipher_suite) + } else { + ArrayVec::new() + }; + + ParsedRecord { + record, + handshakes, + handled: AtomicBool::new(false), + } + } +} + +/// Trait abstracting record parsing-time handling for incoming records. +/// +/// This decouples the record parser from the full `Engine`, allowing the parse loop +/// to decrypt records, classify control records, and queue only the records that +/// should survive into `Incoming`. +pub trait RecordHandler { + fn classify_record(&mut self, record: Record) -> Result, Error>; + fn is_peer_encryption_enabled(&self) -> bool; + fn resolve_epoch(&self, epoch_bits: u8) -> u16; + fn resolve_sequence(&self, epoch: u16, seq_bits: u64, s_flag: bool) -> u64; + fn replay_check(&self, seq: Sequence) -> bool; + fn replay_update(&mut self, seq: Sequence); + + /// Minimum length of a protected record's encrypted fragment for the + /// negotiated suite (tag length in DTLS 1.3). Used to reject records that + /// cannot possibly contain a valid ciphertext + tag. + fn min_protected_fragment_len(&self) -> usize; + + fn decrypt_record( + &mut self, + header: &[u8], + seq: Sequence, + ciphertext: &mut TmpBuf, + ) -> Result<(), Error>; + + /// Decrypt the sequence number bytes in a unified header (RFC 9147 Section 4.2.3). + /// + /// `epoch` is the resolved full epoch, `seq_bytes` are the encrypted sequence + /// bytes from the header (1 or 2 bytes), and `ciphertext_sample` is the first + /// 16 bytes of the ciphertext following the header. + /// + /// Returns the decrypted sequence bytes in-place. + fn decrypt_sequence_number( + &self, + epoch: u16, + seq_bytes: &mut [u8], + ciphertext_sample: &[u8; 16], + ); +} + +fn parse_handshakes( + mut input: &[u8], + mut base_offset: usize, + cipher_suite: Option, +) -> ArrayVec { + let mut handshakes = ArrayVec::new(); + while !input.is_empty() { + if let Ok((remaining, handshake)) = Handshake::parse(input, base_offset, cipher_suite, true) + { + let len = input.len() - remaining.len(); + base_offset += len; + input = remaining; + if handshakes.try_push(handshake).is_err() { + break; + } + } else { + break; + } + } + handshakes +} + +/// Recover the inner content type from a decrypted DTLSInnerPlaintext. +/// +/// The format is: `content || ContentType || zeros*` +/// Scan backward past zero padding to find the content type byte. +fn recover_inner_content_type(decrypted: &[u8]) -> Result<(ContentType, usize), InternalError> { + let mut i = decrypted.len(); + // Skip zero padding + while i > 0 && decrypted[i - 1] == 0 { + i -= 1; + } + if i == 0 { + return Err(InternalError::parse(nom::error::ErrorKind::Fail)); + } + // The byte before padding is the content type + i -= 1; + let content_type = ContentType::from_u8(decrypted[i]); + // Content length is everything before the content type byte + Ok((content_type, i)) +} + +impl fmt::Debug for Incoming { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Incoming") + .field("records", &self.records()) + .finish() + } +} + +impl fmt::Debug for Record { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Record") + .field("record", &self.parsed.record) + .field("handshakes", &self.parsed.handshakes) + .finish() + } +} + +/* +Why it is sound to assert UnwindSafe for Incoming + +- No internal unwind boundaries: this crate does not use catch_unwind. We do not + cross panic boundaries internally while mutating state. This marker exists to + document that external callers can wrap our APIs in catch_unwind without + observing broken invariants from this type. + +- Read-only builders: our dependent builders (e.g., ParsedRecord::parse) take + only a &[u8] to the buffer and do not mutate the buffer during construction. + An unwind during builder execution therefore cannot leave the buffer partially + mutated across a boundary. + +- Decrypt-and-reparse is publish-after-complete: when decrypting we first extract + the buffer, mutate it (in-place decrypt), and only then construct a fresh Record + from the fully transformed bytes. If a panic occurs mid-transformation, the new + Record is not built and the previously-built Record is dropped; no consumer can + observe a half-transformed record across an unwind boundary. + +- Interior mutability is benign across unwind: the only interior mutability is + AtomicBool "handled" flags. They are monotonic (false -> true). If an external + caller catches a panic and continues, the worst effect is conservatively + skipping work already done. This does not introduce memory unsafety or aliasing + violations, and no invariants rely on "handled implies delivery". + +Given the above, an unwind cannot leave Incoming in a state where broken +invariants are later observed across a catch_unwind boundary. Marking Incoming +as UnwindSafe is a sound assertion and clarifies behavior for callers. +*/ +impl std::panic::UnwindSafe for Incoming {} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct TestHandler { + classify_calls: usize, + dropped_acks: usize, + } + + impl RecordHandler for TestHandler { + fn classify_record(&mut self, record: Record) -> Result, Error> { + self.classify_calls += 1; + if record.record().content_type == ContentType::Ack { + self.dropped_acks += 1; + return Ok(None); + } + Ok(Some(record)) + } + + fn is_peer_encryption_enabled(&self) -> bool { + false + } + + fn resolve_epoch(&self, _epoch_bits: u8) -> u16 { + panic!("resolve_epoch should not be called when peer encryption is disabled"); + } + + fn resolve_sequence(&self, _epoch: u16, _seq_bits: u64, _s_flag: bool) -> u64 { + panic!("resolve_sequence should not be called when peer encryption is disabled"); + } + + fn replay_check(&self, _seq: Sequence) -> bool { + panic!("replay_check should not be called when peer encryption is disabled"); + } + + fn replay_update(&mut self, _seq: Sequence) { + panic!("replay_update should not be called when peer encryption is disabled"); + } + + fn min_protected_fragment_len(&self) -> usize { + panic!( + "min_protected_fragment_len should not be called when peer encryption is disabled" + ); + } + + fn decrypt_record( + &mut self, + _header: &[u8], + _seq: Sequence, + _ciphertext: &mut TmpBuf, + ) -> Result<(), Error> { + panic!("decrypt_record should not be called when peer encryption is disabled"); + } + + fn decrypt_sequence_number( + &self, + _epoch: u16, + _seq_bytes: &mut [u8], + _ciphertext_sample: &[u8; 16], + ) { + panic!("decrypt_sequence_number should not be called when peer encryption is disabled"); + } + } + + fn build_plaintext_record(content_type: ContentType, seq: u64, fragment: &[u8]) -> Vec { + let mut out = Vec::new(); + out.push(content_type.as_u8()); + out.extend_from_slice(&[0xFE, 0xFD]); + out.extend_from_slice(&0u16.to_be_bytes()); + out.extend_from_slice(&seq.to_be_bytes()[2..]); + out.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); + out.extend_from_slice(fragment); + out + } + + fn build_ciphertext_record(epoch: u16, seq: u16, fragment: &[u8]) -> Vec { + let mut out = Vec::new(); + let flags = 0b0010_0000 | 0b0000_1000 | 0b0000_0100 | (epoch as u8 & 0x03); + out.push(flags); + out.extend_from_slice(&seq.to_be_bytes()); + out.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); + out.extend_from_slice(fragment); + out + } + + #[test] + fn parse_packet_filters_control_records_after_packet_validation() { + let mut packet = Vec::new(); + packet.extend_from_slice(&build_plaintext_record(ContentType::Ack, 1, &[0xAA, 0xBB])); + packet.extend_from_slice(&build_ciphertext_record(2, 2, &[0x11, 0x22, 0x33])); + + let mut handler = TestHandler::default(); + let incoming = Incoming::parse_packet(&packet, &mut handler, None) + .unwrap() + .expect("ciphertext application data record should remain"); + + assert_eq!(handler.classify_calls, 2); + assert_eq!(handler.dropped_acks, 1); + assert_eq!(incoming.records().len(), 1); + assert_eq!( + incoming.first().record().content_type, + ContentType::ApplicationData + ); + assert_eq!(incoming.first().record().sequence.epoch, 2); + } +} diff --git a/third_party/dimpl/src/dtls13/message/certificate.rs b/third_party/dimpl/src/dtls13/message/certificate.rs new file mode 100644 index 0000000..4e84245 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/certificate.rs @@ -0,0 +1,158 @@ +use super::Asn1Cert; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u8, be_u16, be_u24}; +use std::ops::Range; + +/// TLS 1.3 CertificateEntry (RFC 8446 Section 4.4.2). +#[derive(Debug, PartialEq, Eq)] +pub struct CertificateEntry { + pub cert: Asn1Cert, + pub extensions_range: Range, +} + +/// TLS 1.3 Certificate message (RFC 8446 Section 4.4.2). +#[derive(Debug, PartialEq, Eq)] +pub struct Certificate { + pub context_range: Range, + pub certificate_list: ArrayVec, +} + +impl Certificate { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Certificate> { + let original_input = input; + + // certificate_request_context<0..255> + let (input, context_len) = be_u8(input)?; + let (input, context_slice) = take(context_len)(input)?; + let context_relative = context_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let context_range = (base_offset + context_relative) + ..(base_offset + context_relative + context_slice.len()); + + // certificate_list<0..2^24-1> + let (input, total_len) = be_u24(input)?; + let (input, certs_data) = take(total_len)(input)?; + + let certs_base_offset = + base_offset + (certs_data.as_ptr() as usize - original_input.as_ptr() as usize); + + let mut certificate_list = ArrayVec::new(); + let mut rest = certs_data; + while !rest.is_empty() { + let entry_base = + certs_base_offset + (rest.as_ptr() as usize - certs_data.as_ptr() as usize); + + // cert_data<1..2^24-1> + let (r, cert) = Asn1Cert::parse(rest, entry_base)?; + + // extensions<0..2^16-1> + let (r, ext_len) = be_u16(r)?; + let (r, ext_slice) = take(ext_len)(r)?; + let ext_relative = ext_slice.as_ptr() as usize - certs_data.as_ptr() as usize; + let extensions_range = (certs_base_offset + ext_relative) + ..(certs_base_offset + ext_relative + ext_slice.len()); + + certificate_list + .try_push(CertificateEntry { + cert, + extensions_range, + }) + .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; + rest = r; + } + + Ok(( + input, + Certificate { + context_range, + certificate_list, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + // certificate_request_context + let context = &buf[self.context_range.clone()]; + output.push(context.len() as u8); + output.extend_from_slice(context); + + // Calculate total certificate_list length + let total_len: usize = self + .certificate_list + .iter() + .map(|entry| { + let cert_data = entry.cert.as_slice(buf); + let ext_data = &buf[entry.extensions_range.clone()]; + 3 + cert_data.len() + 2 + ext_data.len() + }) + .sum(); + output.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]); + + for entry in &self.certificate_list { + let cert_data = entry.cert.as_slice(buf); + output.extend_from_slice(&(cert_data.len() as u32).to_be_bytes()[1..]); + output.extend_from_slice(cert_data); + + let ext_data = &buf[entry.extensions_range.clone()]; + output.extend_from_slice(&(ext_data.len() as u16).to_be_bytes()); + output.extend_from_slice(ext_data); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x02, // context length + 0xAA, 0xBB, // context bytes + 0x00, 0x00, 0x12, // total certificate_list length (18) + // CertificateEntry 1 + 0x00, 0x00, 0x04, // cert_data length + 0x01, 0x02, 0x03, 0x04, // cert_data + 0x00, 0x00, // extensions length (0) + // CertificateEntry 2 + 0x00, 0x00, 0x02, // cert_data length + 0x05, 0x06, // cert_data + 0x00, 0x02, // extensions length (2) + 0xDE, 0xAD, // extension bytes (opaque) + ]; + + #[test] + fn roundtrip() { + let (rest, parsed) = Certificate::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } + + #[test] + fn rejects_too_many_certificates() { + let mut message = Vec::new(); + message.push(0x00); // empty certificate_request_context + let total_len = 33 * 6; + message.extend_from_slice(&(total_len as u32).to_be_bytes()[1..]); + for _ in 0..33 { + message.extend_from_slice(&[0x00, 0x00, 0x01, 0xAA]); // cert_data + message.extend_from_slice(&[0x00, 0x00]); // empty extensions + } + + let result = Certificate::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "oversized certificate list should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/certificate_verify.rs b/third_party/dimpl/src/dtls13/message/certificate_verify.rs new file mode 100644 index 0000000..f082091 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/certificate_verify.rs @@ -0,0 +1,43 @@ +use super::DigitallySigned; +use crate::buffer::Buf; +use nom::IResult; + +#[derive(Debug, PartialEq, Eq)] +pub struct CertificateVerify { + pub signed: DigitallySigned, +} + +impl CertificateVerify { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], CertificateVerify> { + let (input, signed) = DigitallySigned::parse(input, base_offset)?; + Ok((input, CertificateVerify { signed })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + self.signed.serialize(buf, output); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x04, 0x03, // SignatureScheme::ECDSA_SECP256R1_SHA256 + 0x00, 0x04, // Signature length + 0x01, 0x02, 0x03, 0x04, // Signature data + ]; + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = CertificateVerify::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } +} diff --git a/third_party/dimpl/src/dtls13/message/client_hello.rs b/third_party/dimpl/src/dtls13/message/client_hello.rs new file mode 100644 index 0000000..b6ceeda --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/client_hello.rs @@ -0,0 +1,385 @@ +use super::{CompressionMethod, Dtls13CipherSuite, ProtocolVersion}; +use super::{Cookie, Extension, Random, SessionId}; +use arrayvec::ArrayVec; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u8, be_u16}; +use nom::{Err, IResult}; + +use crate::buffer::Buf; +use crate::util::{many0, many1}; + +#[derive(Debug, PartialEq, Eq)] +pub struct ClientHello { + pub legacy_version: ProtocolVersion, + pub random: Random, + pub legacy_session_id: SessionId, + pub legacy_cookie: Cookie, + pub cipher_suites: ArrayVec, + pub legacy_compression_methods: ArrayVec, + pub extensions: ArrayVec, +} + +impl ClientHello { + pub fn new( + legacy_version: ProtocolVersion, + random: Random, + legacy_session_id: SessionId, + legacy_cookie: Cookie, + cipher_suites: ArrayVec, + legacy_compression_methods: ArrayVec, + ) -> Self { + ClientHello { + legacy_version, + random, + legacy_session_id, + legacy_cookie, + cipher_suites, + legacy_compression_methods, + extensions: ArrayVec::new(), + } + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ClientHello> { + Self::parse_with_options(input, base_offset, false) + } + + pub(crate) fn parse_allow_unknown_suites( + input: &[u8], + base_offset: usize, + ) -> IResult<&[u8], ClientHello> { + Self::parse_with_options(input, base_offset, true) + } + + fn parse_with_options( + input: &[u8], + base_offset: usize, + allow_unknown_suites: bool, + ) -> IResult<&[u8], ClientHello> { + let original_input = input; + let (input, legacy_version) = ProtocolVersion::parse(input)?; + let (input, random) = Random::parse(input)?; + let (input, legacy_session_id) = SessionId::parse(input)?; + let (input, legacy_cookie) = Cookie::parse(input)?; + let (input, cipher_suites_len) = be_u16(input)?; + if cipher_suites_len == 0 || cipher_suites_len % 2 != 0 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + let (input, input_cipher) = take(cipher_suites_len)(input)?; + let (rest, cipher_suites) = if allow_unknown_suites { + many0(Dtls13CipherSuite::parse, Dtls13CipherSuite::is_supported)(input_cipher)? + } else { + many1(Dtls13CipherSuite::parse, Dtls13CipherSuite::is_supported)(input_cipher)? + }; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + let (input, compression_methods_len) = be_u8(input)?; + let (input, input_compression) = take(compression_methods_len)(input)?; + let (rest, legacy_compression_methods) = + many1(CompressionMethod::parse, CompressionMethod::is_supported)(input_compression)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + + let consumed = input.as_ptr() as usize - original_input.as_ptr() as usize; + let extensions_base_offset = base_offset + consumed; + + let (remaining_input, extensions) = Self::parse_extensions(input, extensions_base_offset)?; + + Ok(( + remaining_input, + ClientHello { + legacy_version, + random, + legacy_session_id, + legacy_cookie, + cipher_suites, + legacy_compression_methods, + extensions, + }, + )) + } + + fn parse_extensions( + input: &[u8], + base_offset: usize, + ) -> IResult<&[u8], ArrayVec> { + let mut extensions = ArrayVec::new(); + + if input.is_empty() { + return Ok((input, extensions)); + } + + let original_input = input; + let (remaining, extensions_len) = be_u16(input)?; + + let (remaining, extensions_data) = take(extensions_len)(remaining)?; + if !remaining.is_empty() { + return Err(Err::Failure(Error::new(remaining, ErrorKind::LengthValue))); + } + + let consumed = extensions_data.as_ptr() as usize - original_input.as_ptr() as usize; + let data_base_offset = base_offset + consumed; + + let mut extensions_rest = extensions_data; + let mut current_offset = data_base_offset; + while !extensions_rest.is_empty() { + let before_len = extensions_rest.len(); + let (rest, extension) = Extension::parse(extensions_rest, current_offset)?; + let parsed_len = before_len - rest.len(); + current_offset += parsed_len; + + if extension.extension_type.is_supported() { + if extensions + .iter() + .any(|existing| existing.extension_type == extension.extension_type) + { + return Err(Err::Failure(Error::new( + extensions_rest, + ErrorKind::LengthValue, + ))); + } + extensions.try_push(extension).map_err(|_| { + Err::Failure(Error::new(extensions_rest, ErrorKind::LengthValue)) + })?; + } + extensions_rest = rest; + } + + Ok((remaining, extensions)) + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.legacy_version.as_u16().to_be_bytes()); + self.random.serialize(output); + output.push(self.legacy_session_id.len() as u8); + output.extend_from_slice(&self.legacy_session_id); + output.push(self.legacy_cookie.len() as u8); + output.extend_from_slice(&self.legacy_cookie); + output.extend_from_slice(&(self.cipher_suites.len() as u16 * 2).to_be_bytes()); + for suite in &self.cipher_suites { + output.extend_from_slice(&suite.as_u16().to_be_bytes()); + } + output.push(self.legacy_compression_methods.len() as u8); + for method in &self.legacy_compression_methods { + output.push(method.as_u8()); + } + + if !self.extensions.is_empty() { + let mut extensions_len = 0; + for ext in &self.extensions { + let ext_data = ext.extension_data(source_buf); + extensions_len += 4 + ext_data.len(); + } + + output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + for ext in &self.extensions { + ext.serialize(source_buf, output); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + use crate::dtls13::message::ExtensionType; + + const MESSAGE: &[u8] = &[ + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 (legacy) + // Random + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, // + 0x01, // SessionId length + 0xAA, // SessionId + 0x01, // Cookie length + 0xBB, // Cookie + 0x00, 0x04, // CipherSuites length + 0x13, 0x01, // AES_128_GCM_SHA256 + 0x13, 0x02, // AES_256_GCM_SHA384 + 0x01, // CompressionMethods length + 0x00, // Null + ]; + + #[test] + fn roundtrip() { + let random = Random::parse(&MESSAGE[2..34]).unwrap().1; + let session_id = SessionId::try_new(&[0xAA]).unwrap(); + let cookie = Cookie::try_new(&[0xBB]).unwrap(); + let mut cipher_suites = ArrayVec::new(); + cipher_suites.push(Dtls13CipherSuite::AES_128_GCM_SHA256); + cipher_suites.push(Dtls13CipherSuite::AES_256_GCM_SHA384); + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + let client_hello = ClientHello::new( + ProtocolVersion::DTLS1_2, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + ); + + let mut serialized = Buf::new(); + client_hello.serialize(&[], &mut serialized); + assert_eq!(&*serialized, MESSAGE); + + let (rest, parsed) = ClientHello::parse(&serialized, 0).unwrap(); + assert_eq!(parsed, client_hello); + + assert!(rest.is_empty()); + } + + #[test] + fn dtls12_only_cipher_suites_parse_for_auto_detection() { + let mut message = MESSAGE.to_vec(); + // DTLS 1.2 ECDHE_ECDSA AES-GCM suites are intentionally unknown to + // the DTLS 1.3 suite filter, but the ClientHello is structurally valid. + message[40..44].copy_from_slice(&[0xC0, 0x2B, 0xC0, 0x2C]); + + let (rest, parsed) = ClientHello::parse_allow_unknown_suites(&message, 0).unwrap(); + + assert!(rest.is_empty()); + assert!(parsed.cipher_suites.is_empty()); + } + + #[test] + fn dtls12_only_cipher_suites_are_rejected_by_normal_parse() { + let mut message = MESSAGE.to_vec(); + message[40..44].copy_from_slice(&[0xC0, 0x2B, 0xC0, 0x2C]); + + assert!(ClientHello::parse(&message, 0).is_err()); + } + + #[test] + fn empty_cipher_suites_is_malformed_in_both_modes() { + let mut message = Vec::new(); + message.extend_from_slice(&MESSAGE[..38]); + message.extend_from_slice(&[0x00, 0x00]); + message.extend_from_slice(&MESSAGE[44..]); + + assert!(ClientHello::parse(&message, 0).is_err()); + assert!(ClientHello::parse_allow_unknown_suites(&message, 0).is_err()); + } + + #[test] + fn odd_cipher_suites_is_malformed_in_both_modes() { + let mut message = Vec::new(); + message.extend_from_slice(&MESSAGE[..38]); + message.extend_from_slice(&[0x00, 0x03]); + message.extend_from_slice(&[0x13, 0x01, 0x13]); + message.extend_from_slice(&MESSAGE[44..]); + + assert!(ClientHello::parse(&message, 0).is_err()); + assert!(ClientHello::parse_allow_unknown_suites(&message, 0).is_err()); + } + + #[test] + fn session_id_too_long() { + let mut message = MESSAGE.to_vec(); + message[34] = 0x21; // SessionId length (33, too long) + + let result = ClientHello::parse(&message, 0); + assert!(result.is_err()); + } + + #[test] + fn cookie_too_long() { + let mut message = MESSAGE.to_vec(); + message[36] = 0xFF; // Cookie length (255, too long for available data) + + let result = ClientHello::parse(&message, 0); + assert!(result.is_err()); + } + + #[test] + fn cipher_suites_capacity_matches_known() { + let client_hello = ClientHello { + legacy_version: ProtocolVersion::DTLS1_2, + random: Random::parse(&MESSAGE[2..34]).unwrap().1, + legacy_session_id: SessionId::empty(), + legacy_cookie: Cookie::empty(), + cipher_suites: ArrayVec::new(), + legacy_compression_methods: ArrayVec::new(), + extensions: ArrayVec::new(), + }; + + assert_eq!( + client_hello.cipher_suites.capacity(), + Dtls13CipherSuite::supported().len(), + "cipher_suites ArrayVec capacity must match supported Dtls13CipherSuites" + ); + } + + #[test] + fn extensions_capacity_fits_supported() { + let client_hello = ClientHello { + legacy_version: ProtocolVersion::DTLS1_2, + random: Random::parse(&MESSAGE[2..34]).unwrap().1, + legacy_session_id: SessionId::empty(), + legacy_cookie: Cookie::empty(), + cipher_suites: ArrayVec::new(), + legacy_compression_methods: ArrayVec::new(), + extensions: ArrayVec::new(), + }; + + assert!( + client_hello.extensions.capacity() >= ExtensionType::supported().len(), + "extensions ArrayVec capacity must fit all supported ExtensionTypes" + ); + } + + #[test] + fn duplicate_supported_extensions_are_rejected() { + for count in [2, 9] { + let mut message = MESSAGE.to_vec(); + message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); + for _ in 0..count { + message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = ClientHello::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "duplicate supported extensions should fail with LengthValue" + ); + } + } + + #[test] + fn zero_length_extension_vector_rejects_trailing_bytes() { + let mut message = MESSAGE.to_vec(); + message.extend_from_slice(&0u16.to_be_bytes()); + message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + + assert!( + ClientHello::parse(&message, 0).is_err(), + "extension vector length 0 must consume the remaining ClientHello body" + ); + } + + #[test] + fn underdeclared_extension_vector_rejects_trailing_bytes() { + let mut message = MESSAGE.to_vec(); + message.extend_from_slice(&4u16.to_be_bytes()); + message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + message.push(0); + + assert!( + ClientHello::parse(&message, 0).is_err(), + "declared extension vector length must consume the remaining ClientHello body" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/digitally_signed.rs b/third_party/dimpl/src/dtls13/message/digitally_signed.rs new file mode 100644 index 0000000..8a08753 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/digitally_signed.rs @@ -0,0 +1,68 @@ +use crate::buffer::Buf; +use crate::types::SignatureScheme; +use nom::number::complete::be_u16; +use nom::{IResult, bytes::complete::take}; +use std::ops::Range; + +#[derive(Debug, PartialEq, Eq)] +pub struct DigitallySigned { + pub scheme: SignatureScheme, + pub signature_range: Range, +} + +impl DigitallySigned { + pub fn signature<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.signature_range.clone()] + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], DigitallySigned> { + let original_input = input; + let (rest, scheme) = SignatureScheme::parse(input)?; + let (rest, signature_len) = be_u16(rest)?; + let (rest, signature_slice) = take(signature_len)(rest)?; + + // Calculate absolute range in root buffer + let relative_offset = signature_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + signature_slice.len(); + + Ok(( + rest, + DigitallySigned { + scheme, + signature_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.scheme.as_u16().to_be_bytes()); + let signature = self.signature(buf); + output.extend_from_slice(&(signature.len() as u16).to_be_bytes()); + output.extend_from_slice(signature); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x04, 0x03, // SignatureScheme::ECDSA_SECP256R1_SHA256 + 0x00, 0x04, // Signature length + 0x01, 0x02, 0x03, 0x04, // Signature data + ]; + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = DigitallySigned::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } +} diff --git a/third_party/dimpl/src/dtls13/message/encrypted_extensions.rs b/third_party/dimpl/src/dtls13/message/encrypted_extensions.rs new file mode 100644 index 0000000..176f16b --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/encrypted_extensions.rs @@ -0,0 +1,129 @@ +use super::Extension; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u16; + +/// EncryptedExtensions message (RFC 8446 Section 4.3.1). +#[derive(Debug, PartialEq, Eq)] +pub struct EncryptedExtensions { + pub extensions: ArrayVec, +} + +impl EncryptedExtensions { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], EncryptedExtensions> { + let original_input = input; + let (input, extensions_len) = be_u16(input)?; + let (input, extensions_data) = take(extensions_len)(input)?; + + let data_base_offset = + base_offset + (extensions_data.as_ptr() as usize - original_input.as_ptr() as usize); + + let mut extensions = ArrayVec::new(); + let mut rest = extensions_data; + let mut current_offset = data_base_offset; + while !rest.is_empty() { + let before_len = rest.len(); + let (new_rest, ext) = Extension::parse(rest, current_offset)?; + let parsed_len = before_len - new_rest.len(); + current_offset += parsed_len; + + if ext.extension_type.is_supported() { + if extensions + .iter() + .any(|existing: &Extension| existing.extension_type == ext.extension_type) + { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + extensions + .try_push(ext) + .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; + } + rest = new_rest; + } + + Ok((input, EncryptedExtensions { extensions })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + let mut extensions_len = 0usize; + for ext in &self.extensions { + let ext_data = ext.extension_data(buf); + extensions_len += 4 + ext_data.len(); + } + + output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + for ext in &self.extensions { + ext.serialize(buf, output); + } + } +} + +#[cfg(test)] +mod tests { + use super::super::ExtensionType; + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x00, 0x0C, // Extensions length (12) + 0x00, 0x0A, // ExtensionType::SupportedGroups + 0x00, 0x08, // Extension data length + 0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, // Extension data + ]; + + #[test] + fn roundtrip() { + let (rest, parsed) = EncryptedExtensions::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } + + #[test] + fn duplicate_supported_extensions_are_rejected() { + let mut message = Vec::new(); + let count = 2; + message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); + for _ in 0..count { + message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = EncryptedExtensions::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "duplicate supported extensions should fail with LengthValue" + ); + } + + #[test] + fn too_many_distinct_supported_extensions_are_rejected() { + let mut message = Vec::new(); + message.extend_from_slice(&(ExtensionType::supported().len() as u16 * 4).to_be_bytes()); + for extension_type in ExtensionType::supported() { + message.extend_from_slice(&extension_type.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = EncryptedExtensions::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many distinct supported extensions should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extension.rs b/third_party/dimpl/src/dtls13/message/extension.rs new file mode 100644 index 0000000..4c0d457 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extension.rs @@ -0,0 +1,244 @@ +use crate::buffer::Buf; +use nom::{IResult, bytes::complete::take, number::complete::be_u16}; +use std::{fmt, ops::Range}; + +#[derive(Debug, PartialEq, Eq, Default)] +pub struct Extension { + pub extension_type: ExtensionType, + pub extension_data_range: Range, +} + +impl Extension { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Extension> { + let original_input = input; + let (input, extension_type) = ExtensionType::parse(input)?; + let (input, extension_length) = be_u16(input)?; + let (input, extension_data_slice) = if extension_length > 0 { + take(extension_length)(input)? + } else { + (input, &input[0..0]) + }; + + // Calculate absolute range in root buffer + let relative_offset = + extension_data_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + extension_data_slice.len(); + + Ok(( + input, + Extension { + extension_type, + extension_data_range: start..end, + }, + )) + } + + pub fn extension_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.extension_data_range.clone()] + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + let extension_data = self.extension_data(buf); + output.extend_from_slice(&self.extension_type.as_u16().to_be_bytes()); + output.extend_from_slice(&(extension_data.len() as u16).to_be_bytes()); + if !extension_data.is_empty() { + output.extend_from_slice(extension_data); + } + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct ExtensionType(u16); + +#[allow(non_upper_case_globals)] +impl ExtensionType { + pub const ServerName: Self = Self(0x0000); + pub const MaxFragmentLength: Self = Self(0x0001); + pub const ClientCertificateUrl: Self = Self(0x0002); + pub const TrustedCaKeys: Self = Self(0x0003); + pub const TruncatedHmac: Self = Self(0x0004); + pub const StatusRequest: Self = Self(0x0005); + pub const UserMapping: Self = Self(0x0006); + pub const ClientAuthz: Self = Self(0x0007); + pub const ServerAuthz: Self = Self(0x0008); + pub const CertType: Self = Self(0x0009); + pub const SupportedGroups: Self = Self(0x000A); + pub const EcPointFormats: Self = Self(0x000B); + pub const Srp: Self = Self(0x000C); + pub const SignatureAlgorithms: Self = Self(0x000D); + pub const UseSrtp: Self = Self(0x000E); + pub const Heartbeat: Self = Self(0x000F); + pub const ApplicationLayerProtocolNegotiation: Self = Self(0x0010); + pub const StatusRequestV2: Self = Self(0x0011); + pub const SignedCertificateTimestamp: Self = Self(0x0012); + pub const ClientCertificateType: Self = Self(0x0013); + pub const ServerCertificateType: Self = Self(0x0014); + pub const Padding: Self = Self(0x0015); + pub const EncryptThenMac: Self = Self(0x0016); + pub const ExtendedMasterSecret: Self = Self(0x0017); + pub const TokenBinding: Self = Self(0x0018); + pub const CachedInfo: Self = Self(0x0019); + pub const SessionTicket: Self = Self(0x0023); + pub const PreSharedKey: Self = Self(0x0029); + pub const EarlyData: Self = Self(0x002A); + pub const SupportedVersions: Self = Self(0x002B); + pub const Cookie: Self = Self(0x002C); + pub const PskKeyExchangeModes: Self = Self(0x002D); + pub const CertificateAuthorities: Self = Self(0x002F); + pub const OidFilters: Self = Self(0x0030); + pub const PostHandshakeAuth: Self = Self(0x0031); + pub const SignatureAlgorithmsCert: Self = Self(0x0032); + pub const KeyShare: Self = Self(0x0033); + pub const RenegotiationInfo: Self = Self(0xFF01); + + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + pub const fn as_u16(&self) -> u16 { + self.0 + } + + const fn is_unknown(&self) -> bool { + !matches!( + *self, + Self(0x0000..=0x0019 | 0x0023 | 0x0029..=0x002D | 0x002F..=0x0033 | 0xFF01) + ) + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], ExtensionType> { + let (input, value) = be_u16(input)?; + Ok((input, ExtensionType::from_u16(value))) + } + + /// Returns true if this extension type is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// Supported extension types that this DTLS 1.3 implementation handles. + pub const fn supported() -> &'static [ExtensionType; 6] { + &[ + ExtensionType::SupportedVersions, + ExtensionType::SupportedGroups, + ExtensionType::SignatureAlgorithms, + ExtensionType::KeyShare, + ExtensionType::UseSrtp, + ExtensionType::Cookie, + ] + } +} + +impl fmt::Debug for ExtensionType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unknown() { + return f.debug_tuple("Unknown").field(&self.0).finish(); + } + + let name = match *self { + ExtensionType::ServerName => "ServerName", + ExtensionType::MaxFragmentLength => "MaxFragmentLength", + ExtensionType::ClientCertificateUrl => "ClientCertificateUrl", + ExtensionType::TrustedCaKeys => "TrustedCaKeys", + ExtensionType::TruncatedHmac => "TruncatedHmac", + ExtensionType::StatusRequest => "StatusRequest", + ExtensionType::UserMapping => "UserMapping", + ExtensionType::ClientAuthz => "ClientAuthz", + ExtensionType::ServerAuthz => "ServerAuthz", + ExtensionType::CertType => "CertType", + ExtensionType::SupportedGroups => "SupportedGroups", + ExtensionType::EcPointFormats => "EcPointFormats", + ExtensionType::Srp => "Srp", + ExtensionType::SignatureAlgorithms => "SignatureAlgorithms", + ExtensionType::UseSrtp => "UseSrtp", + ExtensionType::Heartbeat => "Heartbeat", + ExtensionType::ApplicationLayerProtocolNegotiation => { + "ApplicationLayerProtocolNegotiation" + } + ExtensionType::StatusRequestV2 => "StatusRequestV2", + ExtensionType::SignedCertificateTimestamp => "SignedCertificateTimestamp", + ExtensionType::ClientCertificateType => "ClientCertificateType", + ExtensionType::ServerCertificateType => "ServerCertificateType", + ExtensionType::Padding => "Padding", + ExtensionType::EncryptThenMac => "EncryptThenMac", + ExtensionType::ExtendedMasterSecret => "ExtendedMasterSecret", + ExtensionType::TokenBinding => "TokenBinding", + ExtensionType::CachedInfo => "CachedInfo", + ExtensionType::SessionTicket => "SessionTicket", + ExtensionType::PreSharedKey => "PreSharedKey", + ExtensionType::EarlyData => "EarlyData", + ExtensionType::SupportedVersions => "SupportedVersions", + ExtensionType::Cookie => "Cookie", + ExtensionType::PskKeyExchangeModes => "PskKeyExchangeModes", + ExtensionType::CertificateAuthorities => "CertificateAuthorities", + ExtensionType::OidFilters => "OidFilters", + ExtensionType::PostHandshakeAuth => "PostHandshakeAuth", + ExtensionType::SignatureAlgorithmsCert => "SignatureAlgorithmsCert", + ExtensionType::KeyShare => "KeyShare", + ExtensionType::RenegotiationInfo => "RenegotiationInfo", + _ => unreachable!("known DTLS 1.3 extension type missing Debug label"), + }; + + f.write_str(name) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0x00, 0x0A, // ExtensionType::SupportedGroups + 0x00, 0x08, // Extension length + 0x00, 0x06, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, // Extension data + ]; + + #[test] + fn extension_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(ExtensionType::default().as_u16(), 0); + assert_eq!(ExtensionType::default(), ExtensionType::ServerName); + } + + #[test] + fn extension_type_wire_roundtrip() { + for extension_type in ExtensionType::supported() { + assert_eq!( + ExtensionType::from_u16(extension_type.as_u16()), + *extension_type + ); + assert!(!extension_type.is_unknown()); + } + + let unknown = ExtensionType::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn extension_type_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", ExtensionType::SupportedGroups), + "SupportedGroups" + ); + assert_eq!( + format!("{:?}", ExtensionType::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn roundtrip() { + // Parse the message with base_offset 0 + let (rest, parsed) = Extension::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + // Serialize and compare to MESSAGE + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extensions/cookie.rs b/third_party/dimpl/src/dtls13/message/extensions/cookie.rs new file mode 100644 index 0000000..972a8e9 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/cookie.rs @@ -0,0 +1,54 @@ +use nom::Err; +use nom::IResult; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u16; + +/// Parse the DTLS 1.3 Cookie extension body. +/// +/// RFC 8446 defines the extension payload as `cookie<1..2^16-1>`, +/// so the extension body is a u16 length followed by exactly that many bytes. +pub(crate) fn parse_cookie_extension(input: &[u8]) -> IResult<&[u8], &[u8]> { + if input.len() < 2 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let (rest, cookie_len) = be_u16(input)?; + if cookie_len == 0 || rest.len() != cookie_len as usize { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok((&[], rest)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn malformed_cookie_vectors_are_rejected() { + for input in [ + &[][..], + &[0x00], + &[0x00, 0x00], + &[0x00, 0x02, 0xAA], + &[0x00, 0x01, 0xAA, 0xBB], + ] { + let result = parse_cookie_extension(input); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "malformed cookie vector should fail with LengthValue: {input:02x?}" + ); + } + } + + #[test] + fn valid_cookie_vector_is_accepted() { + let (rest, cookie) = parse_cookie_extension(&[0x00, 0x02, 0xAA, 0xBB]).unwrap(); + assert!(rest.is_empty()); + assert_eq!(cookie, &[0xAA, 0xBB]); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extensions/key_share.rs b/third_party/dimpl/src/dtls13/message/extensions/key_share.rs new file mode 100644 index 0000000..04256dc --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/key_share.rs @@ -0,0 +1,296 @@ +use crate::buffer::Buf; +use crate::types::NamedGroup; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u16; +use std::ops::Range; + +/// A single KeyShareEntry (RFC 8446 Section 4.2.8). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyShareEntry { + pub group: NamedGroup, + pub key_exchange_range: Range, +} + +impl KeyShareEntry { + pub fn key_exchange<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.key_exchange_range.clone()] + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], KeyShareEntry> { + let original_input = input; + let (input, group) = NamedGroup::parse(input)?; + let (input, ke_len) = be_u16(input)?; + let (input, ke_slice) = take(ke_len)(input)?; + + let relative_offset = ke_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + ke_slice.len(); + + Ok(( + input, + KeyShareEntry { + group, + key_exchange_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.group.as_u16().to_be_bytes()); + let ke = self.key_exchange(buf); + output.extend_from_slice(&(ke.len() as u16).to_be_bytes()); + output.extend_from_slice(ke); + } +} + +/// KeyShare extension in ClientHello (RFC 8446 Section 4.2.8). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyShareClientHello { + pub entries: ArrayVec, +} + +impl KeyShareClientHello { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], KeyShareClientHello> { + let original_input = input; + let (input, list_len) = be_u16(input)?; + let (input, entries_data) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let entries_base_offset = + base_offset + (entries_data.as_ptr() as usize - original_input.as_ptr() as usize); + + let mut entries = ArrayVec::new(); + let mut rest = entries_data; + while !rest.is_empty() { + let entry_offset = + entries_base_offset + (rest.as_ptr() as usize - entries_data.as_ptr() as usize); + let (r, entry) = KeyShareEntry::parse(rest, entry_offset)?; + if entry.group.is_supported() { + entries + .try_push(entry) + .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; + } + rest = r; + } + + Ok((input, KeyShareClientHello { entries })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + // Calculate total length of entries + let total_len: usize = self + .entries + .iter() + .map(|e| 2 + 2 + e.key_exchange(buf).len()) + .sum(); + output.extend_from_slice(&(total_len as u16).to_be_bytes()); + + for entry in &self.entries { + entry.serialize(buf, output); + } + } +} + +/// KeyShare extension in ServerHello (RFC 8446 Section 4.2.8). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyShareServerHello { + pub entry: KeyShareEntry, +} + +impl KeyShareServerHello { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], KeyShareServerHello> { + let (input, entry) = KeyShareEntry::parse(input, base_offset)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok((input, KeyShareServerHello { entry })) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + self.entry.serialize(buf, output); + } +} + +/// KeyShare extension in HelloRetryRequest (RFC 8446 Section 4.2.8). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyShareHelloRetryRequest { + pub selected_group: NamedGroup, +} + +impl KeyShareHelloRetryRequest { + pub fn parse(input: &[u8]) -> IResult<&[u8], KeyShareHelloRetryRequest> { + let (input, selected_group) = NamedGroup::parse(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok((input, KeyShareHelloRetryRequest { selected_group })) + } + + pub fn serialize(&self, output: &mut Buf) { + output.extend_from_slice(&self.selected_group.as_u16().to_be_bytes()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn key_share_client_hello_roundtrip() { + let message: &[u8] = &[ + 0x00, 0x08, // client_shares length (8) + 0x00, 0x1D, // NamedGroup::X25519 + 0x00, 0x04, // key_exchange length + 0x01, 0x02, 0x03, 0x04, // key_exchange data + ]; + + let (rest, parsed) = KeyShareClientHello::parse(message, 0).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(message, &mut serialized); + assert_eq!(&*serialized, message); + } + + #[test] + fn key_share_server_hello_roundtrip() { + let message: &[u8] = &[ + 0x00, 0x1D, // NamedGroup::X25519 + 0x00, 0x04, // key_exchange length + 0x01, 0x02, 0x03, 0x04, // key_exchange data + ]; + + let (rest, parsed) = KeyShareServerHello::parse(message, 0).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(message, &mut serialized); + assert_eq!(&*serialized, message); + } + + #[test] + fn key_share_hrr_roundtrip() { + let message: &[u8] = &[ + 0x00, 0x17, // NamedGroup::Secp256r1 + ]; + + let (rest, parsed) = KeyShareHelloRetryRequest::parse(message).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(&mut serialized); + assert_eq!(&*serialized, message); + } + + #[test] + fn distinct_supported_key_shares_are_accepted() { + let mut message = Vec::new(); + message.extend_from_slice(&(NamedGroup::supported().len() as u16 * 5).to_be_bytes()); + for group in NamedGroup::supported() { + message.extend_from_slice(&group.as_u16().to_be_bytes()); + message.extend_from_slice(&1u16.to_be_bytes()); + message.push(0x42); + } + + let (rest, parsed) = KeyShareClientHello::parse(&message, 0).unwrap(); + assert!(rest.is_empty()); + assert_eq!(parsed.entries.len(), NamedGroup::supported().len()); + + let mut serialized = Buf::new(); + parsed.serialize(&message, &mut serialized); + assert_eq!(&*serialized, message); + } + + #[test] + fn too_many_duplicate_supported_key_shares_are_rejected() { + let mut message = Vec::new(); + let count = NamedGroup::supported().len() + 1; + message.extend_from_slice(&(count as u16 * 5).to_be_bytes()); + for _ in 0..count { + message.extend_from_slice(&NamedGroup::X25519.as_u16().to_be_bytes()); + message.extend_from_slice(&1u16.to_be_bytes()); + message.push(0x42); + } + + let result = KeyShareClientHello::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many duplicate key shares should fail with LengthValue" + ); + } + + #[test] + fn trailing_client_key_share_bytes_are_rejected() { + let result = KeyShareClientHello::parse( + &[ + 0x00, 0x08, // client_shares length (8) + 0x00, 0x1D, // NamedGroup::X25519 + 0x00, 0x04, // key_exchange length + 0x01, 0x02, 0x03, 0x04, // key_exchange data + 0xFF, // Extension body has a trailing byte beyond the vector. + ], + 0, + ); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing key_share client bytes should fail with LengthValue" + ); + } + + #[test] + fn trailing_server_key_share_bytes_are_rejected() { + let result = KeyShareServerHello::parse( + &[ + 0x00, 0x1D, // NamedGroup::X25519 + 0x00, 0x04, // key_exchange length + 0x01, 0x02, 0x03, 0x04, // key_exchange data + 0xFF, // Extension body has a trailing byte after the entry. + ], + 0, + ); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing key_share server bytes should fail with LengthValue" + ); + } + + #[test] + fn trailing_hello_retry_request_key_share_bytes_are_rejected() { + let result = KeyShareHelloRetryRequest::parse(&[ + 0x00, 0x1D, // NamedGroup::X25519 + 0xFF, // Extension body has a trailing byte after selected_group. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing key_share HRR bytes should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extensions/mod.rs b/third_party/dimpl/src/dtls13/message/extensions/mod.rs new file mode 100644 index 0000000..2ba3d73 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/mod.rs @@ -0,0 +1,6 @@ +pub mod cookie; +pub mod key_share; +pub mod signature_algorithms; +pub mod supported_groups; +pub mod supported_versions; +pub mod use_srtp; diff --git a/third_party/dimpl/src/dtls13/message/extensions/signature_algorithms.rs b/third_party/dimpl/src/dtls13/message/extensions/signature_algorithms.rs new file mode 100644 index 0000000..8c1ca40 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/signature_algorithms.rs @@ -0,0 +1,187 @@ +use crate::buffer::Buf; +use crate::types::SignatureScheme; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; + +/// SignatureAlgorithms extension for TLS 1.3 (RFC 8446 Section 4.2.3). +/// +/// Uses `SignatureScheme` (u16) instead of the TLS 1.2 `SignatureAndHashAlgorithm`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignatureAlgorithmsExtension { + pub supported_signature_algorithms: ArrayVec, +} + +impl SignatureAlgorithmsExtension { + /// Create a default SignatureAlgorithmsExtension with supported schemes. + pub fn default() -> Self { + SignatureAlgorithmsExtension { + supported_signature_algorithms: SignatureScheme::supported(), + } + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAlgorithmsExtension> { + let (input, list_len) = nom::number::complete::be_u16(input)?; + if list_len == 0 || list_len % 2 != 0 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let mut algorithms: ArrayVec = ArrayVec::new(); + let (input, mut current_input) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + while !current_input.is_empty() { + let (rest, scheme) = SignatureScheme::parse(current_input)?; + if scheme.is_supported() { + algorithms + .try_push(scheme) + .map_err(|_| Err::Failure(Error::new(current_input, ErrorKind::LengthValue)))?; + } + current_input = rest; + } + + Ok(( + input, + SignatureAlgorithmsExtension { + supported_signature_algorithms: algorithms, + }, + )) + } + + pub fn serialize(&self, output: &mut Buf) { + output.extend_from_slice( + &((self.supported_signature_algorithms.len() * 2) as u16).to_be_bytes(), + ); + + for scheme in &self.supported_signature_algorithms { + output.extend_from_slice(&scheme.as_u16().to_be_bytes()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_signature_algorithms_extension() { + let mut algorithms: ArrayVec = ArrayVec::new(); + algorithms.push(SignatureScheme::ECDSA_SECP256R1_SHA256); + algorithms.push(SignatureScheme::ECDSA_SECP384R1_SHA384); + + let ext = SignatureAlgorithmsExtension { + supported_signature_algorithms: algorithms.clone(), + }; + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x00, 0x04, // Length (4 bytes) + 0x04, 0x03, // ECDSA_SECP256R1_SHA256 + 0x05, 0x03, // ECDSA_SECP384R1_SHA384 + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = SignatureAlgorithmsExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.supported_signature_algorithms, algorithms); + } + + #[test] + fn capacity_matches_supported() { + let ext = SignatureAlgorithmsExtension::default(); + assert_eq!( + ext.supported_signature_algorithms.capacity(), + SignatureScheme::supported().len(), + "SignatureAlgorithmsExtension capacity must match supported schemes count" + ); + } + + #[test] + fn too_many_supported_signature_algorithms_are_rejected() { + let mut bytes = Vec::new(); + let supported = SignatureScheme::supported(); + let count = supported.len() + 1; + bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes()); + for _ in 0..count { + bytes.extend_from_slice( + &SignatureScheme::ECDSA_SECP256R1_SHA256 + .as_u16() + .to_be_bytes(), + ); + } + + let result = SignatureAlgorithmsExtension::parse(&bytes); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many supported signature algorithms should fail with LengthValue" + ); + } + + #[test] + fn odd_length_signature_algorithms_are_rejected_without_panic() { + let result = std::panic::catch_unwind(|| { + SignatureAlgorithmsExtension::parse(&[ + 0x00, 0x01, // Declared list length is not divisible by 2. + 0x04, 0x03, // Extra byte proves the parser must reject before looping. + ]) + }); + + assert!( + result.is_ok(), + "odd signature_algorithms length must not panic" + ); + assert!( + matches!( + result.unwrap(), + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "odd signature_algorithms length should fail with LengthValue" + ); + } + + #[test] + fn empty_signature_algorithms_are_rejected() { + let result = SignatureAlgorithmsExtension::parse(&[ + 0x00, 0x00, // Empty signature_algorithms vector is invalid. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "empty signature_algorithms vector should fail with LengthValue" + ); + } + + #[test] + fn trailing_signature_algorithms_bytes_are_rejected() { + let result = SignatureAlgorithmsExtension::parse(&[ + 0x00, 0x02, // One algorithm follows. + 0x04, 0x03, // ECDSA_SECP256R1_SHA256 + 0xff, // Extension body has a trailing byte beyond the vector. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing signature_algorithms bytes should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extensions/supported_groups.rs b/third_party/dimpl/src/dtls13/message/extensions/supported_groups.rs new file mode 100644 index 0000000..2bcdff1 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/supported_groups.rs @@ -0,0 +1,169 @@ +use crate::buffer::Buf; +use crate::types::NamedGroup; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; + +/// SupportedGroups extension as defined in RFC 8422 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SupportedGroupsExtension { + pub groups: ArrayVec, +} + +impl SupportedGroupsExtension { + pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedGroupsExtension> { + let (input, list_len) = nom::number::complete::be_u16(input)?; + if list_len % 2 != 0 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let (input, mut current_input) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let mut groups: ArrayVec = ArrayVec::new(); + + // Parse groups; only include supported groups (skip Unknown and unsupported) + while !current_input.is_empty() { + let group_input = current_input; + let (rest, group) = NamedGroup::parse(group_input)?; + current_input = rest; + // Only add supported groups + if group.is_supported() { + groups + .try_push(group) + .map_err(|_| Err::Failure(Error::new(group_input, ErrorKind::LengthValue)))?; + } + } + + Ok((input, SupportedGroupsExtension { groups })) + } + + pub fn serialize(&self, output: &mut Buf) { + // Write the total length of all groups (2 bytes per group) + output.extend_from_slice(&((self.groups.len() * 2) as u16).to_be_bytes()); + + // Write each group + for group in &self.groups { + output.extend_from_slice(&group.as_u16().to_be_bytes()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn test_supported_groups_extension() { + let mut groups = ArrayVec::new(); + groups.push(NamedGroup::X25519); + groups.push(NamedGroup::Secp256r1); + + let ext = SupportedGroupsExtension { groups }; + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x00, 0x04, // Groups length (4 bytes) + 0x00, 0x1D, // X25519 (0x001D) + 0x00, 0x17, // secp256r1 (0x0017) + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = SupportedGroupsExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.groups.as_slice(), ext.groups.as_slice()); + } + + #[test] + fn test_supported_groups_parse_provided_bytes() { + let bytes = [0, 10, 0, 29, 0, 23, 0, 24, 1, 0, 1, 1]; + + let (rest, parsed) = + SupportedGroupsExtension::parse(&bytes).expect("parse SupportedGroups"); + assert!(rest.is_empty()); + + assert_eq!( + parsed.groups.as_slice(), + &[ + NamedGroup::X25519, + NamedGroup::Secp256r1, + NamedGroup::Secp384r1 + ] + ); + } + + #[test] + fn capacity_matches_supported() { + let ext = SupportedGroupsExtension { + groups: ArrayVec::new(), + }; + assert_eq!( + ext.groups.capacity(), + NamedGroup::supported().len(), + "SupportedGroupsExtension capacity must match all supported NamedGroups" + ); + } + + #[test] + fn too_many_supported_groups_are_rejected() { + let mut bytes = Vec::new(); + let count = NamedGroup::supported().len() + 1; + bytes.extend_from_slice(&(count as u16 * 2).to_be_bytes()); + for _ in 0..count { + bytes.extend_from_slice(&NamedGroup::X25519.as_u16().to_be_bytes()); + } + + let result = SupportedGroupsExtension::parse(&bytes); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many supported groups should fail with LengthValue" + ); + } + + #[test] + fn odd_supported_groups_vector_is_rejected() { + let result = SupportedGroupsExtension::parse(&[ + 0x00, 0x03, // Declared vector length is not divisible by 2. + 0x00, 0x1D, 0xFF, + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "odd supported_groups vector should fail with LengthValue" + ); + } + + #[test] + fn trailing_supported_groups_bytes_are_rejected() { + let result = SupportedGroupsExtension::parse(&[ + 0x00, 0x02, // One named group. + 0x00, 0x1D, // X25519. + 0xFF, // Extension body has a trailing byte beyond the vector. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing supported_groups bytes should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extensions/supported_versions.rs b/third_party/dimpl/src/dtls13/message/extensions/supported_versions.rs new file mode 100644 index 0000000..cb33a70 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/supported_versions.rs @@ -0,0 +1,201 @@ +use crate::buffer::Buf; +use crate::types::ProtocolVersion; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u8; + +/// SupportedVersions extension in ClientHello (RFC 8446 Section 4.2.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SupportedVersionsClientHello { + pub versions: ArrayVec, +} + +impl SupportedVersionsClientHello { + pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedVersionsClientHello> { + let (input, list_len) = be_u8(input)?; + if list_len == 0 || list_len % 2 != 0 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let (input, versions_data) = take(list_len)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let mut versions = ArrayVec::new(); + let mut rest = versions_data; + while !rest.is_empty() { + let (r, version) = ProtocolVersion::parse(rest)?; + if !version.is_unknown() { + versions + .try_push(version) + .map_err(|_| Err::Failure(Error::new(rest, ErrorKind::LengthValue)))?; + } + rest = r; + } + + Ok((input, SupportedVersionsClientHello { versions })) + } + + pub fn serialize(&self, output: &mut Buf) { + output.push((self.versions.len() * 2) as u8); + for version in &self.versions { + output.extend_from_slice(&version.as_u16().to_be_bytes()); + } + } +} + +/// SupportedVersions extension in ServerHello (RFC 8446 Section 4.2.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SupportedVersionsServerHello { + pub selected_version: ProtocolVersion, +} + +impl SupportedVersionsServerHello { + pub fn parse(input: &[u8]) -> IResult<&[u8], SupportedVersionsServerHello> { + let (input, selected_version) = ProtocolVersion::parse(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok((input, SupportedVersionsServerHello { selected_version })) + } + + pub fn serialize(&self, output: &mut Buf) { + output.extend_from_slice(&self.selected_version.as_u16().to_be_bytes()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn client_hello_roundtrip() { + let message: &[u8] = &[ + 0x04, // list length (4 bytes = 2 versions) + 0xFE, 0xFC, // DTLS 1.3 + 0xFE, 0xFD, // DTLS 1.2 + ]; + + let (rest, parsed) = SupportedVersionsClientHello::parse(message).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(&mut serialized); + assert_eq!(&*serialized, message); + } + + #[test] + fn server_hello_roundtrip() { + let message: &[u8] = &[ + 0xFE, 0xFC, // DTLS 1.3 + ]; + + let (rest, parsed) = SupportedVersionsServerHello::parse(message).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(&mut serialized); + assert_eq!(&*serialized, message); + } + + #[test] + fn unknown_client_hello_versions_are_ignored() { + let message: &[u8] = &[ + 0x08, // list length (8 bytes = 4 versions) + 0xFE, 0xFC, // DTLS 1.3 + 0xFE, 0xFD, // DTLS 1.2 + 0xFE, 0xFF, // DTLS 1.0 + 0xFE, 0xFE, // Unknown + ]; + + let (rest, parsed) = SupportedVersionsClientHello::parse(message).unwrap(); + assert!(rest.is_empty()); + assert_eq!( + parsed.versions.as_slice(), + &[ + ProtocolVersion::DTLS1_3, + ProtocolVersion::DTLS1_2, + ProtocolVersion::DTLS1_0, + ] + ); + } + + #[test] + fn too_many_duplicate_client_hello_versions_are_rejected() { + let message: &[u8] = &[ + 0x08, // list length (8 bytes = 4 versions) + 0xFE, 0xFC, // DTLS 1.3 + 0xFE, 0xFC, // DTLS 1.3 + 0xFE, 0xFC, // DTLS 1.3 + 0xFE, 0xFC, // DTLS 1.3 + ]; + + let result = SupportedVersionsClientHello::parse(message); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many supported versions should fail with LengthValue" + ); + } + + #[test] + fn odd_client_hello_versions_are_rejected() { + let result = SupportedVersionsClientHello::parse(&[ + 0x03, // Declared vector length is not divisible by 2. + 0xFE, 0xFC, 0xFF, + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "odd supported_versions vector should fail with LengthValue" + ); + } + + #[test] + fn trailing_client_hello_versions_bytes_are_rejected() { + let result = SupportedVersionsClientHello::parse(&[ + 0x02, // One protocol version. + 0xFE, 0xFC, // DTLS 1.3. + 0xFF, // Extension body has a trailing byte beyond the vector. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing supported_versions bytes should fail with LengthValue" + ); + } + + #[test] + fn trailing_server_hello_version_bytes_are_rejected() { + let result = SupportedVersionsServerHello::parse(&[ + 0xFE, 0xFC, // DTLS 1.3. + 0xFF, // Extension body has a trailing byte after selected_version. + ]); + + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "trailing selected_version bytes should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/extensions/use_srtp.rs b/third_party/dimpl/src/dtls13/message/extensions/use_srtp.rs new file mode 100644 index 0000000..912039b --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/extensions/use_srtp.rs @@ -0,0 +1,295 @@ +use crate::SrtpProfile; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u8, be_u16}; +use nom::{Err, IResult}; + +/// DTLS-SRTP protection profile identifiers +/// From RFC 5764 Section 4.1.2 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[allow(non_camel_case_types)] +pub enum SrtpProfileId { + #[default] + SRTP_AES128_CM_SHA1_80 = 0x0001, + SRTP_AEAD_AES_128_GCM = 0x0007, + SRTP_AEAD_AES_256_GCM = 0x0008, +} + +impl SrtpProfileId { + pub fn parse(input: &[u8]) -> IResult<&[u8], SrtpProfileId> { + let (input, value) = be_u16(input)?; + let profile = match value { + 0x0001 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, + 0x0007 => SrtpProfileId::SRTP_AEAD_AES_128_GCM, + 0x0008 => SrtpProfileId::SRTP_AEAD_AES_256_GCM, + _ => { + return Err(nom::Err::Error(nom::error::Error::new( + input, + nom::error::ErrorKind::Switch, + ))); + } + }; + Ok((input, profile)) + } + + pub fn as_u16(&self) -> u16 { + *self as u16 + } + + /// All recognized SRTP profile IDs (every non-`Unknown` variant). + pub const fn all() -> &'static [SrtpProfileId; 3] { + &[ + SrtpProfileId::SRTP_AES128_CM_SHA1_80, + SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfileId::SRTP_AEAD_AES_256_GCM, + ] + } + + /// Supported SRTP profile IDs. + pub const fn supported() -> &'static [SrtpProfileId; 3] { + Self::all() + } +} + +impl From for SrtpProfileId { + fn from(profile: SrtpProfile) -> Self { + match profile { + SrtpProfile::AES128_CM_SHA1_80 => SrtpProfileId::SRTP_AES128_CM_SHA1_80, + SrtpProfile::AEAD_AES_128_GCM => SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfile::AEAD_AES_256_GCM => SrtpProfileId::SRTP_AEAD_AES_256_GCM, + } + } +} + +impl From for SrtpProfile { + fn from(profile: SrtpProfileId) -> Self { + match profile { + SrtpProfileId::SRTP_AES128_CM_SHA1_80 => SrtpProfile::AES128_CM_SHA1_80, + SrtpProfileId::SRTP_AEAD_AES_128_GCM => SrtpProfile::AEAD_AES_128_GCM, + SrtpProfileId::SRTP_AEAD_AES_256_GCM => SrtpProfile::AEAD_AES_256_GCM, + } + } +} + +/// UseSrtp extension as defined in RFC 5764 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UseSrtpExtension { + pub profiles: ArrayVec, + pub mki: ArrayVec, // MKI value (usually empty) +} + +impl UseSrtpExtension { + pub fn new(profiles: ArrayVec, mki: ArrayVec) -> Self { + UseSrtpExtension { profiles, mki } + } + + /// Create a default UseSrtpExtension with standard profiles + pub fn default() -> Self { + let mut profiles = ArrayVec::new(); + // Add profiles in order of preference (most secure first) + profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM); + profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM); + profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80); + + // MKI is typically empty as per RFC 5764 + UseSrtpExtension { + profiles, + mki: ArrayVec::new(), + } + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], UseSrtpExtension> { + let (input, profiles_length) = be_u16(input)?; + let (input, profiles_data) = take(profiles_length)(input)?; + + // Parse the profiles (ignore unknown profile IDs instead of failing) + let mut profiles: ArrayVec = ArrayVec::new(); + let mut profiles_rest = profiles_data; + + while profiles_rest.len() >= 2 { + let profile_input = profiles_rest; + let (rest, value) = be_u16(profile_input)?; + profiles_rest = rest; + match value { + 0x0001 => profiles + .try_push(SrtpProfileId::SRTP_AES128_CM_SHA1_80) + .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, + 0x0007 => profiles + .try_push(SrtpProfileId::SRTP_AEAD_AES_128_GCM) + .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, + 0x0008 => profiles + .try_push(SrtpProfileId::SRTP_AEAD_AES_256_GCM) + .map_err(|_| Err::Failure(Error::new(profile_input, ErrorKind::LengthValue)))?, + _ => { + // Unknown SRTP profile: skip + } + } + } + if !profiles_rest.is_empty() { + return Err(Err::Failure(Error::new( + profiles_rest, + ErrorKind::LengthValue, + ))); + } + + // Parse MKI + let (input, mki_length) = be_u8(input)?; + let (input, mki) = take(mki_length)(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + Ok(( + input, + UseSrtpExtension { + profiles, + mki: ArrayVec::try_from(mki).unwrap_or_default(), + }, + )) + } + + pub fn serialize(&self, output: &mut Buf) { + // Length of all profiles (2 bytes per profile) + output.extend_from_slice(&((self.profiles.len() * 2) as u16).to_be_bytes()); + + // Write each profile + for profile in &self.profiles { + output.extend_from_slice(&profile.as_u16().to_be_bytes()); + } + + // MKI length and data + output.push(self.mki.len() as u8); + output.extend_from_slice(&self.mki); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::buffer::Buf; + + #[test] + fn test_use_srtp_extension() { + let mut profiles = ArrayVec::new(); + profiles.push(SrtpProfileId::SRTP_AEAD_AES_256_GCM); + profiles.push(SrtpProfileId::SRTP_AEAD_AES_128_GCM); + profiles.push(SrtpProfileId::SRTP_AES128_CM_SHA1_80); + + let mut mki = ArrayVec::new(); + mki.push(1); + mki.push(2); + mki.push(3); + + let ext = UseSrtpExtension::new(profiles, mki.clone()); + + let mut serialized = Buf::new(); + ext.serialize(&mut serialized); + + let expected = [ + 0x00, 0x06, // Profiles length (6 bytes) + 0x00, 0x08, // SRTP_AEAD_AES_256_GCM (0x0008) + 0x00, 0x07, // SRTP_AEAD_AES_128_GCM (0x0007) + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80 (0x0001) + 0x03, // MKI length (3 bytes) + 0x01, 0x02, 0x03, // MKI + ]; + + assert_eq!(&*serialized, expected); + + let (_, parsed) = UseSrtpExtension::parse(&serialized).unwrap(); + + assert_eq!(parsed.profiles.as_slice(), ext.profiles.as_slice()); + assert_eq!(parsed.mki, mki); + } + + #[test] + fn test_use_srtp_parse_provided_bytes() { + let bytes = [0, 8, 0, 7, 0, 8, 0, 1, 0, 2, 0]; + + let (_, parsed) = UseSrtpExtension::parse(&bytes).expect("parse UseSrtpExtension"); + + assert_eq!( + parsed.profiles.as_slice(), + &[ + SrtpProfileId::SRTP_AEAD_AES_128_GCM, + SrtpProfileId::SRTP_AEAD_AES_256_GCM, + SrtpProfileId::SRTP_AES128_CM_SHA1_80 + ] + ); + assert_eq!(parsed.mki, ArrayVec::::new()); + } + + #[test] + fn capacity_matches_profile_count() { + let ext = UseSrtpExtension::default(); + assert_eq!( + ext.profiles.capacity(), + SrtpProfileId::supported().len(), + "UseSrtpExtension capacity must match supported profile IDs" + ); + } + + #[test] + fn too_many_supported_srtp_profiles_are_rejected() { + let bytes = [ + 0x00, 0x08, // Four profile IDs. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, // Empty MKI. + ]; + + let err = UseSrtpExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } + + #[test] + fn odd_srtp_profile_vector_is_rejected() { + let bytes = [ + 0x00, 0x03, // Odd profile vector length. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, // Dangling byte in profile vector. + 0x00, // Empty MKI. + ]; + + let err = UseSrtpExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } + + #[test] + fn trailing_mki_bytes_are_rejected() { + let bytes = [ + 0x00, 0x02, // One profile ID. + 0x00, 0x01, // SRTP_AES128_CM_SHA1_80. + 0x00, // Empty MKI. + 0xFF, // Trailing extension-body byte. + ]; + + let err = UseSrtpExtension::parse(&bytes).unwrap_err(); + + assert!(matches!( + err, + Err::Failure(Error { + code: ErrorKind::LengthValue, + .. + }) + )); + } +} diff --git a/third_party/dimpl/src/dtls13/message/finished.rs b/third_party/dimpl/src/dtls13/message/finished.rs new file mode 100644 index 0000000..99d5795 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/finished.rs @@ -0,0 +1,56 @@ +use crate::buffer::Buf; +use crate::types::Dtls13CipherSuite; +use nom::IResult; +use nom::bytes::complete::take; +use std::ops::Range; + +#[derive(Debug, PartialEq, Eq)] +pub struct Finished { + pub verify_data_range: Range, +} + +impl Finished { + pub fn verify_data<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.verify_data_range.clone()] + } + + pub fn parse(input: &[u8], cipher_suite: Dtls13CipherSuite) -> IResult<&[u8], Finished> { + let verify_data_length = cipher_suite.verify_data_length(); + let (rest, verify_data_slice) = take(verify_data_length)(input)?; + + // Calculate range relative to input buffer + let start = verify_data_slice.as_ptr() as usize - input.as_ptr() as usize; + let end = start + verify_data_slice.len(); + + Ok(( + rest, + Finished { + verify_data_range: start..end, + }, + )) + } + + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + output.extend_from_slice(self.verify_data(buf)); + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::buffer::Buf; + + #[test] + fn roundtrip() { + // SHA-256 verify_data is 32 bytes + let verify_data: Vec = (0..32).collect(); + + let (rest, parsed) = + Finished::parse(&verify_data, Dtls13CipherSuite::AES_128_GCM_SHA256).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(&verify_data, &mut serialized); + assert_eq!(&*serialized, &verify_data[..]); + } +} diff --git a/third_party/dimpl/src/dtls13/message/handshake.rs b/third_party/dimpl/src/dtls13/message/handshake.rs new file mode 100644 index 0000000..77f43ff --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/handshake.rs @@ -0,0 +1,752 @@ +use std::fmt; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::{Certificate, CertificateVerify, ClientHello, Dtls13CipherSuite}; +use super::{EncryptedExtensions, Finished, ServerHello}; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u8; +use nom::number::complete::{be_u16, be_u24}; + +// Defensive stack cap over flattened handshake fragments selected for one +// defragmentation attempt. This intentionally does not mirror the receive +// queue's record-count cap; exceeding 50 fragments for one handshake implies +// pathologically tiny records and is treated as invalid input. +const MAX_DEFRAGMENT_HANDSHAKES: usize = 50; + +#[derive(Debug, PartialEq, Eq, Default, Clone, Copy)] +pub struct Header { + pub msg_type: MessageType, + pub length: u32, + pub message_seq: u16, + pub fragment_offset: u32, + pub fragment_length: u32, +} + +#[derive(Debug, Default)] +pub struct Handshake { + pub header: Header, + pub body: Body, + pub handled: AtomicBool, +} + +impl PartialEq for Handshake { + fn eq(&self, other: &Self) -> bool { + self.header == other.header + && self.body == other.body + && self.handled.load(Ordering::Relaxed) == other.handled.load(Ordering::Relaxed) + } +} + +impl Eq for Handshake {} + +impl Handshake { + #[cfg(test)] + pub fn new( + msg_type: MessageType, + length: u32, + message_seq: u16, + fragment_offset: u32, + fragment_length: u32, + body: Body, + ) -> Self { + Handshake { + header: Header { + msg_type, + length, + message_seq, + fragment_offset, + fragment_length, + }, + body, + handled: AtomicBool::new(false), + } + } + + pub fn parse_header(input: &[u8]) -> IResult<&[u8], Header> { + let (input, msg_type) = MessageType::parse(input)?; + let (input, length) = be_u24(input)?; + let (input, message_seq) = be_u16(input)?; + let (input, fragment_offset) = be_u24(input)?; + let (input, fragment_length) = be_u24(input)?; + + Ok(( + input, + Header { + msg_type, + length, + message_seq, + fragment_offset, + fragment_length, + }, + )) + } + + pub fn parse( + input: &[u8], + base_offset: usize, + c: Option, + as_fragment: bool, + ) -> IResult<&[u8], Handshake> { + let original_input = input; + let (input, header) = Self::parse_header(input)?; + + let is_fragment = header.fragment_offset > 0 || header.fragment_length < header.length; + + if !as_fragment && is_fragment { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + + let (input, body) = if as_fragment { + let (input, fragment_slice) = take(header.fragment_length as usize)(input)?; + // Calculate range relative to original input + let relative_offset = + fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + fragment_slice.len(); + (input, Body::Fragment(start..end)) + } else { + let (input, body_bytes) = take(header.length as usize)(input)?; + // Calculate base_offset for body parsing + let consumed = body_bytes.as_ptr() as usize - original_input.as_ptr() as usize; + let body_base_offset = base_offset + consumed; + let (_, body) = Body::parse(body_bytes, body_base_offset, header.msg_type, c)?; + (input, body) + }; + + Ok(( + input, + Handshake { + header, + body, + handled: AtomicBool::new(false), + }, + )) + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + output.push(self.header.msg_type.as_u8()); + output.extend_from_slice(&self.header.length.to_be_bytes()[1..]); + output.extend_from_slice(&self.header.message_seq.to_be_bytes()); + output.extend_from_slice(&self.header.fragment_offset.to_be_bytes()[1..]); + output.extend_from_slice(&self.header.fragment_length.to_be_bytes()[1..]); + self.body.serialize(source_buf, output); + } + + #[allow(private_interfaces)] + pub fn defragment<'b>( + iter: impl Iterator, + buffer: &mut Buf, + cipher_suite: Option, + transcript: Option<&mut Buf>, + ) -> Result { + Self::defragment_with_options(iter, buffer, cipher_suite, transcript, false) + } + + pub(crate) fn defragment_allow_unknown_client_hello_suites<'b>( + iter: impl Iterator, + buffer: &mut Buf, + cipher_suite: Option, + transcript: Option<&mut Buf>, + ) -> Result { + Self::defragment_with_options(iter, buffer, cipher_suite, transcript, true) + } + + fn defragment_with_options<'b>( + mut iter: impl Iterator, + buffer: &mut Buf, + cipher_suite: Option, + transcript: Option<&mut Buf>, + allow_unknown_client_hello_suites: bool, + ) -> Result { + buffer.clear(); + + // Invariant is upheld by the caller. + let (first_handshake, first_buffer) = iter.next().unwrap(); + + let Body::Fragment(range) = &first_handshake.body else { + unreachable!("Non-Fragment body in defragment()") + }; + let mut handled = ArrayVec::<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>::new(); + handled + .try_push(first_handshake) + .map_err(|_| crate::InternalError::too_many_records())?; + buffer.extend_from_slice(&first_buffer[range.clone()]); + + let mut assembled_end = + first_handshake.header.fragment_offset + first_handshake.header.fragment_length; + + for (handshake, source_buf) in iter { + if handshake.header.msg_type != first_handshake.header.msg_type + || handshake.header.message_seq != first_handshake.header.message_seq + { + break; + } + + let Body::Fragment(range) = &handshake.body else { + unreachable!("Non-Fragment body in defragment()") + }; + + handled + .try_push(handshake) + .map_err(|_| crate::InternalError::too_many_records())?; + + // Handle overlapping fragment data: skip bytes already assembled + let frag_start = handshake.header.fragment_offset as usize; + let frag_len = handshake.header.fragment_length as usize; + let skip = (assembled_end as usize).saturating_sub(frag_start); + if skip < frag_len { + buffer.extend_from_slice(&source_buf[range.start + skip..range.end]); + } + let end = handshake.header.fragment_offset + handshake.header.fragment_length; + if end > assembled_end { + assembled_end = end; + } + } + + if buffer.len() != first_handshake.header.length as usize { + debug!("Defragmentation failed. Fragment length mismatch"); + return Err(crate::InternalError::parse_incomplete()); + } + + let (rest, body) = if allow_unknown_client_hello_suites { + match Body::parse_allow_unknown_client_hello_suites( + buffer, + 0, + first_handshake.header.msg_type, + cipher_suite, + ) { + Ok(parsed) => parsed, + Err(err) => { + mark_handled(handled); + return Err(err.into()); + } + } + } else { + match Body::parse(buffer, 0, first_handshake.header.msg_type, cipher_suite) { + Ok(parsed) => parsed, + Err(err) => { + mark_handled(handled); + return Err(err.into()); + } + } + }; + + if !rest.is_empty() + && first_handshake + .header + .msg_type + .rejects_trailing_body_bytes() + { + debug!("Defragmentation failed. Body::parse() did not consume the entire buffer"); + mark_handled(handled); + return Err(crate::InternalError::parse_incomplete()); + } + + // Intentional boundary: Body::parse validates the handshake body shape and + // extension envelopes, but known extension payloads remain validated by the + // client/server state handlers. A transiently corrupted UDP datagram whose + // extension payload fails later may therefore have been consumed here; that + // recovery edge is accepted to keep this path parser-only and avoid the + // broader transaction/rollback machinery. + mark_handled(handled); + + // If transcript is provided, write the TLS 1.3-style header + body after parsing succeeds. + // Per RFC 9147 Section 5.2, the transcript uses msg_type(1) + length(3) + // WITHOUT the DTLS-specific message_seq, fragment_offset, fragment_length. + if let Some(transcript) = transcript { + transcript.push(first_handshake.header.msg_type.as_u8()); + transcript.extend_from_slice(&first_handshake.header.length.to_be_bytes()[1..]); + transcript.extend_from_slice(&buffer[..first_handshake.header.length as usize]); + } + + let handshake = Handshake { + header: Header { + msg_type: first_handshake.header.msg_type, + length: first_handshake.header.length, + message_seq: first_handshake.header.message_seq, + fragment_offset: 0, + fragment_length: first_handshake.header.length, + }, + body, + handled: AtomicBool::new(false), + }; + + // Create a new Handshake with the merged body + Ok(handshake) + } + + // These handshakes trigger a resend of the entire flight when detected as + // duplicates. + pub fn dupe_triggers_resend(&self) -> Option { + // Only trigger on the first fragment of a handshake message to avoid + // multiple resends caused by fragmented duplicates of the same message. + if self.header.fragment_offset != 0 { + return None; + } + + let qualifies = matches!( + self.header.msg_type, + MessageType::ClientHello // flight 1 + | MessageType::Finished // client final flight + ); + + qualifies.then_some(self.header.message_seq) + } + + pub fn is_handled(&self) -> bool { + self.handled.load(Ordering::Relaxed) + } + + pub fn set_handled(&self) { + self.handled.store(true, Ordering::Relaxed); + } +} + +fn mark_handled(handled: ArrayVec<&Handshake, MAX_DEFRAGMENT_HANDSHAKES>) { + for handshake in handled { + handshake.set_handled(); + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct MessageType(u8); + +#[allow(non_upper_case_globals)] +impl MessageType { + pub const ClientHello: Self = Self(1); + pub const ServerHello: Self = Self(2); + pub const EncryptedExtensions: Self = Self(8); + pub const Certificate: Self = Self(11); + pub const CertificateRequest: Self = Self(13); + pub const CertificateVerify: Self = Self(15); + pub const Finished: Self = Self(20); + pub const KeyUpdate: Self = Self(24); + + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + pub const fn as_u8(&self) -> u8 { + self.0 + } + + const fn is_unknown(&self) -> bool { + !matches!(*self, Self(1..=2 | 8 | 11 | 13 | 15 | 20 | 24)) + } + + const fn rejects_trailing_body_bytes(&self) -> bool { + !self.is_unknown() + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], MessageType> { + let (input, byte) = be_u8(input)?; + Ok((input, Self::from_u8(byte))) + } +} + +impl fmt::Debug for MessageType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unknown() { + return f.debug_tuple("Unknown").field(&self.0).finish(); + } + + let name = match *self { + MessageType::ClientHello => "ClientHello", + MessageType::ServerHello => "ServerHello", + MessageType::EncryptedExtensions => "EncryptedExtensions", + MessageType::Certificate => "Certificate", + MessageType::CertificateRequest => "CertificateRequest", + MessageType::CertificateVerify => "CertificateVerify", + MessageType::Finished => "Finished", + MessageType::KeyUpdate => "KeyUpdate", + _ => unreachable!("known DTLS 1.3 handshake message type missing Debug label"), + }; + + f.write_str(name) + } +} + +#[allow(clippy::large_enum_variant)] +#[derive(Debug, PartialEq, Eq)] +pub enum Body { + ClientHello(ClientHello), + ServerHello(ServerHello), + EncryptedExtensions(EncryptedExtensions), + Certificate(Certificate), + CertificateRequest(Range), + CertificateVerify(CertificateVerify), + Finished(Finished), + KeyUpdate(KeyUpdateRequest), + Unknown(u8), + Fragment(Range), +} + +/// RFC 8446 Section 4.6.3 KeyUpdate request type. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum KeyUpdateRequest { + /// Peer does not need to respond with its own KeyUpdate. + UpdateNotRequested = 0, + /// Peer MUST respond with its own KeyUpdate (update_not_requested). + UpdateRequested = 1, +} + +impl KeyUpdateRequest { + /// Parse from a single byte. + pub fn from_u8(value: u8) -> Option { + match value { + 0 => Some(KeyUpdateRequest::UpdateNotRequested), + 1 => Some(KeyUpdateRequest::UpdateRequested), + _ => None, + } + } + + /// Serialize to a single byte. + pub fn as_u8(self) -> u8 { + self as u8 + } +} + +impl Default for Body { + fn default() -> Self { + Self::Unknown(0) + } +} + +impl Body { + pub fn parse( + input: &[u8], + base_offset: usize, + m: MessageType, + c: Option, + ) -> IResult<&[u8], Body> { + Self::parse_with_options(input, base_offset, m, c, false) + } + + pub(crate) fn parse_allow_unknown_client_hello_suites( + input: &[u8], + base_offset: usize, + m: MessageType, + c: Option, + ) -> IResult<&[u8], Body> { + Self::parse_with_options(input, base_offset, m, c, true) + } + + fn parse_with_options( + input: &[u8], + base_offset: usize, + m: MessageType, + c: Option, + allow_unknown_client_hello_suites: bool, + ) -> IResult<&[u8], Body> { + match m { + MessageType::ClientHello => { + let (input, client_hello) = if allow_unknown_client_hello_suites { + ClientHello::parse_allow_unknown_suites(input, base_offset)? + } else { + ClientHello::parse(input, base_offset)? + }; + Ok((input, Body::ClientHello(client_hello))) + } + MessageType::ServerHello => { + let (input, server_hello) = ServerHello::parse(input, base_offset)?; + Ok((input, Body::ServerHello(server_hello))) + } + MessageType::EncryptedExtensions => { + let (input, ee) = EncryptedExtensions::parse(input, base_offset)?; + Ok((input, Body::EncryptedExtensions(ee))) + } + MessageType::Certificate => { + let (input, certificate) = Certificate::parse(input, base_offset)?; + Ok((input, Body::Certificate(certificate))) + } + MessageType::CertificateRequest => { + let range = base_offset..(base_offset + input.len()); + Ok((&[], Body::CertificateRequest(range))) + } + MessageType::CertificateVerify => { + let (input, cv) = CertificateVerify::parse(input, base_offset)?; + Ok((input, Body::CertificateVerify(cv))) + } + MessageType::Finished => { + let cipher_suite = + c.ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; + let (input, finished) = Finished::parse(input, cipher_suite)?; + Ok((input, Body::Finished(finished))) + } + MessageType::KeyUpdate => { + let (input, byte) = be_u8(input)?; + if !input.is_empty() { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + let request = KeyUpdateRequest::from_u8(byte) + .ok_or_else(|| Err::Failure(Error::new(input, ErrorKind::Fail)))?; + Ok((input, Body::KeyUpdate(request))) + } + _ => Ok((input, Body::Unknown(m.as_u8()))), + } + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + match self { + Body::ClientHello(client_hello) => { + client_hello.serialize(source_buf, output); + } + Body::ServerHello(server_hello) => { + server_hello.serialize(source_buf, output); + } + Body::EncryptedExtensions(ee) => { + ee.serialize(source_buf, output); + } + Body::Certificate(certificate) => { + certificate.serialize(source_buf, output); + } + Body::CertificateRequest(range) => { + output.extend_from_slice(&source_buf[range.clone()]); + } + Body::CertificateVerify(cv) => { + cv.serialize(source_buf, output); + } + Body::Finished(finished) => { + finished.serialize(source_buf, output); + } + Body::KeyUpdate(request) => { + output.push(request.as_u8()); + } + Body::Unknown(value) => { + output.push(*value); + } + Body::Fragment(range) => { + output.extend_from_slice(&source_buf[range.clone()]); + } + } + } +} + +#[cfg(test)] +mod tests { + use arrayvec::ArrayVec; + + use super::*; + use crate::buffer::Buf; + use crate::dtls13::message::{CompressionMethod, Cookie, Dtls13CipherSuite}; + use crate::dtls13::message::{ProtocolVersion, Random, SessionId}; + + const MESSAGE: &[u8] = &[ + 0x01, // MessageType::ClientHello + 0x00, 0x00, 0x2E, // length + 0x00, 0x00, // message_seq + 0x00, 0x00, 0x00, // fragment_offset + 0x00, 0x00, 0x2E, // fragment_length + // ClientHello + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 (legacy) + // Random + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, // + 0x01, // SessionId length + 0xAA, // SessionId + 0x01, // Cookie length + 0xBB, // Cookie + 0x00, 0x04, // CipherSuites length + 0x13, 0x01, // AES_128_GCM_SHA256 + 0x13, 0x02, // AES_256_GCM_SHA384 + 0x01, // CompressionMethods length + 0x00, // Null + ]; + + #[test] + fn message_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(MessageType::default().as_u8(), 0); + assert!(MessageType::default().is_unknown()); + } + + #[test] + fn message_type_wire_roundtrip() { + for message_type in [ + MessageType::ClientHello, + MessageType::ServerHello, + MessageType::EncryptedExtensions, + MessageType::Certificate, + MessageType::CertificateRequest, + MessageType::CertificateVerify, + MessageType::Finished, + MessageType::KeyUpdate, + ] { + assert_eq!(MessageType::from_u8(message_type.as_u8()), message_type); + assert!(!message_type.is_unknown()); + } + + let unknown = MessageType::from_u8(0xFF); + assert_eq!(unknown.as_u8(), 0xFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn message_type_debug_stays_enum_like() { + assert_eq!(format!("{:?}", MessageType::ClientHello), "ClientHello"); + assert_eq!(format!("{:?}", MessageType::from_u8(0xFF)), "Unknown(255)"); + } + + #[test] + fn handshake_size() { + let h = Handshake::new( + MessageType::EncryptedExtensions, + 2, + 0, + 0, + 2, + Body::EncryptedExtensions(EncryptedExtensions { + extensions: ArrayVec::new(), + }), + ); + + let mut v = Buf::new(); + h.serialize(&[], &mut v); + + // 12 bytes header + 2 bytes (empty extensions length) + assert_eq!(v.len(), 14); + } + + #[test] + fn roundtrip() { + let mut serialized = Buf::new(); + + let random = Random::parse(&MESSAGE[14..46]).unwrap().1; + let session_id = SessionId::try_new(&[0xAA]).unwrap(); + let cookie = Cookie::try_new(&[0xBB]).unwrap(); + let mut cipher_suites = ArrayVec::new(); + cipher_suites.push(Dtls13CipherSuite::AES_128_GCM_SHA256); + cipher_suites.push(Dtls13CipherSuite::AES_256_GCM_SHA384); + let mut compression_methods = ArrayVec::new(); + compression_methods.push(CompressionMethod::Null); + + let client_hello = ClientHello::new( + ProtocolVersion::DTLS1_2, + random, + session_id, + cookie, + cipher_suites, + compression_methods, + ); + + let handshake = Handshake::new( + MessageType::ClientHello, + 0x2E, + 0, + 0, + 0x2E, + Body::ClientHello(client_hello), + ); + + // Serialize and compare to MESSAGE + handshake.serialize(&[], &mut serialized); + assert_eq!(&*serialized, MESSAGE); + + // Parse and compare with original + let (rest, parsed) = Handshake::parse(&serialized, 0, None, false).unwrap(); + assert_eq!(parsed, handshake); + + assert!(rest.is_empty()); + } + + #[test] + fn key_update_body_rejects_trailing_bytes() { + let source = [KeyUpdateRequest::UpdateRequested.as_u8(), 0]; + let handshake = Handshake::new( + MessageType::KeyUpdate, + source.len() as u32, + 0, + 0, + source.len() as u32, + Body::Fragment(0..source.len()), + ); + + let mut buffer = Buf::new(); + let mut transcript = Buf::new(); + let result = Handshake::defragment( + std::iter::once((&handshake, source.as_slice())), + &mut buffer, + None, + Some(&mut transcript), + ); + + assert!( + result.is_err(), + "KeyUpdate bodies with trailing bytes must be rejected" + ); + assert!(handshake.is_handled()); + assert!(transcript.is_empty()); + } + + #[test] + fn defragment_stops_at_cross_sequence_fragment() { + let body = &MESSAGE[12..]; + let mut source = body.to_vec(); + source.push(0); + + let handshake = Handshake::new( + MessageType::ClientHello, + body.len() as u32, + 0, + 0, + body.len() as u32, + Body::Fragment(0..body.len()), + ); + let decoy = Handshake::new( + MessageType::ClientHello, + body.len() as u32 + 1, + 1, + body.len() as u32, + 1, + Body::Fragment(body.len()..body.len() + 1), + ); + + let mut defragmented_buffer = Buf::new(); + let defragmented_handshake = Handshake::defragment( + [(&handshake, source.as_slice()), (&decoy, source.as_slice())].into_iter(), + &mut defragmented_buffer, + None, + None, + ) + .unwrap(); + + assert_eq!(defragmented_handshake.header.message_seq, 0); + assert_eq!(&defragmented_buffer[..body.len()], body); + assert!(handshake.is_handled()); + assert!(!decoy.is_handled()); + } + + #[test] + fn known_body_rejects_trailing_bytes() { + let source = [0, 0, 0]; + let handshake = Handshake::new( + MessageType::EncryptedExtensions, + source.len() as u32, + 0, + 0, + source.len() as u32, + Body::Fragment(0..source.len()), + ); + + let mut buffer = Buf::new(); + let mut transcript = Buf::new(); + let result = Handshake::defragment( + std::iter::once((&handshake, source.as_slice())), + &mut buffer, + None, + Some(&mut transcript), + ); + + assert!(result.is_err()); + assert!(handshake.is_handled()); + assert!(transcript.is_empty()); + } +} diff --git a/third_party/dimpl/src/dtls13/message/id.rs b/third_party/dimpl/src/dtls13/message/id.rs new file mode 100644 index 0000000..2580544 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/id.rs @@ -0,0 +1,128 @@ +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::be_u8; +use nom::{Err, IResult}; +use std::fmt; +use std::ops::Deref; + +pub struct InvalidLength(&'static str, IdType, usize); + +impl fmt::Debug for InvalidLength { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self) + } +} + +impl std::error::Error for InvalidLength {} + +impl fmt::Display for InvalidLength { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.1 { + IdType::Fixed(len) => write!( + f, + "Incorrect fixed ID ({}) length: {} should be {}", + self.0, self.2, len + ), + IdType::Variable(min, max) => write!( + f, + "Incorrect variable ID ({}) length: {} <= {} <= {}", + self.0, min, self.2, max, + ), + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum IdType { + #[allow(unused)] + Fixed(usize), + Variable(usize, usize), +} + +macro_rules! var_array { + ($name:ident, $min:expr, $max:expr) => { + #[derive(Clone, Copy)] + pub struct $name([u8; $max], usize); + + impl $name { + pub fn try_new(data: &[u8]) -> Result { + #[allow(unused_comparisons)] + if data.len() < $min || data.len() > $max { + return Err(InvalidLength( + stringify!($name), + IdType::Variable($min, $max), + data.len(), + )); + } + let mut array = [0; $max]; + array[..data.len()].copy_from_slice(data); + Ok($name(array, data.len())) + } + + pub fn empty() -> Self { + if $min > 0 { + panic!("{}::empty() is not valid", stringify!($name)); + } + Self([0; $max], 0) + } + + pub fn parse(input: &[u8]) -> IResult<&[u8], Self> { + let (input, len) = be_u8(input)?; + if len < $min as u8 || len > $max as u8 { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + let (input, data) = take(len as usize)(input)?; + // unwrap() is ok because we check the size above. + let instance = Self::try_new(data).unwrap(); + Ok((input, instance)) + } + } + + impl fmt::Debug for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self) + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}({:02x?})", stringify!($name), &self.0[..self.1]) + } + } + + impl PartialEq for $name { + fn eq(&self, other: &Self) -> bool { + self.deref() == other.deref() + } + } + + impl Eq for $name {} + + impl Deref for $name { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0[..self.1] + } + } + + impl<'a> TryFrom<&'a [u8]> for $name { + type Error = InvalidLength; + + fn try_from(value: &'a [u8]) -> Result { + Self::try_new(value) + } + } + + impl<'a> TryFrom<&'a str> for $name { + type Error = InvalidLength; + + fn try_from(value: &'a str) -> Result { + Self::try_new(value.as_bytes()) + } + } + }; +} + +var_array!(SessionId, 0, 32); +var_array!(Cookie, 0, 255); diff --git a/third_party/dimpl/src/dtls13/message/mod.rs b/third_party/dimpl/src/dtls13/message/mod.rs new file mode 100644 index 0000000..139c266 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/mod.rs @@ -0,0 +1,47 @@ +//! Low-level DTLS 1.3 message parsing and serialization types. +//! +//! This module exposes enums and helpers used for parsing TLS 1.3 handshake +//! messages over DTLS 1.3 (RFC 9147). + +mod certificate; +mod certificate_verify; +mod client_hello; +mod digitally_signed; +mod encrypted_extensions; +mod extension; +mod extensions; +mod finished; +mod handshake; +mod id; +mod record; +mod server_hello; +mod wrapped; + +pub use certificate::{Certificate, CertificateEntry}; +pub use certificate_verify::CertificateVerify; +pub use client_hello::ClientHello; +pub use digitally_signed::DigitallySigned; +pub use encrypted_extensions::EncryptedExtensions; +pub use extension::{Extension, ExtensionType}; +pub(crate) use extensions::cookie::parse_cookie_extension; +pub use extensions::key_share::{ + KeyShareClientHello, KeyShareEntry, KeyShareHelloRetryRequest, KeyShareServerHello, +}; +pub use extensions::signature_algorithms::SignatureAlgorithmsExtension; +pub use extensions::supported_groups::SupportedGroupsExtension; +pub use extensions::supported_versions::{ + SupportedVersionsClientHello, SupportedVersionsServerHello, +}; +pub use extensions::use_srtp::{SrtpProfileId, UseSrtpExtension}; +pub use finished::Finished; +pub use handshake::{Body, Handshake, Header, KeyUpdateRequest, MessageType}; +pub use id::{Cookie, SessionId}; +pub use record::Dtls13Record; +pub use server_hello::ServerHello; +pub use wrapped::{Asn1Cert, DistinguishedName}; + +// Re-export shared types +pub use crate::types::{ + CompressionMethod, ContentType, Dtls13CipherSuite, NamedGroup, ProtocolVersion, Random, + Sequence, SignatureScheme, +}; diff --git a/third_party/dimpl/src/dtls13/message/record.rs b/third_party/dimpl/src/dtls13/message/record.rs new file mode 100644 index 0000000..cbbaf73 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/record.rs @@ -0,0 +1,354 @@ +//! DTLS 1.3 record layer types. +//! +//! Supports both DTLSPlaintext (epoch 0) and DTLSCiphertext (unified header) +//! record formats per RFC 9147 Section 4. + +use std::fmt; +use std::ops::Range; + +use crate::buffer::Buf; +use crate::types::{ContentType, ProtocolVersion, Sequence}; +use crate::util::be_u48; +use nom::bytes::complete::take; +use nom::number::complete::{be_u8, be_u16}; +use nom::{Err, IResult}; + +/// DTLS 1.3 record structure. +/// +/// Represents both DTLSPlaintext (epoch 0) and DTLSCiphertext (unified header) +/// records. The format is determined during parsing based on the first byte. +#[derive(PartialEq, Eq, Default)] +pub struct Dtls13Record { + /// The content type of this record. + /// For plaintext records, this is the actual content type. + /// For ciphertext records before decryption, this is ApplicationData. + pub content_type: ContentType, + /// The epoch and sequence number. + /// For ciphertext records, epoch holds only the low 2 bits and + /// sequence_number holds the 8- or 16-bit partial value until resolved. + pub sequence: Sequence, + /// The length of the fragment. + pub length: u16, + /// The range of the fragment in the source buffer. + pub fragment_range: Range, +} + +impl Dtls13Record { + /// DTLSPlaintext header length: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) + pub const PLAINTEXT_HEADER_LEN: usize = 13; + + /// Byte offset in the plaintext record header where the 2-byte length field is + pub const PLAINTEXT_LENGTH_OFFSET: Range = 11..13; + + /// Returns true if the first byte indicates a unified (ciphertext) header. + /// + /// The fixed bit pattern `001` in the top 3 bits distinguishes ciphertext + /// records from plaintext ContentType values (all < 0x20). + pub fn is_ciphertext_header(byte: u8) -> bool { + byte & 0b1110_0000 == 0b0010_0000 + } + + /// Parse a DTLS 1.3 record from the input buffer. + /// + /// Detects plaintext vs ciphertext format from the first byte. + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Dtls13Record> { + if input.is_empty() { + return Err(Err::Error(nom::error::Error::new( + input, + nom::error::ErrorKind::Eof, + ))); + } + + if Self::is_ciphertext_header(input[0]) { + Self::parse_ciphertext(input, base_offset) + } else { + Self::parse_plaintext(input, base_offset) + } + } + + /// Parse a DTLSPlaintext record (epoch 0). + fn parse_plaintext(input: &[u8], base_offset: usize) -> IResult<&[u8], Dtls13Record> { + let original_input = input; + let (input, content_type) = ContentType::parse(input)?; // u8 + let (input, version) = ProtocolVersion::parse(input)?; // u16 + + // RFC 9147 §4.1: Only alert(21), handshake(22), and ack(26) are valid + // plaintext content types in DTLS 1.3. Reject all others. + match content_type { + ContentType::Alert | ContentType::Handshake | ContentType::Ack => {} + _ => { + return Err(Err::Failure(nom::error::Error::new( + input, + nom::error::ErrorKind::Tag, + ))); + } + } + + // Accept DTLS 1.0 or 1.2 in record layer per RFC 9147 §5.1 + // (same legacy version handling as DTLS 1.2) + match version { + ProtocolVersion::DTLS1_0 | ProtocolVersion::DTLS1_2 => {} + _ => { + return Err(Err::Failure(nom::error::Error::new( + input, + nom::error::ErrorKind::Tag, + ))); + } + } + + let (input, epoch) = be_u16(input)?; // u16 + + // RFC 9147 §4.1: DTLSPlaintext records must use epoch 0. + // Epoch values other than 0 in plaintext format are invalid. + if epoch != 0 { + return Err(Err::Failure(nom::error::Error::new( + input, + nom::error::ErrorKind::Tag, + ))); + } + + let (input, sequence_number) = be_u48(input)?; // u48 + let (input, length) = be_u16(input)?; // u16 + let (rest, fragment_slice) = take(length as usize)(input)?; + + // Calculate absolute range in root buffer + let relative_offset = fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + fragment_slice.len(); + + let sequence = Sequence { + epoch, + sequence_number, + }; + + Ok(( + rest, + Dtls13Record { + content_type, + sequence, + length, + fragment_range: start..end, + }, + )) + } + + /// Parse a DTLSCiphertext record (unified header, epoch >= 2). + /// + /// The unified header flags byte layout: + /// ```text + /// 0 1 2 3 4 5 6 7 + /// +-+-+-+-+-+-+-+-+ + /// |0|0|1|C|S|L|E E| + /// +-+-+-+-+-+-+-+-+ + /// ``` + /// C=0 always (no CID support), S=seq length, L=length present, EE=epoch low bits. + fn parse_ciphertext(input: &[u8], base_offset: usize) -> IResult<&[u8], Dtls13Record> { + let original_input = input; + let (input, flags) = be_u8(input)?; + + let c_flag = flags & 0b0001_0000 != 0; + if c_flag { + // CID not supported + return Err(Err::Failure(nom::error::Error::new( + input, + nom::error::ErrorKind::Tag, + ))); + } + + let s_flag = flags & 0b0000_1000 != 0; + let l_flag = flags & 0b0000_0100 != 0; + let epoch_bits = (flags & 0b0000_0011) as u16; + + let (input, sequence_number) = if s_flag { + let (input, seq) = be_u16(input)?; + (input, seq as u64) + } else { + let (input, seq) = be_u8(input)?; + (input, seq as u64) + }; + + let (rest, length, fragment_slice) = if l_flag { + let (input, length) = be_u16(input)?; + let (rest, fragment) = take(length as usize)(input)?; + (rest, length, fragment) + } else { + // No length field: record consumes the rest of the datagram + let length = input.len() as u16; + let (rest, fragment) = take(length as usize)(input)?; + (rest, length, fragment) + }; + + let relative_offset = fragment_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + fragment_slice.len(); + + let sequence = Sequence { + epoch: epoch_bits, + sequence_number, + }; + + Ok(( + rest, + Dtls13Record { + content_type: ContentType::ApplicationData, + sequence, + length, + fragment_range: start..end, + }, + )) + } + + /// Get the fragment data from the source buffer. + pub fn fragment<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.fragment_range.clone()] + } + + /// Serialize this record to the output buffer. + pub fn serialize(&self, buf: &[u8], output: &mut Buf) { + if self.sequence.epoch == 0 { + self.serialize_plaintext(buf, output); + } else { + self.serialize_ciphertext(buf, output); + } + } + + fn serialize_plaintext(&self, buf: &[u8], output: &mut Buf) { + output.push(self.content_type.as_u8()); + ProtocolVersion::DTLS1_2.serialize(output); + output.extend_from_slice(&self.sequence.epoch.to_be_bytes()); + output.extend_from_slice(&self.sequence.sequence_number.to_be_bytes()[2..]); + output.extend_from_slice(&self.length.to_be_bytes()); + output.extend_from_slice(self.fragment(buf)); + } + + fn serialize_ciphertext(&self, buf: &[u8], output: &mut Buf) { + // Always use S=1 (2-byte sequence) and L=1 (length present) + let flags: u8 = 0b0010_0000 + | 0b0000_1000 // S=1 + | 0b0000_0100 // L=1 + | (self.sequence.epoch as u8 & 0x03); + output.push(flags); + output.extend_from_slice(&(self.sequence.sequence_number as u16).to_be_bytes()); + output.extend_from_slice(&self.length.to_be_bytes()); + output.extend_from_slice(self.fragment(buf)); + } +} + +impl fmt::Debug for Dtls13Record { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Dtls13Record") + .field("content_type", &self.content_type) + .field("sequence", &self.sequence) + .field("length", &self.length) + .field("fragment_range", &self.fragment_range) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plaintext_content_type_whitelist() { + // RFC 9147 §4.1: Only alert(21), handshake(22), and ack(26) are valid + // plaintext content types in DTLS 1.3. Plaintext records must use epoch 0. + // ApplicationData and other invalid types are rejected at parse time. + + fn build_plaintext_record(content_type: u8) -> Vec { + vec![ + content_type, // ContentType + 0xFE, + 0xFD, // version: DTLS 1.2 + 0x00, + 0x00, // epoch: 0 (plaintext) + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, // sequence_number + 0x00, + 0x02, // length: 2 + 0xAA, + 0xBB, // fragment payload + ] + } + + fn build_plaintext_record_with_epoch(content_type: u8, epoch: u16) -> Vec { + vec![ + content_type, // ContentType + 0xFE, + 0xFD, // version: DTLS 1.2 + (epoch >> 8) as u8, + (epoch & 0xFF) as u8, // epoch + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, // sequence_number + 0x00, + 0x02, // length: 2 + 0xAA, + 0xBB, // fragment payload + ] + } + + // ALLOWED: Alert (21) with epoch 0 + let alert = build_plaintext_record(0x15); + assert!( + Dtls13Record::parse(&alert, 0).is_ok(), + "Alert should be allowed in plaintext DTLS 1.3" + ); + + // ALLOWED: Handshake (22) with epoch 0 + let handshake = build_plaintext_record(0x16); + assert!( + Dtls13Record::parse(&handshake, 0).is_ok(), + "Handshake should be allowed in plaintext DTLS 1.3" + ); + + // ALLOWED: Ack (26) with epoch 0 + let ack = build_plaintext_record(0x1A); + assert!( + Dtls13Record::parse(&ack, 0).is_ok(), + "Ack should be allowed in plaintext DTLS 1.3" + ); + + // REJECTED: ApplicationData (23) + let app_data = build_plaintext_record(0x17); + assert!( + Dtls13Record::parse(&app_data, 0).is_err(), + "ApplicationData must be rejected in plaintext DTLS 1.3" + ); + + // REJECTED: ChangeCipherSpec (20) - valid in DTLS 1.2 but not DTLS 1.3 + let ccs = build_plaintext_record(0x14); + assert!( + Dtls13Record::parse(&ccs, 0).is_err(), + "ChangeCipherSpec must be rejected in DTLS 1.3" + ); + + // REJECTED: Unknown ContentType (0xFF) + let unknown = build_plaintext_record(0xFF); + assert!( + Dtls13Record::parse(&unknown, 0).is_err(), + "Unknown ContentType must be rejected in plaintext DTLS 1.3" + ); + + // REJECTED: Plaintext format with epoch 1 (invalid per RFC 9147 §4.1) + let epoch_1_handshake = build_plaintext_record_with_epoch(0x16, 1); + assert!( + Dtls13Record::parse(&epoch_1_handshake, 0).is_err(), + "Plaintext format with epoch 1 must be rejected" + ); + + // REJECTED: Plaintext format with epoch 2 (should use unified header) + let epoch_2_handshake = build_plaintext_record_with_epoch(0x16, 2); + assert!( + Dtls13Record::parse(&epoch_2_handshake, 0).is_err(), + "Plaintext format with epoch 2 must be rejected" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/server_hello.rs b/third_party/dimpl/src/dtls13/message/server_hello.rs new file mode 100644 index 0000000..de70511 --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/server_hello.rs @@ -0,0 +1,250 @@ +use super::{CompressionMethod, Dtls13CipherSuite, Extension}; +use super::{ProtocolVersion, Random, SessionId}; +use crate::buffer::Buf; +use arrayvec::ArrayVec; +use nom::Err; +use nom::error::{Error, ErrorKind}; +use nom::{IResult, bytes::complete::take, number::complete::be_u16}; + +/// Magic random value indicating HelloRetryRequest (RFC 8446 Section 4.1.3). +const HRR_RANDOM: [u8; 32] = [ + 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, +]; + +#[derive(Debug, PartialEq, Eq)] +pub struct ServerHello { + pub legacy_version: ProtocolVersion, + pub random: Random, + pub legacy_session_id: SessionId, + pub cipher_suite: Dtls13CipherSuite, + pub legacy_compression_method: CompressionMethod, + pub extensions: Option>, +} + +impl ServerHello { + pub fn new( + legacy_version: ProtocolVersion, + random: Random, + legacy_session_id: SessionId, + cipher_suite: Dtls13CipherSuite, + legacy_compression_method: CompressionMethod, + extensions: Option>, + ) -> Self { + ServerHello { + legacy_version, + random, + legacy_session_id, + cipher_suite, + legacy_compression_method, + extensions, + } + } + + /// Returns true if this ServerHello is actually a HelloRetryRequest. + pub fn is_hello_retry_request(&self) -> bool { + self.random.bytes == HRR_RANDOM + } + + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], ServerHello> { + let original_input = input; + let (input, legacy_version) = ProtocolVersion::parse(input)?; + let (input, random) = Random::parse(input)?; + let (input, legacy_session_id) = SessionId::parse(input)?; + let (input, cipher_suite) = Dtls13CipherSuite::parse(input)?; + let (input, legacy_compression_method) = CompressionMethod::parse(input)?; + + let (input, extensions) = if !input.is_empty() { + if input.len() < 2 { + return Err(Err::Failure(Error::new(input, ErrorKind::Eof))); + } + let (input, extensions_len) = be_u16(input)?; + + if input.len() < extensions_len as usize { + return Err(Err::Failure(Error::new(input, ErrorKind::Eof))); + } + + if extensions_len > 0 { + let (rest, input_ext) = take(extensions_len)(input)?; + if !rest.is_empty() { + return Err(Err::Failure(Error::new(rest, ErrorKind::LengthValue))); + } + let consumed_to_ext_data = + input_ext.as_ptr() as usize - original_input.as_ptr() as usize; + let ext_base_offset = base_offset + consumed_to_ext_data; + + let mut extensions_vec: ArrayVec = ArrayVec::new(); + let mut current_input = input_ext; + let mut current_offset = ext_base_offset; + while !current_input.is_empty() { + let before_len = current_input.len(); + let (new_rest, ext) = Extension::parse(current_input, current_offset)?; + let parsed_len = before_len - new_rest.len(); + current_offset += parsed_len; + if ext.extension_type.is_supported() { + if extensions_vec + .iter() + .any(|existing| existing.extension_type == ext.extension_type) + { + return Err(Err::Failure(Error::new( + current_input, + ErrorKind::LengthValue, + ))); + } + extensions_vec.try_push(ext).map_err(|_| { + Err::Failure(Error::new(current_input, ErrorKind::LengthValue)) + })?; + } + current_input = new_rest; + } + (rest, Some(extensions_vec)) + } else { + (input, None) + } + } else { + (input, None) + }; + + Ok(( + input, + ServerHello { + legacy_version, + random, + legacy_session_id, + cipher_suite, + legacy_compression_method, + extensions, + }, + )) + } + + pub fn serialize(&self, source_buf: &[u8], output: &mut Buf) { + output.extend_from_slice(&self.legacy_version.as_u16().to_be_bytes()); + self.random.serialize(output); + output.push(self.legacy_session_id.len() as u8); + output.extend_from_slice(&self.legacy_session_id); + output.extend_from_slice(&self.cipher_suite.as_u16().to_be_bytes()); + output.push(self.legacy_compression_method.as_u8()); + if let Some(extensions) = &self.extensions { + let mut extensions_len = 0; + for ext in extensions.iter() { + let ext_data = ext.extension_data(source_buf); + extensions_len += 2 + 2 + ext_data.len(); + } + + output.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + for ext in extensions { + ext.serialize(source_buf, output); + } + } + } +} + +#[cfg(test)] +mod test { + use super::super::ExtensionType; + use super::*; + use crate::buffer::Buf; + + const MESSAGE: &[u8] = &[ + 0xFE, 0xFD, // ProtocolVersion::DTLS1_2 (legacy) + // Random + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, // + 0x01, // SessionId length + 0xAA, // SessionId + 0x13, 0x01, // Dtls13CipherSuite::AES_128_GCM_SHA256 + 0x00, // CompressionMethod::Null + 0x00, 0x0C, // Extensions length (12 bytes) + 0x00, 0x0A, // ExtensionType::SupportedGroups + 0x00, 0x08, // Extension data length (8 bytes) + 0x00, 0x06, // Extension data + 0x00, 0x17, // NamedGroup::Secp256r1 + 0x00, 0x18, // NamedGroup::Secp384r1 + 0x00, 0x19, // NamedGroup::Secp521r1 + ]; + + #[test] + fn roundtrip() { + let (rest, parsed) = ServerHello::parse(MESSAGE, 0).unwrap(); + assert!(rest.is_empty()); + + let mut serialized = Buf::new(); + parsed.serialize(MESSAGE, &mut serialized); + assert_eq!(&*serialized, MESSAGE); + } + + #[test] + fn session_id_too_long() { + let mut message = MESSAGE.to_vec(); + message[34] = 0x21; // SessionId length (33, too long) + + let result = ServerHello::parse(&message, 0); + assert!(result.is_err()); + } + + #[test] + fn hello_retry_request_detection() { + let hrr_random = Random { bytes: HRR_RANDOM }; + + let sh = ServerHello::new( + ProtocolVersion::DTLS1_2, + hrr_random, + SessionId::empty(), + Dtls13CipherSuite::AES_128_GCM_SHA256, + CompressionMethod::Null, + None, + ); + + assert!(sh.is_hello_retry_request()); + } + + #[test] + fn normal_server_hello_not_hrr() { + let (_, parsed) = ServerHello::parse(MESSAGE, 0).unwrap(); + assert!(!parsed.is_hello_retry_request()); + } + + #[test] + fn duplicate_supported_extensions_are_rejected() { + let mut message = MESSAGE[..39].to_vec(); + let count = 2; + message.extend_from_slice(&(count as u16 * 4).to_be_bytes()); + for _ in 0..count { + message.extend_from_slice(&ExtensionType::Cookie.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = ServerHello::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "duplicate supported extensions should fail with LengthValue" + ); + } + + #[test] + fn too_many_distinct_supported_extensions_are_rejected() { + let mut message = MESSAGE[..39].to_vec(); + message.extend_from_slice(&(ExtensionType::supported().len() as u16 * 4).to_be_bytes()); + for extension_type in ExtensionType::supported() { + message.extend_from_slice(&extension_type.as_u16().to_be_bytes()); + message.extend_from_slice(&0u16.to_be_bytes()); + } + + let result = ServerHello::parse(&message, 0); + assert!( + matches!( + result, + Err(nom::Err::Failure(error)) + if error.code == nom::error::ErrorKind::LengthValue + ), + "too many distinct supported extensions should fail with LengthValue" + ); + } +} diff --git a/third_party/dimpl/src/dtls13/message/wrapped.rs b/third_party/dimpl/src/dtls13/message/wrapped.rs new file mode 100644 index 0000000..6221d5b --- /dev/null +++ b/third_party/dimpl/src/dtls13/message/wrapped.rs @@ -0,0 +1,42 @@ +use nom::Err; +use nom::IResult; +use nom::bytes::complete::take; +use nom::error::{Error, ErrorKind}; +use nom::number::complete::{be_u16, be_u24}; +use std::ops::Range; + +macro_rules! wrapped_slice { + ($name:ident, $length_parser:path, $min:expr) => { + #[derive(Debug, Clone, PartialEq, Eq, Default)] + pub struct $name(pub Range); + + impl $name { + pub fn parse(input: &[u8], base_offset: usize) -> IResult<&[u8], Self> { + let original_input = input; + let (input, len) = $length_parser(input)?; + #[allow(unused_comparisons)] + if len < $min { + return Err(Err::Failure(Error::new(input, ErrorKind::LengthValue))); + } + let (input, data_slice) = take(len)(input)?; + + // Calculate absolute range in root buffer + let relative_offset = + data_slice.as_ptr() as usize - original_input.as_ptr() as usize; + let start = base_offset + relative_offset; + let end = start + data_slice.len(); + + Ok((input, $name(start..end))) + } + } + }; +} + +wrapped_slice!(Asn1Cert, be_u24, 0); +wrapped_slice!(DistinguishedName, be_u16, 1); + +impl Asn1Cert { + pub fn as_slice<'a>(&self, buf: &'a [u8]) -> &'a [u8] { + &buf[self.0.clone()] + } +} diff --git a/third_party/dimpl/src/dtls13/mod.rs b/third_party/dimpl/src/dtls13/mod.rs new file mode 100644 index 0000000..4fb8211 --- /dev/null +++ b/third_party/dimpl/src/dtls13/mod.rs @@ -0,0 +1,39 @@ +//! DTLS 1.3 protocol implementation. +//! + +// This is the full DTLS 1.3 handshake flow (RFC 9147) +// +// Client Server +// +// ClientHello +// + supported_versions +// + supported_groups +// + key_share +// + signature_algorithms --------> +// ServerHello +// + key_share +// + supported_versions +// {EncryptedExtensions} +// {CertificateRequest*} +// {Certificate} +// {CertificateVerify} +// <-------- {Finished} +// {Certificate*} +// {CertificateVerify*} +// {Finished} --------> +// [Application Data] <-------> [Application Data] +// +// {} = encrypted with handshake keys (epoch 2) +// [] = encrypted with application keys (epoch 3) +// * = optional (client auth) + +pub mod incoming; +pub mod message; + +mod client; +mod engine; +mod queue; +mod server; + +pub use client::Client; +pub use server::Server; diff --git a/third_party/dimpl/src/dtls13/queue.rs b/third_party/dimpl/src/dtls13/queue.rs new file mode 100644 index 0000000..8fd1ff9 --- /dev/null +++ b/third_party/dimpl/src/dtls13/queue.rs @@ -0,0 +1,115 @@ +//! Queue wrapper types with safe Debug implementations. +//! +//! These wrappers ensure that debug output only shows metadata, +//! not potentially sensitive payload data. + +use std::collections::VecDeque; +use std::fmt; +use std::ops::{Deref, DerefMut}; + +use crate::buffer::Buf; +use crate::dtls13::incoming::Incoming; +use crate::types::ContentType; + +/// Wrapper around the receive queue that provides safe Debug output. +/// +/// The Debug implementation only shows metadata (counts by content type), +/// not potentially sensitive payload data. +pub(crate) struct QueueRx(VecDeque); + +impl QueueRx { + pub fn new() -> Self { + Self(VecDeque::new()) + } +} + +impl Deref for QueueRx { + type Target = VecDeque; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for QueueRx { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl fmt::Debug for QueueRx { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut handshake = 0; + let mut app_data = 0; + let mut alert = 0; + let mut other = 0; + let mut min_seq: Option<(u16, u64)> = None; + let mut max_seq: Option<(u16, u64)> = None; + + for item in &self.0 { + let record = item.first().record(); + match record.content_type { + ContentType::Handshake => handshake += 1, + ContentType::ApplicationData => app_data += 1, + ContentType::Alert => alert += 1, + _ => other += 1, + } + + let seq = (record.sequence.epoch, record.sequence.sequence_number); + min_seq = Some(min_seq.map_or(seq, |m| m.min(seq))); + max_seq = Some(max_seq.map_or(seq, |m| m.max(seq))); + } + + let mut s = f.debug_struct("QueueRx"); + s.field("len", &self.0.len()) + .field("handshake", &handshake) + .field("app_data", &app_data) + .field("alert", &alert) + .field("other", &other); + + if let (Some(min), Some(max)) = (min_seq, max_seq) { + s.field( + "seq_range", + &format_args!("{}:{} - {}:{}", min.0, min.1, max.0, max.1), + ); + } + + s.finish() + } +} + +/// Wrapper around the transmit queue that provides safe Debug output. +/// +/// The Debug implementation only shows metadata (datagram count and total bytes), +/// not potentially sensitive payload data. +pub(crate) struct QueueTx(VecDeque); + +impl QueueTx { + pub fn new() -> Self { + Self(VecDeque::new()) + } +} + +impl Deref for QueueTx { + type Target = VecDeque; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for QueueTx { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl fmt::Debug for QueueTx { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let total_bytes: usize = self.0.iter().map(|b| b.len()).sum(); + f.debug_struct("QueueTx") + .field("datagrams", &self.0.len()) + .field("total_bytes", &total_bytes) + .finish() + } +} diff --git a/third_party/dimpl/src/dtls13/server.rs b/third_party/dimpl/src/dtls13/server.rs new file mode 100644 index 0000000..ebe3ed5 --- /dev/null +++ b/third_party/dimpl/src/dtls13/server.rs @@ -0,0 +1,1519 @@ +// DTLS 1.3 Server Handshake Flow (RFC 9147): +// +// 1. Client sends ClientHello (plaintext, epoch 0) +// - Server validates: legacy_version==DTLS1.2, null compression offered +// - Server checks supported_versions for DTLS1.3 +// - Server selects cipher suite, key exchange group, SRTP profile +// - If no cookie: send HelloRetryRequest with HMAC-based cookie +// - If cookie present: validate HMAC, proceed +// - If no matching key_share but supported_groups match: HRR for key exchange +// 2. Server sends ServerHello (plaintext, epoch 0) +// - Derives handshake secrets, installs handshake keys +// 3. Server sends EncryptedExtensions (encrypted, epoch 2) +// 4. Server sends CertificateRequest (optional, encrypted, epoch 2) +// 5. Server sends Certificate (encrypted, epoch 2) +// 6. Server sends CertificateVerify (encrypted, epoch 2) +// 7. Server sends Finished (encrypted, epoch 2) +// - Derives application secrets, installs application keys +// - Enables peer encryption for client's epoch 2 +// 8. Client sends Certificate (if requested, encrypted, epoch 2) +// 9. Client sends CertificateVerify (if cert present, encrypted, epoch 2) +// 10. Client sends Finished (encrypted, epoch 2) +// - Server verifies, emits Connected, extracts SRTP keying material +// 11. Application data flows on epoch 3 +// +// This implementation is a Sans-IO DTLS 1.3 server. + +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::Instant; + +use arrayvec::ArrayVec; +use subtle::ConstantTimeEq; + +use crate::buffer::Buf; +use crate::buffer::ToBuf; +use crate::crypto::{ActiveKeyExchange, SrtpProfile}; +use crate::dtls13::Client; +use crate::dtls13::client::LocalEvent; +use crate::dtls13::client::handshake_create_certificate; +use crate::dtls13::client::handshake_create_certificate_verify; +use crate::dtls13::client::signature_scheme_to_components; +#[cfg(feature = "_crypto-common")] +use crate::dtls13::client::verify_scheme_curve; +use crate::dtls13::engine::Engine; +use crate::dtls13::message::Body; +use crate::dtls13::message::CompressionMethod; +use crate::dtls13::message::ContentType; +use crate::dtls13::message::Dtls13CipherSuite; +use crate::dtls13::message::Extension; +use crate::dtls13::message::ExtensionType; +use crate::dtls13::message::KeyShareClientHello; +use crate::dtls13::message::KeyShareEntry; +use crate::dtls13::message::KeyShareHelloRetryRequest; +use crate::dtls13::message::KeyShareServerHello; +use crate::dtls13::message::KeyUpdateRequest; +use crate::dtls13::message::MessageType; +use crate::dtls13::message::NamedGroup; +use crate::dtls13::message::ProtocolVersion; +use crate::dtls13::message::Random; +use crate::dtls13::message::ServerHello; +use crate::dtls13::message::SessionId; +use crate::dtls13::message::SignatureAlgorithmsExtension; +use crate::dtls13::message::SignatureScheme; +use crate::dtls13::message::SupportedGroupsExtension; +use crate::dtls13::message::SupportedVersionsClientHello; +use crate::dtls13::message::SupportedVersionsServerHello; +use crate::dtls13::message::UseSrtpExtension; +use crate::dtls13::message::parse_cookie_extension; +use crate::{Config, DtlsCertificate, Error, InternalError, Output}; + +/// Magic random value indicating HelloRetryRequest (RFC 8446 Section 4.1.3). +const HRR_RANDOM: [u8; 32] = [ + 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, +]; + +const MAX_RETAINED_CLIENT_HELLO: usize = 64; + +/// DTLS 1.3 server +pub struct Server { + /// Current server state. + state: State, + + /// Engine in common between server and client. + engine: Engine, + + /// Random unique data. Used for ServerHello. + random: Option, + + /// Client's session ID echoed from ClientHello. + client_session_id: Option, + + /// Storage for extension data. + extension_data: Buf, + + /// The negotiated SRTP profile (if any). + negotiated_srtp_profile: Option, + + /// Client certificates. + client_certificates: Vec, + + /// Buffer for defragmenting handshakes. + defragment_buffer: Buf, + + /// The last now we seen. + last_now: Instant, + + /// Local events. + local_events: VecDeque, + + /// Data that is sent before we are connected. + queued_data: Vec, + + /// Active key exchange state (ECDHE). + active_key_exchange: Option>, + + /// Saved shared secret for deriving application secrets later. + shared_secret: Option, + + /// Saved handshake secret for deriving application secrets. + handshake_secret: Option, + + /// Client handshake traffic secret (for client Finished verification). + client_hs_traffic_secret: Option, + + /// Server handshake traffic secret (for server Finished). + server_hs_traffic_secret: Option, + + /// Whether we requested client authentication. + client_auth_requested: bool, + + /// Whether we sent a HelloRetryRequest. + hello_retry: bool, + + /// Cookie secret for HMAC-based DoS protection. + cookie_secret: [u8; 32], + + /// Whether we need to respond with our own KeyUpdate. + pending_key_update_response: bool, + + /// When true, a ClientHello without DTLS 1.3 in `supported_versions` + /// returns [`Error::Dtls12Fallback`] instead of a security error. + /// Used by the auto-sense server path. + auto_mode: bool, + + /// Raw packets buffered during auto-sense so they can be replayed + /// to a DTLS 1.2 server on fallback. + retained_hello: VecDeque, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + AwaitClientHello, + SendServerHello, + SendEncryptedExtensions, + SendCertificateRequest, + SendCertificate, + SendCertificateVerify, + SendFinished, + AwaitCertificate, + AwaitCertificateVerify, + AwaitFinished, + AwaitApplicationData, + HalfClosedLocal, + Closed, +} + +impl Server { + /// Create a new DTLS 1.3 server. + pub fn new(config: Arc, certificate: DtlsCertificate, now: Instant) -> Server { + let engine = Engine::new(config, certificate); + Self::new_with_engine(engine, now, false) + } + + /// Create a new DTLS 1.3 server in auto-sense mode. + /// + /// In auto-sense mode, if the ClientHello does not offer DTLS 1.3 + /// in `supported_versions`, the server returns [`Error::Dtls12Fallback`] + /// instead of a fatal security error, allowing the caller to switch + /// to a DTLS 1.2 server. + pub fn new_auto(config: Arc, certificate: DtlsCertificate, now: Instant) -> Server { + let engine = Engine::new(config, certificate); + Self::new_with_engine(engine, now, true) + } + + pub fn new_with_engine(mut engine: Engine, now: Instant, auto_mode: bool) -> Server { + let cookie_secret = engine.random_arr(); + + Server { + state: State::AwaitClientHello, + engine, + random: None, + client_session_id: None, + extension_data: Buf::new(), + negotiated_srtp_profile: None, + client_certificates: Vec::with_capacity(3), + defragment_buffer: Buf::new(), + last_now: now, + local_events: VecDeque::new(), + queued_data: Vec::new(), + active_key_exchange: None, + shared_secret: None, + handshake_secret: None, + client_hs_traffic_secret: None, + server_hs_traffic_secret: None, + client_auth_requested: false, + hello_retry: false, + cookie_secret, + pending_key_update_response: false, + auto_mode, + retained_hello: VecDeque::with_capacity(10), + } + } + + pub fn into_client(self) -> Client { + Client::new_with_engine(self.engine, self.last_now) + } + + /// Whether this server is in auto-sense mode. + pub fn is_auto_mode(&self) -> bool { + self.auto_mode + } + + /// Take all relevant config from this server instance. + /// + /// This is used in two cases: + /// + /// 1. Switching a server pending (auto-mode) to dtls12 server + /// 2. set_active(true), turning a server pending (auto-mode) to a ClientPending + pub fn into_parts(self) -> (Arc, DtlsCertificate, Instant, VecDeque) { + let (config, cert) = self.engine.into_fallback(); + (config, cert, self.last_now, self.retained_hello) + } + + pub(crate) fn state_name(&self) -> &'static str { + self.state.name() + } + + pub fn is_closing(&self) -> bool { + (matches!(self.state, State::HalfClosedLocal | State::Closed) && !self.is_closed()) + || self.engine.close_notify_pending() + } + + pub fn is_closed(&self) -> bool { + self.state == State::Closed + && self.local_events.is_empty() + && !self.engine.has_pending_close_output() + } + + pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { + // In auto-sense mode, buffer raw packets while still waiting for + // the ClientHello so they can be replayed to Server12 on fallback. + if self.auto_mode && self.state == State::AwaitClientHello { + // Cap buffered fragments to prevent unbounded growth from malicious traffic + if self.retained_hello.len() >= MAX_RETAINED_CLIENT_HELLO { + return Err(Error::TooManyClientHelloFragments); + } + self.retained_hello.push_back(packet.to_buf()); + } + + match self + .engine + .parse_packet(packet) + .and_then(|_| self.make_progress()) + { + Ok(()) => {} + Err(e) => { + if let Some(err) = e.into_public_error() { + return Err(err); + } + return Ok(()); + } + } + + // Once past AwaitClientHello, DTLS 1.3 is committed — free the buffer. + if self.auto_mode && self.state != State::AwaitClientHello { + self.retained_hello.clear(); + self.auto_mode = false; + } + + Ok(()) + } + + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { + if let Some(event) = self.local_events.pop_front() { + return event.into_output(buf, &self.client_certificates); + } + self.engine.poll_output(buf, self.last_now) + } + + /// Handle a timeout event. + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + self.last_now = now; + if self.random.is_none() { + self.random = Some(self.engine.random()); + } + self.engine.handle_timeout(now)?; + match self.make_progress() { + Ok(()) => Ok(()), + Err(e) => e.into_public_error().map_or(Ok(()), Err), + } + } + + fn initiate_key_update(&mut self) -> Result<(), Error> { + self.engine + .create_key_update(KeyUpdateRequest::UpdateRequested) + } + + /// Send application data when the server is connected. + pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { + if self.state == State::Closed || self.state == State::HalfClosedLocal { + return Err(Error::ConnectionClosed); + } + + if self.state != State::AwaitApplicationData { + self.queued_data.push(data.to_buf()); + return Ok(()); + } + + let epoch = self.engine.app_send_epoch(); + self.engine.create_ciphertext_record( + ContentType::ApplicationData, + epoch, + false, + |body| { + body.extend_from_slice(data); + }, + )?; + + Ok(()) + } + + /// Initiate graceful shutdown by sending a `close_notify` alert. + pub fn close(&mut self) -> Result<(), Error> { + if self.state == State::Closed || self.state == State::HalfClosedLocal { + return Ok(()); + } + if self.state != State::AwaitApplicationData { + self.engine.abort(); + self.state = State::Closed; + return Ok(()); + } + let epoch = self.engine.app_send_epoch(); + self.engine + .create_ciphertext_record(ContentType::Alert, epoch, false, |body| { + body.push(1); // level: legacy (ignored in DTLS 1.3) + body.push(0); // description: close_notify + })?; + self.engine.cancel_flights(); + self.state = State::HalfClosedLocal; + Ok(()) + } + + fn make_progress(&mut self) -> Result<(), InternalError> { + loop { + let prev_state = self.state; + + let new_state = prev_state.make_progress(self)?; + if prev_state != new_state { + self.state = new_state; + trace!("{:?} -> {:?}", prev_state, new_state); + } else { + break; + } + } + Ok(()) + } +} + +impl State { + fn name(&self) -> &'static str { + match self { + State::AwaitClientHello => "AwaitClientHello", + State::SendServerHello => "SendServerHello", + State::SendEncryptedExtensions => "SendEncryptedExtensions", + State::SendCertificateRequest => "SendCertificateRequest", + State::SendCertificate => "SendCertificate", + State::SendCertificateVerify => "SendCertificateVerify", + State::SendFinished => "SendFinished", + State::AwaitCertificate => "AwaitCertificate", + State::AwaitCertificateVerify => "AwaitCertificateVerify", + State::AwaitFinished => "AwaitFinished", + State::AwaitApplicationData => "AwaitApplicationData", + State::HalfClosedLocal => "HalfClosedLocal", + State::Closed => "Closed", + } + } + + fn make_progress(self, server: &mut Server) -> Result { + match self { + State::AwaitClientHello => self.await_client_hello(server), + State::SendServerHello => self.send_server_hello(server), + State::SendEncryptedExtensions => self.send_encrypted_extensions(server), + State::SendCertificateRequest => self.send_certificate_request(server), + State::SendCertificate => self.send_certificate(server), + State::SendCertificateVerify => self.send_certificate_verify(server), + State::SendFinished => self.send_finished(server), + State::AwaitCertificate => self.await_certificate(server), + State::AwaitCertificateVerify => self.await_certificate_verify(server), + State::AwaitFinished => self.await_finished(server), + State::AwaitApplicationData => self.await_application_data(server), + State::HalfClosedLocal => self.half_closed_local(server), + State::Closed => Ok(self), + } + } + + fn await_client_hello(self, server: &mut Server) -> Result { + // Save transcript length so we can roll back if a stale ClientHello + // arrives after HelloRetryRequest (no cookie → must discard). + let transcript_len_before = server.engine.transcript.len(); + + let maybe = if server.auto_mode { + server + .engine + .next_client_hello_for_auto_sense(&mut server.defragment_buffer)? + } else { + server + .engine + .next_handshake(MessageType::ClientHello, &mut server.defragment_buffer)? + }; + + let Some(handshake) = maybe else { + return Ok(self); + }; + + let Body::ClientHello(ref client_hello) = handshake.body else { + unreachable!() + }; + + if !client_hello.legacy_cookie.is_empty() { + return Err(Error::SecurityError( + crate::SecurityError::InvalidLegacyCookieInClientHello, + ) + .into()); + } + + // Validate legacy_version + if client_hello.legacy_version != ProtocolVersion::DTLS1_2 { + return Err(Error::SecurityError( + crate::SecurityError::ClientHelloLegacyVersionNotDtls12, + ) + .into()); + } + + // Validate null compression is offered + let has_null_compression = client_hello + .legacy_compression_methods + .contains(&CompressionMethod::Null); + if !has_null_compression { + return Err(Error::SecurityError( + crate::SecurityError::ClientHelloMustOfferNullCompression, + ) + .into()); + } + + // Parse extensions + let mut supported_versions_ok = false; + let mut client_key_shares: Option< + ArrayVec<(NamedGroup, std::ops::Range), { NamedGroup::supported().len() }>, + > = None; + let mut client_supported_groups: Option> = None; + let mut client_srtp_profiles: Option> = + None; + let mut client_cookie_data: Option> = None; + + for ext in &client_hello.extensions { + match ext.extension_type { + ExtensionType::SupportedVersions => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let (_, sv) = SupportedVersionsClientHello::parse(ext_data) + .map_err(InternalError::from)?; + for v in &sv.versions { + if *v == ProtocolVersion::DTLS1_3 { + supported_versions_ok = true; + } + } + } + ExtensionType::KeyShare => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let ext_data_start = ext.extension_data_range.start; + let (_, ks) = KeyShareClientHello::parse(ext_data, ext_data_start) + .map_err(InternalError::from)?; + let mut entries = ArrayVec::new(); + for entry in &ks.entries { + entries + .try_push((entry.group, entry.key_exchange_range.clone())) + .map_err(|_| { + InternalError::parse(nom::error::ErrorKind::LengthValue) + })?; + } + client_key_shares = Some(entries); + } + ExtensionType::SupportedGroups => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let (_, sg) = + SupportedGroupsExtension::parse(ext_data).map_err(InternalError::from)?; + client_supported_groups = Some(sg.groups); + } + ExtensionType::SignatureAlgorithms => { + let ext_data = ext.extension_data(&server.defragment_buffer); + // Parse but we don't currently filter by signature algorithms + let _ = SignatureAlgorithmsExtension::parse(ext_data); + } + ExtensionType::UseSrtp => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let (_, use_srtp) = + UseSrtpExtension::parse(ext_data).map_err(InternalError::from)?; + client_srtp_profiles = Some(use_srtp.profiles); + } + ExtensionType::Cookie => { + let ext_data = ext.extension_data(&server.defragment_buffer); + let (_, cookie) = + parse_cookie_extension(ext_data).map_err(InternalError::from)?; + client_cookie_data = Some(ArrayVec::try_from(cookie).map_err(|_| { + Error::SecurityError(crate::SecurityError::InvalidCookieInClientHello) + })?); + } + _ => {} + } + } + + if !supported_versions_ok { + if server.auto_mode { + return Err((Error::Dtls12Fallback).into()); + } + return Err(Error::SecurityError( + crate::SecurityError::ClientHelloMissingDtls13SupportedVersions, + ) + .into()); + } + + // Select cipher suite: first from client's list that is in our provider + let selected_cipher_suite = client_hello + .cipher_suites + .iter() + .find(|cs| server.engine.is_cipher_suite_allowed(**cs)) + .copied() + .ok_or(Error::SecurityError( + crate::SecurityError::NoCommonCipherSuite, + ))?; + + // Save the client random and session_id early so HRR can use them + let client_random = client_hello.random; + server.client_session_id = Some(client_hello.legacy_session_id); + + // Cookie-based DoS protection + let need_cookie = server.engine.config().use_server_cookie(); + + // Pre-compute whether we also need a key_share group selection, so + // we can piggyback it on a cookie HRR (avoiding two sequential HRRs). + let our_groups: ArrayVec = server + .engine + .config() + .kx_groups() + .map(|g| g.name()) + .collect(); + let key_shares = client_key_shares + .as_ref() + .map(|v| v.as_slice()) + .unwrap_or(&[]); + let has_matching_key_share = key_shares + .iter() + .any(|(group, _)| our_groups.contains(group)); + + // Determine which group to request if key_share is missing + let hrr_group = if !has_matching_key_share { + let client_groups = client_supported_groups + .as_ref() + .map(|v| v.as_slice()) + .unwrap_or(&[]); + our_groups + .iter() + .find(|g| client_groups.contains(g)) + .copied() + } else { + None + }; + + if need_cookie { + let expected_cookie = compute_cookie( + &server.cookie_secret, + &client_random, + server.engine.config().crypto_provider().hmac_provider, + ); + + if let Some(ref cookie_bytes) = client_cookie_data { + // Validate the cookie + let is_valid: bool = cookie_bytes.as_slice().ct_eq(&expected_cookie).into(); + if !is_valid { + return Err(Error::SecurityError( + crate::SecurityError::InvalidCookieInClientHello, + ) + .into()); + } + debug!("Cookie validated successfully"); + } else { + // No cookie: send HelloRetryRequest with cookie + if server.hello_retry { + // Stale retransmission of the pre-HRR ClientHello. Roll back the + // transcript that next_handshake just appended and silently + // discard. The HRR flight will be retransmitted by the normal + // flight timeout mechanism if the client hasn't responded. + debug!("Discarding stale ClientHello retransmission after HRR"); + server.engine.transcript.resize(transcript_len_before, 0); + return Ok(Self::AwaitClientHello); + } + + debug!("No cookie in ClientHello; sending HelloRetryRequest"); + + // Build HRR as a special ServerHello with magic random + server.engine.set_cipher_suite(selected_cipher_suite); + // Replace transcript BEFORE sending HRR so only CH1 is hashed + // per RFC 8446 Section 4.4.1. + let transcript_len = server.engine.transcript.len(); + server + .engine + .replace_transcript_with_message_hash(transcript_len); + send_hello_retry_request( + server, + selected_cipher_suite, + &expected_cookie, + hrr_group, // also request key_share group if needed + )?; + + server.engine.advance_peer_handshake_seq(); + server.engine.reset_for_hello_retry(); + server.hello_retry = true; + + return Ok(Self::AwaitClientHello); + } + } else if let Some(ref cookie_bytes) = client_cookie_data { + // Validate if a cookie was provided even when not required + let expected_cookie = compute_cookie( + &server.cookie_secret, + &client_random, + server.engine.config().crypto_provider().hmac_provider, + ); + let is_valid: bool = cookie_bytes.as_slice().ct_eq(&expected_cookie).into(); + if !is_valid { + return Err((Error::SecurityError( + crate::SecurityError::InvalidCookieInClientHello, + )) + .into()); + } + } + + // Select key exchange: find first client key_share with a group we support + let key_shares = client_key_shares.unwrap_or_default(); + let matching_entry = key_shares + .iter() + .find(|(group, _)| our_groups.contains(group)); + + let (selected_group, peer_key_range) = if let Some((group, range)) = matching_entry { + (*group, range.clone()) + } else { + // No matching key_share, but check supported_groups for a common group + let client_groups = client_supported_groups.unwrap_or_default(); + let common_group = our_groups + .iter() + .find(|g| client_groups.contains(g)) + .copied(); + + return if let Some(group) = common_group { + // Need HRR for key exchange + if server.hello_retry { + return Err(Error::SecurityError( + crate::SecurityError::CannotSendSecondHelloRetryRequest, + ) + .into()); + } + + debug!( + "No matching key_share; sending HelloRetryRequest for group {:?}", + group + ); + + server.engine.set_cipher_suite(selected_cipher_suite); + // Replace transcript BEFORE sending HRR so only CH1 is hashed + // per RFC 8446 Section 4.4.1. + let transcript_len = server.engine.transcript.len(); + server + .engine + .replace_transcript_with_message_hash(transcript_len); + let cookie_for_hrr = compute_cookie( + &server.cookie_secret, + &client_random, + server.engine.config().crypto_provider().hmac_provider, + ); + send_hello_retry_request( + server, + selected_cipher_suite, + &cookie_for_hrr, + Some(group), + )?; + + server.engine.advance_peer_handshake_seq(); + server.engine.reset_for_hello_retry(); + server.hello_retry = true; + + Ok(Self::AwaitClientHello) + } else { + Err(Error::SecurityError(crate::SecurityError::NoCommonKeyExchangeGroup).into()) + }; + }; + + // Start ECDHE key exchange + let kx_group = server + .engine + .find_kx_group(selected_group) + .ok_or(Error::CryptoError( + crate::CryptoError::KeyExchangeGroupNotFound(selected_group), + ))?; + + let kx_buf = server.engine.pop_buffer(); + let key_exchange = kx_group + .start_exchange(kx_buf) + .map_err(Error::CryptoError)?; + + // Store server's public key in extension_data + server.extension_data.clear(); + let pub_key = key_exchange.pub_key(); + let pub_key_start = server.extension_data.len(); + server.extension_data.extend_from_slice(pub_key); + let pub_key_end = server.extension_data.len(); + + // Complete ECDHE with client's public key + let peer_pub_key = &server.defragment_buffer[peer_key_range]; + let mut shared_secret = server.engine.pop_buffer(); + key_exchange + .complete(peer_pub_key, &mut shared_secret) + .map_err(Error::CryptoError)?; + + server.shared_secret = Some(shared_secret); + + // Select SRTP profile: first from client list that the server supports. + // Per RFC 5764 Section 4.1.1, the server MUST select a profile that + // both sides support. + if let Some(ref profiles) = client_srtp_profiles { + for profile_id in profiles { + let profile: SrtpProfile = (*profile_id).into(); + if SrtpProfile::ALL.contains(&profile) { + server.negotiated_srtp_profile = Some(profile); + break; + } + } + } + + // Store selected group and public key range for ServerHello + // already completed + server.active_key_exchange = None; + + // Save selected cipher suite and key data for SendServerHello + server.engine.set_cipher_suite(selected_cipher_suite); + + // Store the selected group and pub key range in a way SendServerHello can access. + // We encode them into extension_data: first the group as 2 bytes, then the start/end + // Actually, we already wrote the pub key above. We'll store selected_group separately. + // Re-use extension_data: [pub_key_bytes...] at indices pub_key_start..pub_key_end. + // We'll pass this info through the state transition. + // For simplicity, store group and range in the Buf after pub_key: + server + .extension_data + .extend_from_slice(&selected_group.as_u16().to_be_bytes()); + server + .extension_data + .extend_from_slice(&(pub_key_start as u32).to_be_bytes()); + server + .extension_data + .extend_from_slice(&(pub_key_end as u32).to_be_bytes()); + + drop(handshake); + + server.engine.advance_peer_handshake_seq(); + + debug!( + "ClientHello processed: cipher_suite={:?}, group={:?}", + selected_cipher_suite, selected_group + ); + + Ok(Self::SendServerHello) + } + + fn send_server_hello(self, server: &mut Server) -> Result { + // unwrap: is ok because we set the random in handle_timeout + let random = server.random.unwrap(); + + // Extract stored data from extension_data + let ext_data_len = server.extension_data.len(); + // Last 10 bytes: group(2) + start(4) + end(4) + let meta_start = ext_data_len - 10; + let group_bytes = [ + server.extension_data[meta_start], + server.extension_data[meta_start + 1], + ]; + let selected_group = NamedGroup::from_u16(u16::from_be_bytes(group_bytes)); + let pub_key_start = u32::from_be_bytes([ + server.extension_data[meta_start + 2], + server.extension_data[meta_start + 3], + server.extension_data[meta_start + 4], + server.extension_data[meta_start + 5], + ]) as usize; + let pub_key_end = u32::from_be_bytes([ + server.extension_data[meta_start + 6], + server.extension_data[meta_start + 7], + server.extension_data[meta_start + 8], + server.extension_data[meta_start + 9], + ]) as usize; + + // Truncate the metadata we appended + server.extension_data.resize(meta_start, 0); + + let client_session_id = SessionId::empty(); + + server.engine.flight_begin(2); + + server + .engine + .create_handshake(MessageType::ServerHello, |body, engine| { + handshake_create_server_hello( + body, + engine, + random, + client_session_id, + selected_group, + pub_key_start..pub_key_end, + &server.extension_data, + ) + })?; + + // Derive handshake secrets + let shared_secret = server.shared_secret.take().ok_or(Error::InvalidState( + crate::InvalidStateError::NoSharedSecretForHandshakeKeyDerivation, + ))?; + + let (c_hs_traffic, s_hs_traffic, handshake_secret) = + server.engine.derive_handshake_secrets(&shared_secret)?; + + // Save handshake secret for later application key derivation + server.handshake_secret = Some(handshake_secret); + server.engine.push_buffer(shared_secret); + + // Save traffic secrets + let mut s_hs_copy = Buf::new(); + s_hs_copy.extend_from_slice(&s_hs_traffic); + server.server_hs_traffic_secret = Some(s_hs_copy); + let mut c_hs_copy = Buf::new(); + c_hs_copy.extend_from_slice(&c_hs_traffic); + server.client_hs_traffic_secret = Some(c_hs_copy); + + // Install handshake keys + server + .engine + .install_handshake_keys(&c_hs_traffic, &s_hs_traffic)?; + + Ok(Self::SendEncryptedExtensions) + } + + fn send_encrypted_extensions(self, server: &mut Server) -> Result { + debug!("Sending EncryptedExtensions"); + + let negotiated_srtp = server.negotiated_srtp_profile; + + server + .engine + .create_handshake(MessageType::EncryptedExtensions, |body, _engine| { + handshake_create_encrypted_extensions(body, negotiated_srtp) + })?; + + if server.engine.config().require_client_certificate() { + Ok(Self::SendCertificateRequest) + } else { + Ok(Self::SendCertificate) + } + } + + fn send_certificate_request(self, server: &mut Server) -> Result { + debug!("Sending CertificateRequest"); + + server + .engine + .create_handshake(MessageType::CertificateRequest, |body, _engine| { + handshake_create_certificate_request(body) + })?; + + server.client_auth_requested = true; + + Ok(Self::SendCertificate) + } + + fn send_certificate(self, server: &mut Server) -> Result { + debug!("Sending Certificate"); + + server + .engine + .create_handshake(MessageType::Certificate, |body, engine| { + handshake_create_certificate(body, engine, &[]) + })?; + + Ok(Self::SendCertificateVerify) + } + + fn send_certificate_verify(self, server: &mut Server) -> Result { + debug!("Sending CertificateVerify"); + + server + .engine + .create_handshake(MessageType::CertificateVerify, |body, engine| { + handshake_create_certificate_verify( + body, + engine, + b"TLS 1.3, server CertificateVerify\0", + ) + })?; + + Ok(Self::SendFinished) + } + + fn send_finished(self, server: &mut Server) -> Result { + trace!("Sending server Finished message"); + + let server_hs_secret = + server + .server_hs_traffic_secret + .as_ref() + .ok_or(Error::InvalidState( + crate::InvalidStateError::NoServerHandshakeTrafficSecretForFinished, + ))?; + let mut server_hs_secret_copy = Buf::new(); + server_hs_secret_copy.extend_from_slice(server_hs_secret); + let server_hs_secret = server_hs_secret_copy; + + server + .engine + .create_handshake(MessageType::Finished, |body, engine| { + let verify_data = engine.compute_verify_data(&server_hs_secret)?; + body.extend_from_slice(&verify_data); + Ok(()) + })?; + + // Derive application secrets from handshake secret + transcript through server Finished + let handshake_secret = server.handshake_secret.as_ref().ok_or(Error::InvalidState( + crate::InvalidStateError::NoHandshakeSecretForApplicationKeyDerivation, + ))?; + + let (c_ap_traffic, s_ap_traffic) = + server.engine.derive_application_secrets(handshake_secret)?; + + // Install application keys + server + .engine + .install_application_keys(&c_ap_traffic, &s_ap_traffic)?; + + // Enable peer encryption so we can decrypt client's epoch 2 messages + server.engine.enable_peer_encryption()?; + + if server.client_auth_requested { + Ok(Self::AwaitCertificate) + } else { + Ok(Self::AwaitFinished) + } + } + + fn await_certificate(self, server: &mut Server) -> Result { + let maybe = server + .engine + .next_handshake(MessageType::Certificate, &mut server.defragment_buffer)?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + let Body::Certificate(ref certificate) = handshake.body else { + unreachable!() + }; + + if certificate.certificate_list.is_empty() { + debug!("Client sent empty certificate list"); + drop(maybe); + server.engine.advance_peer_handshake_seq(); + // Client's Certificate means our flight was received; stop retransmitting + server.engine.flight_stop_resend_timers(); + // Empty cert list is acceptable - proceed without client auth verification + return Ok(Self::AwaitFinished); + } + + debug!( + "Received client Certificate message with {} certificate(s)", + certificate.certificate_list.len() + ); + + // Extract certificate data before dropping handshake + let cert_ranges: ArrayVec<_, 32> = certificate + .certificate_list + .iter() + .map(|entry| entry.cert.as_slice(&server.defragment_buffer).to_vec()) + .collect(); + + drop(maybe); + + for (i, cert_data) in cert_ranges.iter().enumerate() { + trace!( + "Client certificate #{} size: {} bytes", + i + 1, + cert_data.len() + ); + let mut buf = Buf::new(); + buf.extend_from_slice(cert_data); + server.client_certificates.push(buf); + } + + // Emit PeerCert event + if !server.client_certificates.is_empty() { + server.local_events.push_back(LocalEvent::PeerCert); + } + + // Client's Certificate means our flight was received; stop retransmitting + server.engine.flight_stop_resend_timers(); + + server.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitCertificateVerify) + } + + fn await_certificate_verify(self, server: &mut Server) -> Result { + // Compute transcript hash BEFORE consuming CertificateVerify. + // Per RFC 8446 §4.4.3, the hash covers all messages up to but NOT + // including CertificateVerify. next_handshake() will append CV to + // the transcript, so we must capture the hash first. + let mut transcript_hash = Buf::new(); + server.engine.transcript_hash(&mut transcript_hash); + + let maybe = server.engine.next_handshake( + MessageType::CertificateVerify, + &mut server.defragment_buffer, + )?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + let Body::CertificateVerify(ref cv) = handshake.body else { + unreachable!() + }; + + let scheme = cv.signed.scheme; + let signature = cv.signed.signature(&server.defragment_buffer); + + // RFC 8446 §4.4.3: The signature algorithm MUST be one offered in + // the signature_algorithms field of the CertificateRequest message. + if !SignatureScheme::supported().contains(&scheme) { + return Err( + Error::SecurityError(crate::SecurityError::SignatureSchemeNotOffered(scheme)) + .into(), + ); + } + + // Build the signed content per RFC 8446 Section 4.4.3: + // 0x20 * 64 || "TLS 1.3, client CertificateVerify\0" || transcript_hash + let mut signed_content = Buf::new(); + signed_content.extend_from_slice(&[0x20u8; 64]); + signed_content.extend_from_slice(b"TLS 1.3, client CertificateVerify\0"); + signed_content.extend_from_slice(&transcript_hash); + + // Copy signature data since we need to drop handshake reference + let mut signature_copy = ArrayVec::::new(); + signature_copy + .try_extend_from_slice(signature) + .map_err(|_| Error::SecurityError(crate::SecurityError::SignatureTooLarge))?; + + drop(maybe); + + // Verify the signature + let cert_der = server + .client_certificates + .first() + .ok_or(Error::CertificateError( + crate::CertificateError::NoClientCertificateForVerification, + ))?; + + #[cfg(feature = "_crypto-common")] + verify_scheme_curve(scheme, cert_der)?; + + let (hash_alg, sig_alg) = signature_scheme_to_components(scheme)?; + + server.engine.verify_signature( + cert_der, + &signed_content, + &signature_copy, + hash_alg, + sig_alg, + )?; + + trace!("Client CertificateVerify verified: {:?}", scheme); + + server.engine.advance_peer_handshake_seq(); + Ok(Self::AwaitFinished) + } + + fn await_finished(self, server: &mut Server) -> Result { + // Compute expected verify_data BEFORE consuming Finished + // (verify_data uses transcript hash up to but not including Finished) + let client_hs_secret = + server + .client_hs_traffic_secret + .as_ref() + .ok_or(Error::InvalidState( + crate::InvalidStateError::NoClientHandshakeTrafficSecret, + ))?; + let expected_verify_data = server.engine.compute_verify_data(client_hs_secret)?; + + let maybe = server + .engine + .next_handshake(MessageType::Finished, &mut server.defragment_buffer)?; + + let Some(ref handshake) = maybe else { + return Ok(self); + }; + + let Body::Finished(ref finished) = handshake.body else { + unreachable!() + }; + + let verify_data = finished.verify_data(&server.defragment_buffer); + + trace!( + "Client Finished.verify_data received len={}, expected len={}", + verify_data.len(), + expected_verify_data.len() + ); + + // Constant-time comparison + let is_eq: bool = verify_data.ct_eq(&*expected_verify_data).into(); + if !is_eq { + return Err((Error::SecurityError( + crate::SecurityError::ClientFinishedVerificationFailed, + )) + .into()); + } + + trace!("Client Finished verified successfully"); + + drop(maybe); + + server.engine.advance_peer_handshake_seq(); + + // ACK the client's epoch-2 flight so it stops retransmitting + server.engine.send_ack_retransmittable()?; + + // Stop flight timers - handshake complete + server.engine.flight_stop_resend_timers(); + + // Emit Connected event + server.local_events.push_back(LocalEvent::Connected); + + // Extract and emit SRTP keying material if negotiated + if let Some(profile) = server.negotiated_srtp_profile { + if let Ok((keying_material, profile)) = + server.engine.extract_srtp_keying_material(profile) + { + debug!( + "SRTP keying material extracted ({} bytes) for profile: {:?}", + keying_material.len(), + profile + ); + server + .local_events + .push_back(LocalEvent::KeyingMaterial(keying_material, profile)); + } + } + + server + .engine + .release_application_data_retaining_handshake_keys(); + + debug!("Handshake complete; ready for application data"); + + Ok(Self::AwaitApplicationData) + } + + fn await_application_data(self, server: &mut Server) -> Result { + // Auto-trigger KeyUpdate when AEAD encryption limit is reached + if server.engine.needs_key_update() && !server.engine.is_key_update_in_flight() { + server.initiate_key_update()?; + } + + // Send queued application data + if !server.queued_data.is_empty() { + let epoch = server.engine.app_send_epoch(); + debug!( + "Sending queued application data: {}", + server.queued_data.len() + ); + for data in server.queued_data.drain(..) { + server.engine.create_ciphertext_record( + ContentType::ApplicationData, + epoch, + false, + |body| { + body.extend_from_slice(&data); + }, + )?; + } + } + + // Send pending KeyUpdate response before processing new KeyUpdates + if server.pending_key_update_response { + server + .engine + .create_key_update(KeyUpdateRequest::UpdateNotRequested)?; + server.pending_key_update_response = false; + } + + // Check for incoming KeyUpdate + if server.engine.has_complete_handshake(MessageType::KeyUpdate) { + let maybe = server.engine.next_handshake_no_transcript( + MessageType::KeyUpdate, + &mut server.defragment_buffer, + )?; + + if let Some(handshake) = maybe { + let Body::KeyUpdate(request) = handshake.body else { + unreachable!() + }; + + // Install new recv keys + server.engine.update_recv_keys()?; + + // ACK the KeyUpdate record + server.engine.send_ack()?; + + // If peer requested us to update, schedule our own KeyUpdate + if request == KeyUpdateRequest::UpdateRequested + && !server.engine.is_key_update_in_flight() + { + server.pending_key_update_response = true; + } + + server.engine.advance_peer_handshake_seq(); + debug!("Received KeyUpdate (request={:?})", request); + } + } + + Ok(self) + } + + fn half_closed_local(self, server: &mut Server) -> Result { + // Write half is closed: drain incoming KeyUpdate to keep recv keys in sync, + // but do not send our own KeyUpdate response. + if server.engine.has_complete_handshake(MessageType::KeyUpdate) { + let maybe = server.engine.next_handshake_no_transcript( + MessageType::KeyUpdate, + &mut server.defragment_buffer, + )?; + if let Some(handshake) = maybe { + let Body::KeyUpdate(_) = handshake.body else { + unreachable!() + }; + server.engine.update_recv_keys()?; + server.engine.advance_peer_handshake_seq(); + } + } + + if server.engine.close_notify_received() { + return Ok(State::Closed); + } + + Ok(self) + } +} + +// ========================================================================= +// Helper Functions +// ========================================================================= + +/// Compute a cookie for DoS protection using HMAC-SHA256. +/// +/// The cookie is HMAC-SHA256(cookie_secret, client_random.bytes), truncated to 32 bytes. +fn compute_cookie( + cookie_secret: &[u8; 32], + client_random: &Random, + hmac_provider: &'static dyn crate::crypto::HmacProvider, +) -> [u8; 32] { + // unwrap: HMAC-SHA256 should not fail with valid key/data + hmac_provider + .hmac_sha256(cookie_secret, &client_random.bytes) + .unwrap() +} + +/// Send a HelloRetryRequest (encoded as a ServerHello with magic random). +fn send_hello_retry_request( + server: &mut Server, + cipher_suite: Dtls13CipherSuite, + cookie: &[u8; 32], + selected_group: Option, +) -> Result<(), Error> { + let hrr_random = Random { bytes: HRR_RANDOM }; + let client_session_id = SessionId::empty(); + + server.engine.flight_begin(2); + + // Build extension data into a local buffer + let mut ext_buf = Buf::new(); + let mut extensions: ArrayVec = ArrayVec::new(); + + // 1. supported_versions extension (DTLS 1.3) + let sv_start = ext_buf.len(); + let sv = SupportedVersionsServerHello { + selected_version: ProtocolVersion::DTLS1_3, + }; + sv.serialize(&mut ext_buf); + let sv_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::SupportedVersions, + extension_data_range: sv_start..sv_end, + }); + + // 2. key_share extension (selected group for retry) if needed + if let Some(group) = selected_group { + let ks_start = ext_buf.len(); + let hrr_ks = KeyShareHelloRetryRequest { + selected_group: group, + }; + hrr_ks.serialize(&mut ext_buf); + let ks_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::KeyShare, + extension_data_range: ks_start..ks_end, + }); + } + + // 3. cookie extension + let cookie_start = ext_buf.len(); + // Cookie extension format: cookie<1..2^16-1> (u16-length-prefixed) + ext_buf.extend_from_slice(&(cookie.len() as u16).to_be_bytes()); + ext_buf.extend_from_slice(cookie); + let cookie_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::Cookie, + extension_data_range: cookie_start..cookie_end, + }); + + let server_hello = ServerHello::new( + ProtocolVersion::DTLS1_2, + hrr_random, + client_session_id, + cipher_suite, + CompressionMethod::Null, + Some(extensions), + ); + + server + .engine + .create_handshake(MessageType::ServerHello, |body, _engine| { + server_hello.serialize(&ext_buf, body); + Ok(()) + })?; + + Ok(()) +} + +fn handshake_create_server_hello( + body: &mut Buf, + engine: &mut Engine, + random: Random, + client_session_id: SessionId, + selected_group: NamedGroup, + pub_key_range: std::ops::Range, + extension_data: &Buf, +) -> Result<(), Error> { + // unwrap: cipher_suite is set by AwaitClientHello + let cipher_suite = engine.cipher_suite().unwrap(); + + // Build extensions + let mut ext_buf = Buf::new(); + let mut extensions: ArrayVec = ArrayVec::new(); + + // 1. supported_versions extension (DTLS 1.3) + let sv_start = ext_buf.len(); + let sv = SupportedVersionsServerHello { + selected_version: ProtocolVersion::DTLS1_3, + }; + sv.serialize(&mut ext_buf); + let sv_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::SupportedVersions, + extension_data_range: sv_start..sv_end, + }); + + // 2. key_share extension (server's public key) + let ks_start = ext_buf.len(); + let ks = KeyShareServerHello { + entry: KeyShareEntry { + group: selected_group, + key_exchange_range: pub_key_range, + }, + }; + ks.serialize(extension_data, &mut ext_buf); + let ks_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::KeyShare, + extension_data_range: ks_start..ks_end, + }); + + let server_hello = ServerHello::new( + ProtocolVersion::DTLS1_2, + random, + client_session_id, + cipher_suite, + CompressionMethod::Null, + Some(extensions), + ); + + server_hello.serialize(&ext_buf, body); + Ok(()) +} + +fn handshake_create_encrypted_extensions( + body: &mut Buf, + negotiated_srtp: Option, +) -> Result<(), Error> { + let mut ext_buf = Buf::new(); + let mut extensions: ArrayVec = ArrayVec::new(); + + // use_srtp extension if negotiated + if let Some(profile) = negotiated_srtp { + let srtp_start = ext_buf.len(); + let profile_id: crate::dtls13::message::SrtpProfileId = profile.into(); + let mut profiles = ArrayVec::new(); + profiles.push(profile_id); + let use_srtp = UseSrtpExtension::new(profiles, ArrayVec::new()); + use_srtp.serialize(&mut ext_buf); + let srtp_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::UseSrtp, + extension_data_range: srtp_start..srtp_end, + }); + } + + // Serialize EncryptedExtensions: extensions_len(2) + extensions + let mut extensions_len = 0usize; + for ext in &extensions { + let ext_data = ext.extension_data(&ext_buf); + extensions_len += 4 + ext_data.len(); + } + + body.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + for ext in &extensions { + ext.serialize(&ext_buf, body); + } + + Ok(()) +} + +fn handshake_create_certificate_request(body: &mut Buf) -> Result<(), Error> { + // CertificateRequest format (RFC 8446 Section 4.3.2): + // certificate_request_context<0..255> + body.push(0); // empty context + + // extensions<2..2^16-1> + let mut ext_buf = Buf::new(); + let mut extensions: ArrayVec = ArrayVec::new(); + + // signature_algorithms extension (required) + let sa_start = ext_buf.len(); + let sa = SignatureAlgorithmsExtension::default(); + sa.serialize(&mut ext_buf); + let sa_end = ext_buf.len(); + extensions.push(Extension { + extension_type: ExtensionType::SignatureAlgorithms, + extension_data_range: sa_start..sa_end, + }); + + // Calculate total extensions length + let mut extensions_len = 0usize; + for ext in &extensions { + let ext_data = ext.extension_data(&ext_buf); + extensions_len += 4 + ext_data.len(); + } + + body.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + for ext in &extensions { + ext.serialize(&ext_buf, body); + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn certificate_request_omits_empty_certificate_authorities() { + let mut body = Buf::new(); + handshake_create_certificate_request(&mut body).expect("create CertificateRequest"); + + assert_eq!(body[0], 0, "certificate_request_context"); + let ext_len = u16::from_be_bytes([body[1], body[2]]) as usize; + assert_eq!(body.len(), 3 + ext_len); + + let mut extension_types = Vec::new(); + let mut pos = 3; + while pos < body.len() { + assert!(pos + 4 <= body.len()); + let extension_type = + ExtensionType::from_u16(u16::from_be_bytes([body[pos], body[pos + 1]])); + let extension_data_len = u16::from_be_bytes([body[pos + 2], body[pos + 3]]) as usize; + pos += 4; + assert!(pos + extension_data_len <= body.len()); + + extension_types.push(extension_type); + pos += extension_data_len; + } + + assert!(extension_types.contains(&ExtensionType::SignatureAlgorithms)); + assert!(!extension_types.contains(&ExtensionType::CertificateAuthorities)); + } +} diff --git a/third_party/dimpl/src/error.rs b/third_party/dimpl/src/error.rs new file mode 100644 index 0000000..c22663f --- /dev/null +++ b/third_party/dimpl/src/error.rs @@ -0,0 +1,1339 @@ +//! Public error type returned by the high-level DTLS API. + +use std::fmt; + +use crate::dtls12::message::Dtls12CipherSuite; +use crate::types::CompressionMethod; +use crate::types::Dtls13CipherSuite; +use crate::types::HashAlgorithm; +use crate::types::NamedGroup; +use crate::types::ProtocolVersion; +use crate::types::SignatureAlgorithm; +use crate::types::SignatureScheme; + +pub(crate) fn bounded_error_len(len: usize) -> u16 { + len.min(u16::MAX as usize) as u16 +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +/// Errors returned by DTLS processing functions. +pub enum Error { + /// Unexpected DTLS message. + UnexpectedMessage(UnexpectedMessageError), + /// Local state was missing data required for the requested operation. + InvalidState(InvalidStateError), + /// Cryptographic operation failed. + CryptoError(CryptoError), + /// Certificate validation failed. + CertificateError(CertificateError), + /// Security policy violation. + SecurityError(SecurityError), + /// PSK (Pre-Shared Key) error. + PskError(PskError), + /// Incoming queue exceeded capacity. + ReceiveQueueFull, + /// Outgoing queue exceeded capacity. + TransmitQueueFull, + /// Missing fields when parsing ServerHello. + IncompleteServerHello, + /// Something timed out. + Timeout(TimeoutError), + /// Configuration error (e.g., invalid crypto provider). + ConfigError(ConfigError), + /// Peer attempted renegotiation (not supported). + RenegotiationAttempt, + /// Application data cannot be sent because the handshake is not yet complete. + /// + /// For auto-sense instances this means the version has not yet been + /// resolved. Callers should buffer the data and retry once the + /// handshake advances. + HandshakePending, + /// The connection has been closed (close_notify sent or received). + ConnectionClosed, + /// If we are in auto-sense mode for a server and we received too + /// many client hello fragments that haven't made a packet. + TooManyClientHelloFragments, + /// The DTLS 1.3 server received a ClientHello that does not offer + /// DTLS 1.3 in `supported_versions`. In auto-sense mode the caller + /// should fall back to a DTLS 1.2 server and replay the buffered + /// packets. + /// + /// This value should never be seen outside dimpl. It's an internal + /// value to communicate from dtls13/server.rs to lib.rs. + #[doc(hidden)] + Dtls12Fallback, +} + +/// Fine-grained reason for an [`Error::UnexpectedMessage`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum UnexpectedMessageError { + /// Auto-detection received a server response that was neither DTLS 1.2 nor DTLS 1.3. + UnrecognizedAutoServerResponse, + /// A DTLS 1.2 `ServerKeyExchange` omitted its required signature. + ServerKeyExchangeWithoutSignature, + /// A PSK `ServerKeyExchange` was received while processing an ECDHE suite. + PskServerKeyExchangeInEcdhePath, + /// An ECDHE `ServerKeyExchange` was received while processing a PSK suite. + EcdheServerKeyExchangeInPskPath, + /// A PSK `ClientKeyExchange` was received while processing an ECDHE suite. + PskClientKeyExchangeInEcdhePath, + /// An ECDHE `ClientKeyExchange` was received while processing a PSK suite. + EcdheClientKeyExchangeInPskPath, + /// A DTLS 1.3 `CertificateRequest` context was shorter than declared. + CertificateRequestContextTruncated, + /// A DTLS 1.3 `CertificateRequest` extension block was shorter than declared. + CertificateRequestExtensionsTruncated, +} + +/// Fine-grained reason for an [`Error::InvalidState`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum InvalidStateError { + /// No cipher suite has been selected for the connection. + NoCipherSuiteSelected, + /// A cipher suite was required but not available. + NoCipherSuite, + /// The client random was required but not available. + NoClientRandom, + /// The server random was required but not available. + NoServerRandom, + /// The handshake key schedule was used before a shared secret existed. + NoSharedSecretForHandshakeKeyDerivation, + /// The server handshake traffic secret was required but not available. + NoServerHandshakeTrafficSecret, + /// The server handshake traffic secret was required to verify or create `Finished`. + NoServerHandshakeTrafficSecretForFinished, + /// The client handshake traffic secret was required but not available. + NoClientHandshakeTrafficSecret, + /// The client handshake traffic secret was required to verify or create `Finished`. + NoClientHandshakeTrafficSecretForFinished, + /// Application traffic keys were requested before the handshake secret existed. + NoHandshakeSecretForApplicationKeyDerivation, + /// A key exchange was required but no exchange was active. + NoActiveKeyExchange, + /// A DTLS 1.3 key update was requested before current send keys existed. + NoCurrentAppSendKeysForKeyUpdate, + /// A DTLS 1.3 peer key update was processed before current receive keys existed. + NoCurrentAppRecvKeysForKeyUpdate, + /// Exported keying material was requested before the exporter secret was derived. + ExporterMasterSecretNotDerived, + /// Extended master secret was negotiated, but the session hash was not captured. + ExtendedMasterSecretSessionHashMissing, +} + +/// Fine-grained reason for an [`Error::CryptoError`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum CryptoError { + /// No supported key exchange group is available. + NoSupportedKeyExchangeGroups, + /// DTLS 1.2 needs a key exchange group but none is configured. + NoDtls12KeyExchangeGroupsConfigured, + /// The epoch 0 sequence number space has been exhausted. + Epoch0SequenceNumberExhausted, + /// The send sequence number space for an epoch has been exhausted. + SendSequenceNumberExhausted { + /// The epoch whose send sequence number was exhausted. + epoch: u16, + }, + /// Send keys are not available for an epoch. + SendKeysNotAvailable { + /// The epoch whose send keys are unavailable. + epoch: u16, + }, + /// Receive keys are not available for an epoch. + RecvKeysNotAvailable { + /// The epoch whose receive keys are unavailable. + epoch: u16, + }, + /// No provider key exchange group matches the negotiated group. + KeyExchangeGroupNotFound(NamedGroup), + /// A key exchange operation was requested before initialization. + KeyExchangeNotInitialized, + /// The requested key exchange group is unsupported. + UnsupportedKeyExchangeGroup(NamedGroup), + /// The requested ECDHE group is unsupported. + UnsupportedEcdheNamedGroup(NamedGroup), + /// The requested DTLS 1.2 cipher suite is unsupported. + UnsupportedCipherSuite(Dtls12CipherSuite), + /// The requested HMAC hash algorithm is unsupported. + UnsupportedHmacHash(HashAlgorithm), + /// The requested signature algorithm is unsupported. + UnsupportedSignatureAlgorithm(SignatureAlgorithm), + /// No locally supported signature algorithm was offered by the peer. + SignatureAlgorithmNotOfferedByClient, + /// The signature algorithm did not match the expected algorithm. + SignatureAlgorithmMismatch { + /// The signature algorithm expected for this operation. + expected: SignatureAlgorithm, + /// The signature algorithm actually present. + actual: SignatureAlgorithm, + }, + /// The signature and hash algorithm pair is unsupported. + UnsupportedSignaturePair { + /// The requested signature algorithm. + signature: SignatureAlgorithm, + /// The requested hash algorithm. + hash: HashAlgorithm, + }, + /// The signature, hash, and key group combination is unsupported for verification. + UnsupportedSignatureVerification { + /// The requested signature algorithm. + signature: SignatureAlgorithm, + /// The requested hash algorithm. + hash: HashAlgorithm, + /// The public key group used for verification. + group: NamedGroup, + }, + /// Signature verification failed for a supported signature/hash/group combination. + SignatureVerificationFailed { + /// The requested signature algorithm. + signature: SignatureAlgorithm, + /// The requested hash algorithm. + hash: HashAlgorithm, + /// The public key group used for verification. + group: NamedGroup, + }, + /// The public key algorithm is unsupported. + UnsupportedPublicKeyAlgorithm, + /// A certificate or key references an unsupported EC curve. + UnsupportedEcCurve, + /// Certificate parsing failed during a crypto operation. + CertificateParseFailed, + /// A certificate omitted its required EC curve parameter. + MissingEcCurveParameter, + /// A certificate had an invalid EC curve parameter. + InvalidEcCurveParameter, + /// A certificate had an invalid subject public key. + InvalidSubjectPublicKey, + /// A signature was not encoded in the expected format. + InvalidSignatureFormat, + /// A public key could not be parsed for the given group. + InvalidPublicKey(NamedGroup), + /// A private key could not be parsed in any supported format. + InvalidPrivateKey, + /// A signing key was used with a hash other than the one it is bound to. + SigningKeyHashMismatch { + /// The hash algorithm bound to the signing key. + key_hash: HashAlgorithm, + /// The hash algorithm requested by the caller. + requested: HashAlgorithm, + }, + /// A signing key group does not support the requested hash algorithm. + SigningKeyUnsupportedHash { + /// The key group used for signing. + group: NamedGroup, + /// The requested hash algorithm. + hash: HashAlgorithm, + }, + /// An AES-GCM key had the wrong length. + InvalidAesGcmKeySize { + /// The actual key length in bytes. + /// + /// Values greater than `u16::MAX` are reported as `u16::MAX`. + actual: u16, + }, + /// A ChaCha20-Poly1305 key had the wrong length. + InvalidChacha20Poly1305KeySize { + /// The actual key length in bytes. + /// + /// Values greater than `u16::MAX` are reported as `u16::MAX`. + actual: u16, + }, + /// An AES-128-CCM-8 key had the wrong length. + InvalidAes128Ccm8KeySize { + /// The actual key length in bytes. + /// + /// Values greater than `u16::MAX` are reported as `u16::MAX`. + actual: u16, + }, + /// A nonce was invalid for the selected cipher. + InvalidNonce, + /// A ciphertext was shorter than the selected AEAD permits. + CiphertextTooShort { + /// The minimum accepted ciphertext length in bytes. + minimum: u8, + /// The actual ciphertext length in bytes. + actual: u8, + }, + /// The requested HKDF output length is too large. + HkdfOutputTooLong, + /// The HKDF label is too long to encode. + HkdfLabelTooLong, + /// The HKDF context is too long to encode. + HkdfContextTooLong, + /// The HKDF-Expand-Label output length is too large to encode. + HkdfOutputLengthTooLarge, + /// The `Finished` verify-data length was invalid. + InvalidVerifyDataLength, + /// The `Finished` verify-data is too long to encode. + VerifyDataTooLong, + /// The TLS 1.2 master secret is too long to encode. + MasterSecretTooLong, + /// The requested exported keying material is too long. + KeyingMaterialTooLong, + /// The TLS 1.2 pre-master secret is not available. + PreMasterSecretNotAvailable, + /// The TLS 1.2 master secret is not available. + MasterSecretNotAvailable, + /// The client random is not available. + ClientRandomNotAvailable, + /// The server random is not available. + ServerRandomNotAvailable, + /// The client cipher has not been initialized. + ClientCipherNotInitialized, + /// The server cipher has not been initialized. + ServerCipherNotInitialized, + /// A write IV is not available for the requested side. + WriteIvNotAvailable { + /// Whether the missing write IV is for the client side. + is_client: bool, + }, + /// The DTLS 1.2 record IV length is unsupported for the selected suite. + UnsupportedDtls12RecordIvLen { + /// The unsupported record IV length. + /// + /// Values greater than `u16::MAX` are reported as `u16::MAX`. + len: u16, + /// The selected DTLS 1.2 cipher suite. + suite: Dtls12CipherSuite, + }, + /// No private key is configured. + NoPrivateKeyConfigured, + /// A PSK operation was requested before a PSK was set. + PskNotSet, + /// The exporter master secret is not available. + ExporterMasterSecretNotDerived, + /// A provider operation failed without a more specific reason. + OperationFailed(CryptoOperation), +} + +/// A cryptographic operation that can fail. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum CryptoOperation { + /// Create an AEAD cipher instance. + CreateCipher, + /// Encrypt plaintext. + Encrypt, + /// Decrypt ciphertext. + Decrypt, + /// Sign a transcript or payload. + Sign, + /// Verify a signature. + VerifySignature, + /// Load a private key. + LoadPrivateKey, + /// Start a key exchange. + StartKeyExchange, + /// Complete a key exchange. + CompleteKeyExchange, + /// Generate an ephemeral key. + GenerateEphemeralKey, + /// Compute a public key. + ComputePublicKey, + /// Fill a buffer with random bytes. + FillRandom, + /// Compute an HMAC. + ComputeHmac, + /// Run the TLS 1.2 PRF. + Prf, + /// Run HKDF-Extract. + HkdfExtract, + /// Run HKDF-Expand. + HkdfExpand, + /// Run TLS HKDF-Expand-Label. + HkdfExpandLabel, + /// Derive a DTLS 1.3 early secret. + DeriveEarlySecret, + /// Derive a DTLS 1.3 derived secret. + DeriveDerivedSecret, + /// Derive a DTLS 1.3 handshake secret. + DeriveHandshakeSecret, + /// Derive a DTLS 1.3 traffic secret. + DeriveTrafficSecret, + /// Derive a DTLS 1.3 master secret. + DeriveMasterSecret, + /// Derive a DTLS 1.3 exporter master secret. + DeriveExporterMasterSecret, + /// Derive a DTLS 1.3 next-generation traffic secret. + DeriveNextTrafficSecret, + /// Derive an AEAD key. + DeriveKey, + /// Derive an AEAD IV. + DeriveIv, + /// Derive a record sequence-number encryption key. + DeriveSequenceNumberKey, + /// Derive a Finished-message key. + DeriveFinishedKey, + /// Compute Finished verify data. + ComputeVerifyData, + /// Verify Finished verify data. + VerifyData, + /// Compute a PSK pre-master secret. + ComputePskPreMasterSecret, + /// Compute a DTLS cookie. + ComputeCookie, + /// Extract SRTP keying material. + ExtractSrtpKeyingMaterial, + /// Encode a key. + EncodeKey, + /// Decode a key. + DecodeKey, +} + +/// Fine-grained reason for an [`Error::CertificateError`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum CertificateError { + /// The peer did not send a server certificate. + NoServerCertificateReceived, + /// Client certificate verification was requested with no client certificate. + NoClientCertificateForVerification, + /// Server certificate verification was requested with no server certificate. + NoServerCertificateForVerification, + /// A DTLS 1.3 server certificate carried a non-empty context. + ServerCertificateContextMustBeEmpty, + /// A DTLS 1.3 client certificate carried a non-empty context. + ClientCertificateContextMustBeEmpty, + /// The certificate operation needs an unsupported hash algorithm. + UnsupportedHashAlgorithm(HashAlgorithm), + /// Certificate parsing failed. + ParseFailed, + /// A certificate omitted its EC curve parameter. + MissingEcCurveParameter, + /// A certificate had an invalid EC curve parameter. + InvalidEcCurveParameter, + /// A certificate references an unsupported EC curve. + UnsupportedEcCurve, + /// A certificate had an invalid subject public key. + InvalidSubjectPublicKey, +} + +/// Fine-grained reason for an [`Error::SecurityError`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum SecurityError { + /// `HelloVerifyRequest` used an unsupported protocol version. + UnsupportedHelloVerifyRequestVersion(ProtocolVersion), + /// A server selected an unsupported protocol version. + UnsupportedServerVersion(ProtocolVersion), + /// A client offered an unsupported protocol version. + UnsupportedClientVersion(ProtocolVersion), + /// A server selected an unsupported DTLS 1.2 compression method. + UnsupportedServerCompression(CompressionMethod), + /// A client did not offer null compression. + UnsupportedClientCompression, + /// The selected key exchange algorithm is unsupported. + UnsupportedKeyExchangeAlgorithm, + /// The server selected a cipher suite that was not offered or recognized. + ServerSelectedUnknownCipherSuite, + /// The server selected a DTLS 1.2 cipher suite incompatible with local mode. + ServerSelectedIncompatibleCipherSuite(Dtls12CipherSuite), + /// The server selected a DTLS 1.2 cipher suite disallowed by configuration. + ServerSelectedDisallowedCipherSuite(Dtls12CipherSuite), + /// The server selected a DTLS 1.3 cipher suite disallowed by configuration. + ServerSelectedDisallowedDtls13CipherSuite(Dtls13CipherSuite), + /// DTLS 1.2 extended master secret was required but not negotiated. + ExtendedMasterSecretNotNegotiated, + /// No mutually acceptable cipher suite was found. + NoMutuallyAcceptableCipherSuite, + /// A DTLS 1.3 ClientHello did not use the required DTLS 1.2 legacy version. + ClientHelloLegacyVersionNotDtls12, + /// A DTLS 1.3 ServerHello did not use the required DTLS 1.2 legacy version. + ServerHelloLegacyVersionNotDtls12, + /// A DTLS 1.3 ClientHello did not contain a recognized DTLS 1.3 version. + ClientHelloMissingDtls13SupportedVersions, + /// A ClientHello did not offer null compression. + ClientHelloMustOfferNullCompression, + /// The ClientHello cookie did not match the expected cookie. + InvalidCookieInClientHello, + /// A DTLS 1.3 ClientHello carried a non-empty legacy_cookie field. + InvalidLegacyCookieInClientHello, + /// The server attempted to send a second HelloRetryRequest. + CannotSendSecondHelloRetryRequest, + /// The client received a second HelloRetryRequest. + UnexpectedSecondHelloRetryRequest, + /// No common DTLS 1.3 cipher suite was found. + NoCommonCipherSuite, + /// No common DTLS 1.3 key exchange group was found. + NoCommonKeyExchangeGroup, + /// A HelloRetryRequest selected a disallowed cipher suite. + HrrSelectedDisallowedCipherSuite, + /// A HelloRetryRequest did not select DTLS 1.3. + HrrDidNotSelectDtls13, + /// A ServerHello selected a non-null compression method. + ServerHelloCompressionMustBeNull, + /// A server did not negotiate DTLS 1.3. + ServerDidNotNegotiateDtls13, + /// A DTLS 1.3 server did not send a key share. + ServerMissingKeyShare, + /// The server key share group did not match the expected group. + ServerKeyShareGroupMismatch { + /// The expected key exchange group. + expected: NamedGroup, + /// The key exchange group in the server key share. + actual: NamedGroup, + }, + /// A signature was too large to encode. + SignatureTooLarge, + /// A signature scheme was used even though the peer did not offer it. + SignatureSchemeNotOffered(SignatureScheme), + /// A signature algorithm did not match the expected algorithm. + SignatureAlgorithmMismatch { + /// The expected signature algorithm. + expected: SignatureAlgorithm, + /// The actual signature algorithm. + actual: SignatureAlgorithm, + }, + /// The signature scheme is unsupported. + UnsupportedSignatureScheme(SignatureScheme), + /// The signature scheme and certificate curve are incompatible. + SignatureSchemeCertificateCurveMismatch { + /// The signature scheme used for the operation. + scheme: SignatureScheme, + /// The certificate curve required by the signature scheme. + expected: NamedGroup, + /// The actual certificate curve. + actual: NamedGroup, + }, + /// Server Finished verification failed. + ServerFinishedVerificationFailed, + /// Client Finished verification failed. + ClientFinishedVerificationFailed, + /// A fatal DTLS alert was received. + FatalAlert { + /// The DTLS alert description. + description: u8, + }, +} + +/// Fine-grained reason for an [`Error::PskError`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum PskError { + /// No PSK resolver is configured. + NoPskResolverConfigured, + /// No PSK identity is configured. + NoPskIdentityConfigured, + /// The configured PSK resolver did not return a key. + ResolverReturnedNoKey, +} + +/// Fine-grained reason for an [`Error::Timeout`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum TimeoutError { + /// Timeout while waiting for an auto client hybrid ClientHello to resolve. + HybridClientHello, + /// Timeout while connecting. + Connect, + /// Timeout while handshaking. + Handshake, +} + +/// Fine-grained reason for an [`Error::ConfigError`]. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum ConfigError { + /// The configured MTU is smaller than dimpl permits. + MtuTooSmall { + /// The configured MTU. + mtu: u16, + /// The minimum accepted MTU. + minimum: u16, + }, + /// The configured AEAD encryption limit is too small. + AeadEncryptionLimitTooSmall, + /// Cipher-suite filtering removed every available suite. + NoCipherSuitesAfterFiltering, + /// A PSK resolver is configured but no PSK cipher suite remains enabled. + PskConfiguredWithoutPskCipherSuite, + /// DTLS 1.2 suites are enabled but no compatible key exchange group remains enabled. + NoDtls12KeyExchangeGroupsAfterFiltering, + /// DTLS 1.3 suites are enabled but no key exchange group remains enabled. + NoDtls13KeyExchangeGroupsAfterFiltering, + /// Crypto provider validation failed. + CryptoProvider(CryptoProviderValidationError), +} + +/// Fine-grained reason for crypto provider validation failure. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum CryptoProviderValidationError { + /// The provider has no cipher suites supported by dimpl. + NoCipherSuites, + /// The provider has ECDH cipher suites but no key exchange groups. + EcdhCipherSuitesWithoutKeyExchangeGroups, + /// The provider has no DTLS 1.3 cipher suites. + NoDtls13CipherSuites, + /// No hash test vector exists for the hash algorithm. + MissingHashTestVector(HashAlgorithm), + /// The provider hash implementation returned an unexpected value. + HashProviderIncorrect(HashAlgorithm), + /// The provider PRF operation failed. + PrfFailed { + /// The hash algorithm used by the PRF. + hash: HashAlgorithm, + /// The underlying crypto failure. + source: CryptoError, + }, + /// No PRF test vector exists for the hash algorithm. + MissingPrfTestVector(HashAlgorithm), + /// The provider PRF returned incorrect output. + PrfIncorrect(HashAlgorithm), + /// No signature-validation vector exists for the algorithm pair. + NoSignatureValidationVector { + /// The hash algorithm used by the vector. + hash: HashAlgorithm, + /// The signature algorithm used by the vector. + signature: SignatureAlgorithm, + }, + /// Provider signature verification failed. + SignatureVerificationFailed { + /// The hash algorithm used for verification. + hash: HashAlgorithm, + /// The signature algorithm used for verification. + signature: SignatureAlgorithm, + /// The underlying crypto failure. + source: CryptoError, + }, + /// Provider HKDF validation failed. + HkdfFailed { + /// The DTLS 1.3 cipher suite under validation. + suite: Dtls13CipherSuite, + /// The underlying crypto failure. + source: CryptoError, + }, + /// Provider HKDF returned empty output. + HkdfEmptyOutput(Dtls13CipherSuite), + /// No AEAD test vector exists for the suite. + NoAeadTestVector(Dtls13CipherSuite), + /// Creating the AEAD cipher failed. + AeadCreateFailed { + /// The DTLS 1.3 cipher suite under validation. + suite: Dtls13CipherSuite, + /// The underlying crypto failure. + source: CryptoError, + }, + /// AEAD encryption failed. + AeadEncryptFailed { + /// The DTLS 1.3 cipher suite under validation. + suite: Dtls13CipherSuite, + /// The underlying crypto failure. + source: CryptoError, + }, + /// AEAD encryption returned the wrong output. + AeadEncryptWrongOutput(Dtls13CipherSuite), + /// AEAD decryption failed. + AeadDecryptFailed { + /// The DTLS 1.3 cipher suite under validation. + suite: Dtls13CipherSuite, + /// The underlying crypto failure. + source: CryptoError, + }, + /// AEAD decryption returned the wrong output. + AeadDecryptWrongOutput(Dtls13CipherSuite), + /// No record-number-encryption vector exists for the suite. + NoRecordNumberEncryptionTestVector(Dtls13CipherSuite), + /// Record-number encryption returned the wrong mask. + RecordNumberEncryptionWrongMask(Dtls13CipherSuite), + /// Starting key exchange failed. + KeyExchangeStartFailed { + /// The key exchange group under validation. + group: NamedGroup, + /// The underlying crypto failure. + source: CryptoError, + }, + /// Completing key exchange failed. + KeyExchangeCompleteFailed { + /// The key exchange group under validation. + group: NamedGroup, + /// The underlying crypto failure. + source: CryptoError, + }, + /// Two sides of a validation key exchange produced different shared secrets. + KeyExchangeMismatchedSharedSecret(NamedGroup), + /// HMAC validation failed. + HmacFailed(CryptoError), + /// HMAC validation returned incorrect output. + HmacIncorrect, +} + +#[derive(Debug)] +pub(crate) enum InternalError { + Transient(TransientError), + Fatal(Error), +} + +#[derive(Debug)] +pub(crate) enum TransientError { + ParseIncomplete, + Parse(nom::error::ErrorKind), + TooManyRecords, +} + +impl InternalError { + pub(crate) fn parse_incomplete() -> Self { + Self::Transient(TransientError::ParseIncomplete) + } + + pub(crate) fn parse(kind: nom::error::ErrorKind) -> Self { + Self::Transient(TransientError::Parse(kind)) + } + + pub(crate) fn too_many_records() -> Self { + Self::Transient(TransientError::TooManyRecords) + } + + pub(crate) fn into_public_error(self) -> Option { + match self { + Self::Transient(err) => { + debug!("Discarding packet: {err}"); + None + } + Self::Fatal(err) => Some(err), + } + } +} + +impl From for InternalError { + fn from(value: Error) -> Self { + Self::Fatal(value) + } +} + +impl<'a> From>> for InternalError { + fn from(value: nom::Err>) -> Self { + match value { + nom::Err::Incomplete(_) => InternalError::parse_incomplete(), + nom::Err::Error(x) => InternalError::parse(x.code), + nom::Err::Failure(x) => InternalError::parse(x.code), + } + } +} + +impl From for Error { + fn from(value: CryptoError) -> Self { + Self::CryptoError(value) + } +} + +impl From for Error { + fn from(value: CertificateError) -> Self { + Self::CertificateError(value) + } +} + +impl From for Error { + fn from(value: SecurityError) -> Self { + Self::SecurityError(value) + } +} + +impl From for Error { + fn from(value: PskError) -> Self { + Self::PskError(value) + } +} + +impl From for Error { + fn from(value: ConfigError) -> Self { + Self::ConfigError(value) + } +} + +impl std::error::Error for Error {} + +impl fmt::Display for InternalError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + InternalError::Transient(err) => err.fmt(f), + InternalError::Fatal(err) => err.fmt(f), + } + } +} + +impl fmt::Display for TransientError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TransientError::ParseIncomplete => write!(f, "parse incomplete"), + TransientError::Parse(kind) => write!(f, "parse error: {:?}", kind), + TransientError::TooManyRecords => write!(f, "too many records in packet"), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::UnexpectedMessage(err) => write!(f, "unexpected message: {err}"), + Error::InvalidState(err) => write!(f, "invalid state: {err}"), + Error::CryptoError(err) => write!(f, "crypto error: {err}"), + Error::CertificateError(err) => write!(f, "certificate error: {err}"), + Error::SecurityError(err) => write!(f, "security error: {err}"), + Error::PskError(err) => write!(f, "psk error: {err}"), + Error::ReceiveQueueFull => write!(f, "receive queue full"), + Error::TransmitQueueFull => write!(f, "transmit queue full"), + Error::IncompleteServerHello => write!(f, "incomplete ServerHello"), + Error::Timeout(err) => write!(f, "timeout: {err}"), + Error::ConfigError(err) => write!(f, "config error: {err}"), + Error::RenegotiationAttempt => write!(f, "peer attempted renegotiation"), + Error::HandshakePending => { + write!(f, "handshake pending: cannot send application data yet") + } + Error::TooManyClientHelloFragments => write!(f, "too many client hello fragments"), + Error::ConnectionClosed => write!(f, "connection closed"), + Error::Dtls12Fallback => write!(f, "dtls 1.2 fallback (internal)"), + } + } +} + +impl fmt::Display for UnexpectedMessageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnrecognizedAutoServerResponse => write!(f, "unrecognized response from server"), + Self::ServerKeyExchangeWithoutSignature => { + write!(f, "ServerKeyExchange without signature") + } + Self::PskServerKeyExchangeInEcdhePath => { + write!(f, "PSK ServerKeyExchange in ECDHE path") + } + Self::EcdheServerKeyExchangeInPskPath => { + write!(f, "ECDHE ServerKeyExchange in PSK path") + } + Self::PskClientKeyExchangeInEcdhePath => { + write!(f, "PSK ClientKeyExchange in ECDHE path") + } + Self::EcdheClientKeyExchangeInPskPath => { + write!(f, "ECDHE ClientKeyExchange in PSK path") + } + Self::CertificateRequestContextTruncated => { + write!(f, "CertificateRequest context truncated") + } + Self::CertificateRequestExtensionsTruncated => { + write!(f, "CertificateRequest extensions truncated") + } + } + } +} + +impl fmt::Display for InvalidStateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoCipherSuiteSelected => write!(f, "no cipher suite selected"), + Self::NoCipherSuite => write!(f, "no cipher suite"), + Self::NoClientRandom => write!(f, "no client random"), + Self::NoServerRandom => write!(f, "no server random"), + Self::NoSharedSecretForHandshakeKeyDerivation => { + write!(f, "no shared secret for handshake key derivation") + } + Self::NoServerHandshakeTrafficSecret => { + write!(f, "no server handshake traffic secret") + } + Self::NoServerHandshakeTrafficSecretForFinished => { + write!(f, "no server handshake traffic secret for Finished") + } + Self::NoClientHandshakeTrafficSecret => { + write!(f, "no client handshake traffic secret") + } + Self::NoClientHandshakeTrafficSecretForFinished => { + write!(f, "no client handshake traffic secret for Finished") + } + Self::NoHandshakeSecretForApplicationKeyDerivation => { + write!(f, "no handshake secret for application key derivation") + } + Self::NoActiveKeyExchange => write!(f, "no active key exchange"), + Self::NoCurrentAppSendKeysForKeyUpdate => { + write!(f, "no current app send keys for KeyUpdate") + } + Self::NoCurrentAppRecvKeysForKeyUpdate => { + write!(f, "no current app recv keys for KeyUpdate") + } + Self::ExporterMasterSecretNotDerived => { + write!(f, "exporter master secret not yet derived") + } + Self::ExtendedMasterSecretSessionHashMissing => { + write!( + f, + "extended master secret negotiated but session hash not captured" + ) + } + } + } +} + +impl fmt::Display for CryptoError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoSupportedKeyExchangeGroups => write!(f, "no supported key exchange groups"), + Self::NoDtls12KeyExchangeGroupsConfigured => { + write!(f, "no DTLS 1.2 key exchange groups configured") + } + Self::Epoch0SequenceNumberExhausted => { + write!(f, "epoch 0 sequence number exhausted") + } + Self::SendSequenceNumberExhausted { epoch } => { + write!(f, "send sequence number exhausted for epoch {epoch}") + } + Self::SendKeysNotAvailable { epoch } => { + write!(f, "send keys not available for epoch {epoch}") + } + Self::RecvKeysNotAvailable { epoch } => { + write!(f, "recv keys not available for epoch {epoch}") + } + Self::KeyExchangeGroupNotFound(group) => { + write!(f, "key exchange group not found: {group:?}") + } + Self::KeyExchangeNotInitialized => write!(f, "key exchange not initialized"), + Self::UnsupportedKeyExchangeGroup(group) => { + write!(f, "unsupported key exchange group: {group:?}") + } + Self::UnsupportedEcdheNamedGroup(group) => { + write!(f, "unsupported ECDHE named group: {group:?}") + } + Self::UnsupportedCipherSuite(suite) => { + write!(f, "unsupported cipher suite: {suite:?}") + } + Self::UnsupportedHmacHash(hash) => { + write!(f, "unsupported HMAC hash algorithm: {hash:?}") + } + Self::UnsupportedSignatureAlgorithm(sig) => { + write!(f, "unsupported signature algorithm: {sig:?}") + } + Self::SignatureAlgorithmNotOfferedByClient => { + write!(f, "signature algorithm not offered by client") + } + Self::SignatureAlgorithmMismatch { expected, actual } => { + write!( + f, + "signature algorithm mismatch: {actual:?} != {expected:?}" + ) + } + Self::UnsupportedSignaturePair { signature, hash } => { + write!(f, "unsupported signature algorithm: {signature:?}/{hash:?}") + } + Self::UnsupportedSignatureVerification { + signature, + hash, + group, + } => write!( + f, + "unsupported signature verification: {signature:?} + {hash:?} + {group:?}" + ), + Self::SignatureVerificationFailed { + signature, + hash, + group, + } => write!( + f, + "signature verification failed: {signature:?} + {hash:?} + {group:?}" + ), + Self::UnsupportedPublicKeyAlgorithm => write!(f, "unsupported public key algorithm"), + Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"), + Self::CertificateParseFailed => write!(f, "failed to parse certificate"), + Self::MissingEcCurveParameter => { + write!(f, "missing EC curve parameter in certificate") + } + Self::InvalidEcCurveParameter => { + write!(f, "invalid EC curve parameter in certificate") + } + Self::InvalidSubjectPublicKey => { + write!(f, "invalid EC subject_public_key bitstring") + } + Self::InvalidSignatureFormat => write!(f, "invalid signature format"), + Self::InvalidPublicKey(group) => write!(f, "invalid {group:?} public key"), + Self::InvalidPrivateKey => { + write!(f, "failed to parse private key in any supported format") + } + Self::SigningKeyHashMismatch { + key_hash, + requested, + } => write!( + f, + "signing key is locked to {key_hash:?} but {requested:?} was requested" + ), + Self::SigningKeyUnsupportedHash { group, hash } => { + write!(f, "{group:?} key does not support hash algorithm {hash:?}") + } + Self::InvalidAesGcmKeySize { actual } => { + write!(f, "invalid key size for AES-GCM: {actual}") + } + Self::InvalidChacha20Poly1305KeySize { actual } => { + write!(f, "invalid key size for CHACHA20-POLY1305: {actual}") + } + Self::InvalidAes128Ccm8KeySize { actual } => { + write!(f, "invalid key size for AES-128-CCM-8: {actual}") + } + Self::InvalidNonce => write!(f, "invalid nonce"), + Self::CiphertextTooShort { minimum, actual } => { + write!(f, "ciphertext too short: got {actual}, minimum {minimum}") + } + Self::HkdfOutputTooLong => write!(f, "HKDF output too long"), + Self::HkdfLabelTooLong => write!(f, "label too long for HKDF-Expand-Label"), + Self::HkdfContextTooLong => write!(f, "context too long for HKDF-Expand-Label"), + Self::HkdfOutputLengthTooLarge => { + write!(f, "output length too large for HKDF-Expand-Label") + } + Self::InvalidVerifyDataLength => write!(f, "invalid verify data length"), + Self::VerifyDataTooLong => write!(f, "verify data too long"), + Self::MasterSecretTooLong => write!(f, "master secret too long"), + Self::KeyingMaterialTooLong => write!(f, "keying material too long"), + Self::PreMasterSecretNotAvailable => write!(f, "pre-master secret not available"), + Self::MasterSecretNotAvailable => write!(f, "master secret not available"), + Self::ClientRandomNotAvailable => write!(f, "client random not available"), + Self::ServerRandomNotAvailable => write!(f, "server random not available"), + Self::ClientCipherNotInitialized => write!(f, "client cipher not initialized"), + Self::ServerCipherNotInitialized => write!(f, "server cipher not initialized"), + Self::WriteIvNotAvailable { is_client } => { + let side = if *is_client { "client" } else { "server" }; + write!(f, "{side} write IV not available") + } + Self::UnsupportedDtls12RecordIvLen { len, suite } => { + write!(f, "unsupported DTLS 1.2 record_iv_len={len} for {suite:?}") + } + Self::NoPrivateKeyConfigured => write!(f, "no private key configured"), + Self::PskNotSet => write!(f, "PSK not set"), + Self::ExporterMasterSecretNotDerived => { + write!(f, "exporter master secret not yet derived") + } + Self::OperationFailed(op) => write!(f, "{op} failed"), + } + } +} + +impl fmt::Display for CryptoOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let text = match self { + Self::CreateCipher => "cipher creation", + Self::Encrypt => "encryption", + Self::Decrypt => "decryption", + Self::Sign => "signing", + Self::VerifySignature => "signature verification", + Self::LoadPrivateKey => "private key loading", + Self::StartKeyExchange => "key exchange start", + Self::CompleteKeyExchange => "key exchange completion", + Self::GenerateEphemeralKey => "ephemeral key generation", + Self::ComputePublicKey => "public key computation", + Self::FillRandom => "random generation", + Self::ComputeHmac => "HMAC computation", + Self::Prf => "PRF", + Self::HkdfExtract => "HKDF extract", + Self::HkdfExpand => "HKDF expand", + Self::HkdfExpandLabel => "HKDF expand label", + Self::DeriveEarlySecret => "early secret derivation", + Self::DeriveDerivedSecret => "derived secret derivation", + Self::DeriveHandshakeSecret => "handshake secret derivation", + Self::DeriveTrafficSecret => "traffic secret derivation", + Self::DeriveMasterSecret => "master secret derivation", + Self::DeriveExporterMasterSecret => "exporter master secret derivation", + Self::DeriveNextTrafficSecret => "next traffic secret derivation", + Self::DeriveKey => "key derivation", + Self::DeriveIv => "IV derivation", + Self::DeriveSequenceNumberKey => "sequence number key derivation", + Self::DeriveFinishedKey => "Finished key derivation", + Self::ComputeVerifyData => "verify data computation", + Self::VerifyData => "verify data verification", + Self::ComputePskPreMasterSecret => "PSK pre-master secret computation", + Self::ComputeCookie => "cookie computation", + Self::ExtractSrtpKeyingMaterial => "SRTP keying material extraction", + Self::EncodeKey => "key encoding", + Self::DecodeKey => "key decoding", + }; + write!(f, "{text}") + } +} + +impl fmt::Display for CertificateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoServerCertificateReceived => write!(f, "no server certificate received"), + Self::NoClientCertificateForVerification => { + write!(f, "no client certificate for verification") + } + Self::NoServerCertificateForVerification => { + write!(f, "no server certificate for verification") + } + Self::ServerCertificateContextMustBeEmpty => { + write!(f, "server certificate context must be empty") + } + Self::ClientCertificateContextMustBeEmpty => { + write!(f, "client certificate context must be empty") + } + Self::UnsupportedHashAlgorithm(hash) => { + write!(f, "unsupported hash algorithm: {hash:?}") + } + Self::ParseFailed => write!(f, "failed to parse certificate"), + Self::MissingEcCurveParameter => { + write!(f, "missing EC curve parameter in certificate") + } + Self::InvalidEcCurveParameter => { + write!(f, "invalid EC curve parameter in certificate") + } + Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"), + Self::InvalidSubjectPublicKey => { + write!(f, "invalid EC subject_public_key bitstring") + } + } + } +} + +impl fmt::Display for SecurityError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnsupportedHelloVerifyRequestVersion(version) => { + write!( + f, + "unsupported DTLS version in HelloVerifyRequest: {version:?}" + ) + } + Self::UnsupportedServerVersion(version) => { + write!(f, "unsupported DTLS version from server: {version:?}") + } + Self::UnsupportedClientVersion(version) => { + write!(f, "unsupported DTLS version from client: {version:?}") + } + Self::UnsupportedServerCompression(compression) => { + write!( + f, + "unsupported compression method from server: {compression:?}" + ) + } + Self::UnsupportedClientCompression => { + write!(f, "client did not offer null compression") + } + Self::UnsupportedKeyExchangeAlgorithm => { + write!(f, "unsupported key exchange algorithm") + } + Self::ServerSelectedUnknownCipherSuite => { + write!(f, "server selected unknown cipher suite") + } + Self::ServerSelectedIncompatibleCipherSuite(suite) => { + write!(f, "server selected incompatible cipher suite: {suite:?}") + } + Self::ServerSelectedDisallowedCipherSuite(suite) => { + write!(f, "server selected disallowed cipher suite: {suite:?}") + } + Self::ServerSelectedDisallowedDtls13CipherSuite(suite) => { + write!(f, "server selected disallowed cipher suite: {suite:?}") + } + Self::ExtendedMasterSecretNotNegotiated => { + write!(f, "extended master secret not negotiated") + } + Self::NoMutuallyAcceptableCipherSuite => { + write!(f, "no mutually acceptable cipher suite") + } + Self::ClientHelloLegacyVersionNotDtls12 => { + write!(f, "ClientHello legacy_version must be DTLS 1.2") + } + Self::ServerHelloLegacyVersionNotDtls12 => { + write!(f, "ServerHello legacy_version must be DTLS 1.2") + } + Self::ClientHelloMissingDtls13SupportedVersions => { + write!(f, "ClientHello missing DTLS 1.3 supported_versions") + } + Self::ClientHelloMustOfferNullCompression => { + write!(f, "ClientHello must offer null compression") + } + Self::InvalidCookieInClientHello => write!(f, "invalid cookie in ClientHello"), + Self::InvalidLegacyCookieInClientHello => { + write!(f, "ClientHello legacy_cookie must be empty") + } + Self::CannotSendSecondHelloRetryRequest => { + write!(f, "cannot send second HelloRetryRequest") + } + Self::UnexpectedSecondHelloRetryRequest => { + write!(f, "received second HelloRetryRequest") + } + Self::NoCommonCipherSuite => write!(f, "no common cipher suite found"), + Self::NoCommonKeyExchangeGroup => write!(f, "no common key exchange group"), + Self::HrrSelectedDisallowedCipherSuite => { + write!(f, "HRR selected disallowed cipher suite") + } + Self::HrrDidNotSelectDtls13 => write!(f, "HRR did not select DTLS 1.3"), + Self::ServerHelloCompressionMustBeNull => { + write!(f, "ServerHello compression must be null") + } + Self::ServerDidNotNegotiateDtls13 => { + write!(f, "server did not negotiate DTLS 1.3") + } + Self::ServerMissingKeyShare => write!(f, "server missing key_share"), + Self::ServerKeyShareGroupMismatch { expected, actual } => { + write!( + f, + "server key_share group mismatch: expected {expected:?}, actual {actual:?}" + ) + } + Self::SignatureTooLarge => write!(f, "signature too large"), + Self::SignatureSchemeNotOffered(scheme) => { + write!(f, "signature scheme {scheme:?} was not offered") + } + Self::SignatureAlgorithmMismatch { expected, actual } => { + write!( + f, + "signature algorithm mismatch: expected {expected:?}, got {actual:?}" + ) + } + Self::UnsupportedSignatureScheme(scheme) => { + write!(f, "unsupported signature scheme: {scheme:?}") + } + Self::SignatureSchemeCertificateCurveMismatch { + scheme, + expected, + actual, + } => write!( + f, + "signature scheme {scheme:?} requires {expected:?} but certificate uses {actual:?}" + ), + Self::ServerFinishedVerificationFailed => { + write!(f, "server Finished verification failed") + } + Self::ClientFinishedVerificationFailed => { + write!(f, "client Finished verification failed") + } + Self::FatalAlert { description } => { + write!(f, "received fatal alert: description={description}") + } + } + } +} + +impl fmt::Display for PskError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoPskResolverConfigured => write!(f, "no PSK resolver configured"), + Self::NoPskIdentityConfigured => write!(f, "no PSK identity configured"), + Self::ResolverReturnedNoKey => write!(f, "PSK resolver returned no key"), + } + } +} + +impl fmt::Display for TimeoutError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::HybridClientHello => write!(f, "hybrid ClientHello"), + Self::Connect => write!(f, "connect"), + Self::Handshake => write!(f, "handshake"), + } + } +} + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MtuTooSmall { mtu, minimum } => { + write!(f, "MTU {mtu} is too small (minimum {minimum})") + } + Self::AeadEncryptionLimitTooSmall => { + write!(f, "aead_encryption_limit must be at least 1") + } + Self::NoCipherSuitesAfterFiltering => write!( + f, + concat!( + "no cipher suites remain after filtering; at least one DTLS 1.2 or ", + "DTLS 1.3 cipher suite must be available" + ) + ), + Self::PskConfiguredWithoutPskCipherSuite => write!( + f, + "PSK is configured but no PSK cipher suite remains after filtering DTLS 1.2 suites" + ), + Self::NoDtls12KeyExchangeGroupsAfterFiltering => write!( + f, + concat!( + "DTLS 1.2 cipher suites are enabled but no compatible key exchange ", + "groups remain after filtering" + ) + ), + Self::NoDtls13KeyExchangeGroupsAfterFiltering => write!( + f, + "DTLS 1.3 cipher suites are enabled but no key exchange groups remain after filtering" + ), + Self::CryptoProvider(err) => write!(f, "crypto provider validation failed: {err}"), + } + } +} + +impl fmt::Display for CryptoProviderValidationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoCipherSuites => { + write!(f, "CryptoProvider has no cipher suites supported by dimpl") + } + Self::EcdhCipherSuitesWithoutKeyExchangeGroups => write!( + f, + "CryptoProvider has ECDH cipher suites but no supported key exchange groups" + ), + Self::NoDtls13CipherSuites => { + write!(f, "CryptoProvider has no DTLS 1.3 cipher suites") + } + Self::MissingHashTestVector(hash) => { + write!(f, "no expected hash data for hash algorithm: {hash:?}") + } + Self::HashProviderIncorrect(hash) => { + write!(f, "hash provider {hash:?} produced incorrect result") + } + Self::PrfFailed { hash, source } => write!(f, "PRF failed for {hash:?}: {source}"), + Self::MissingPrfTestVector(hash) => { + write!(f, "no expected PRF data for hash algorithm: {hash:?}") + } + Self::PrfIncorrect(hash) => write!(f, "PRF {hash:?} produced incorrect result"), + Self::NoSignatureValidationVector { hash, signature } => { + write!(f, "no validation test vectors for {hash:?} + {signature:?}") + } + Self::SignatureVerificationFailed { + hash, + signature, + source, + } => write!( + f, + "signature verification failed for {hash:?} + {signature:?}: {source}" + ), + Self::HkdfFailed { suite, source } => { + write!(f, "HKDF failed for DTLS 1.3 suite {suite:?}: {source}") + } + Self::HkdfEmptyOutput(suite) => { + write!(f, "HKDF returned empty output for {suite:?}") + } + Self::NoAeadTestVector(suite) => { + write!(f, "no AEAD test vector for DTLS 1.3 suite {suite:?}") + } + Self::AeadCreateFailed { suite, source } => { + write!(f, "failed to create cipher for {suite:?}: {source}") + } + Self::AeadEncryptFailed { suite, source } => { + write!(f, "AEAD encrypt failed for {suite:?}: {source}") + } + Self::AeadEncryptWrongOutput(suite) => { + write!(f, "AEAD encrypt produced wrong output for {suite:?}") + } + Self::AeadDecryptFailed { suite, source } => { + write!(f, "AEAD decrypt failed for {suite:?}: {source}") + } + Self::AeadDecryptWrongOutput(suite) => { + write!(f, "AEAD decrypt produced wrong output for {suite:?}") + } + Self::NoRecordNumberEncryptionTestVector(suite) => { + write!(f, "no encrypt_sn test vector for DTLS 1.3 suite {suite:?}") + } + Self::RecordNumberEncryptionWrongMask(suite) => { + write!(f, "encrypt_sn produced wrong mask for {suite:?}") + } + Self::KeyExchangeStartFailed { group, source } => { + write!(f, "key exchange start failed for {group:?}: {source}") + } + Self::KeyExchangeCompleteFailed { group, source } => { + write!(f, "key exchange complete failed for {group:?}: {source}") + } + Self::KeyExchangeMismatchedSharedSecret(group) => { + write!(f, "key exchange produced different secrets for {group:?}") + } + Self::HmacFailed(source) => write!(f, "HMAC provider failed: {source}"), + Self::HmacIncorrect => { + write!(f, "HMAC provider produced incorrect result for HMAC-SHA256") + } + } + } +} diff --git a/third_party/dimpl/src/lib.rs b/third_party/dimpl/src/lib.rs new file mode 100644 index 0000000..8356df1 --- /dev/null +++ b/third_party/dimpl/src/lib.rs @@ -0,0 +1,1548 @@ +//! dimpl — DTLS 1.2 and 1.3 implementation (Sans‑IO, Sync) +//! +//! dimpl is a DTLS 1.2 and 1.3 implementation aimed at WebRTC. It is a Sans‑IO +//! state machine you embed into your own UDP/RTC event loop: you feed incoming +//! datagrams, poll for outgoing records or timers, and wire up certificate +//! verification and SRTP key export yourself. +//! +//! # Goals +//! - **DTLS 1.2 and 1.3**: Implements the DTLS handshake and record layer used by WebRTC. +//! - **Safety**: `forbid(unsafe_code)` throughout the crate. +//! - **Minimal Rust‑only deps**: Uses small, well‑maintained Rust crypto crates. +//! - **Low overhead**: Tight control over allocations and buffers; Sans‑IO integration. +//! +//! ## Non‑goals +//! - **DTLS 1.0** +//! - **Async** (the crate is Sans‑IO and event‑loop agnostic) +//! - **no_std** (at least not without allocation) +//! - **RSA** +//! - **DHE** +//! +//! ## Version selection +//! +//! Four constructors control which DTLS version is used: +//! - [`Dtls::new_12`][new_12] — explicit DTLS 1.2 (certificate‑based) +//! - [`Dtls::new_12_psk`][new_12_psk] — explicit DTLS 1.2 (PSK, no certificates) +//! - [`Dtls::new_13`][new_13] — explicit DTLS 1.3 +//! - [`Dtls::new_auto`][new_auto] — auto‑sense: the first +//! incoming ClientHello determines the version (based on the +//! `supported_versions` extension) +//! +//! # Cryptography surface +//! - **Cipher suites (TLS 1.2 over DTLS)** +//! - `ECDHE_ECDSA_AES256_GCM_SHA384` +//! - `ECDHE_ECDSA_AES128_GCM_SHA256` +//! - `ECDHE_ECDSA_CHACHA20_POLY1305_SHA256` +//! - **PSK cipher suites (TLS 1.2 over DTLS)** +//! - `PSK_AES128_CCM_8` +//! - **Cipher suites (TLS 1.3 over DTLS)** +//! - `TLS_AES_128_GCM_SHA256` +//! - `TLS_AES_256_GCM_SHA384` +//! - `TLS_CHACHA20_POLY1305_SHA256` +//! - **AEAD**: AES‑GCM 128/256, ChaCha20‑Poly1305 (no CBC/EtM modes). +//! - **Key exchange**: ECDHE (P‑256/P‑384), X25519 +//! - **Signatures**: ECDSA P‑256/SHA‑256, ECDSA P‑384/SHA‑384 +//! - **DTLS‑SRTP**: Exports keying material for `SRTP_AEAD_AES_256_GCM`, +//! `SRTP_AEAD_AES_128_GCM`, and `SRTP_AES128_CM_SHA1_80` ([RFC 5764], [RFC 7714]). +//! - **Extended Master Secret** ([RFC 7627]) is negotiated and enforced (DTLS 1.2). +//! +//! ## Certificate model +//! During the handshake the engine emits +//! [`Output::PeerCert`][peer_cert] with the peer's leaf +//! certificate (DER). The crate uses that certificate to verify DTLS +//! handshake messages, but it does not perform any PKI validation. Your +//! application is responsible for validating the peer certificate according to +//! your policy (fingerprint, chain building, name/EKU checks, pinning, etc.). +//! +//! ## Sans‑IO integration model +//! Drive the engine with three calls: +//! - [`Dtls::handle_packet`][handle_packet] — feed an entire +//! received UDP datagram. +//! - [`Dtls::poll_output`][poll_output] — drain pending output: +//! DTLS records, timers, events. +//! - [`Dtls::handle_timeout`][handle_timeout] — trigger +//! retransmissions/time‑based progress. +//! +//! The output is an [`Output`][output] enum with borrowed +//! references into your provided buffer: +//! - `Packet(&[u8])`: send on your UDP socket +//! - `BufferTooSmall { needed }`: resize the poll buffer and retry +//! - `Timeout(Instant)`: schedule a timer and call `handle_timeout` at/after it +//! - `Connected`: handshake complete +//! - `PeerCert(&[u8])`: peer leaf certificate (DER) — validate in your app +//! - `KeyingMaterial(KeyingMaterial, SrtpProfile)`: DTLS‑SRTP export +//! - `ApplicationData(&[u8])`: plaintext received from peer +//! - `CloseNotify`: peer sent a `close_notify` alert (graceful shutdown) +//! +//! # Error handling +//! +//! Every `Error` returned by the public API +//! ([`handle_packet`][handle_packet], [`handle_timeout`][handle_timeout], +//! `send_application_data`, and `close`) is **fatal**: the connection is no +//! longer usable and must be thrown away. The engine has no recoverable +//! error states, so the correct response is always to drop the `Dtls` +//! instance — and start a fresh handshake if you still need a connection. +//! +//! Transient, non‑fatal conditions inherent to running over an unreliable +//! transport — malformed datagrams, replayed or out‑of‑window records, and +//! other parser noise — are handled internally and never surface as an +//! `Error`. Such packets are discarded (logged at `debug!`) while the +//! connection keeps running. You therefore never need to distinguish +//! "retry" from "give up": a returned `Error` always means give up on this +//! connection. +//! +//! # Example (Sans‑IO loop) +//! +//! ```rust,no_run +//! # #[cfg(feature = "rcgen")] +//! # { +//! use std::sync::Arc; +//! use std::time::Instant; +//! +//! use dimpl::{certificate, Config, Dtls, Output}; +//! +//! // Stub I/O to keep the example focused on the state machine +//! enum Event { Udp(Vec), Timer(Instant) } +//! fn wait_next_event(_next_wake: Option) -> Event { Event::Udp(Vec::new()) } +//! fn send_udp(_bytes: &[u8]) {} +//! +//! fn example_event_loop(mut dtls: Dtls) -> Result<(), dimpl::Error> { +//! let mut next_wake: Option = None; +//! loop { +//! // Drain engine output until we have to wait for I/O or a timer +//! let mut out_buf = vec![0u8; 2048]; +//! loop { +//! match dtls.poll_output(&mut out_buf) { +//! Output::Packet(p) => send_udp(p), +//! Output::BufferTooSmall { needed } => { +//! out_buf.resize(needed, 0); +//! } +//! Output::Timeout(t) => { next_wake = Some(t); break; } +//! Output::Connected => { +//! // DTLS established — application may start sending +//! } +//! Output::PeerCert(_der) => { +//! // Inspect peer leaf certificate if desired +//! } +//! Output::KeyingMaterial(_km, _profile) => { +//! // Provide to SRTP stack +//! } +//! Output::ApplicationData(_data) => { +//! // Deliver plaintext to application +//! } +//! Output::CloseNotify => { +//! // Peer initiated graceful shutdown — leave the event loop +//! return Ok(()); +//! } +//! _ => {} +//! } +//! } +//! +//! // Block waiting for either UDP input or the scheduled timeout +//! match wait_next_event(next_wake) { +//! Event::Udp(pkt) => dtls.handle_packet(&pkt)?, +//! Event::Timer(now) => dtls.handle_timeout(now)?, +//! } +//! } +//! } +//! +//! fn mk_dtls_client() -> Dtls { +//! let cert = certificate::generate_self_signed_certificate().unwrap(); +//! let cfg = Arc::new(Config::default()); +//! let mut dtls = Dtls::new_12(cfg, cert, Instant::now()); +//! dtls.set_active(true); // client role +//! dtls +//! } +//! +//! // Putting it together +//! let dtls = mk_dtls_client(); +//! let _ = example_event_loop(dtls); +//! # } +//! ``` +//! +//! # Example (PSK client) +//! +//! ```rust,no_run +//! use std::sync::Arc; +//! use std::time::Instant; +//! +//! use dimpl::{Config, Dtls, PskResolver}; +//! +//! struct MyPsk; +//! +//! impl PskResolver for MyPsk { +//! fn resolve(&self, identity: &[u8]) -> Option> { +//! if identity == b"device-01" { +//! Some(b"shared-secret-key".to_vec()) +//! } else { +//! None +//! } +//! } +//! } +//! +//! let config = Arc::new( +//! Config::builder() +//! .with_psk_client(b"device-01".to_vec(), Arc::new(MyPsk)) +//! .build() +//! .unwrap(), +//! ); +//! +//! let mut dtls = Dtls::new_12_psk(config, Instant::now()); +//! dtls.set_active(true); // client role +//! ``` +//! +//! ### MSRV +//! Rust 1.85.0 +//! +//! ### Status +//! - Session resumption is not implemented (WebRTC does a full handshake on ICE restart). +//! - Renegotiation is not implemented (WebRTC does full restart). +//! +//! [new_12]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_12 +//! [new_12_psk]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_12_psk +//! [new_13]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_13 +//! [new_auto]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.new_auto +//! [peer_cert]: https://docs.rs/dimpl/latest/dimpl/enum.Output.html#variant.PeerCert +//! [handle_packet]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.handle_packet +//! [poll_output]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.poll_output +//! [handle_timeout]: https://docs.rs/dimpl/latest/dimpl/struct.Dtls.html#method.handle_timeout +//! [output]: https://docs.rs/dimpl/latest/dimpl/enum.Output.html +//! [RFC 5764]: https://www.rfc-editor.org/rfc/rfc5764 +//! [RFC 7714]: https://www.rfc-editor.org/rfc/rfc7714 +//! [RFC 7627]: https://www.rfc-editor.org/rfc/rfc7627 +//! +#![forbid(unsafe_code)] +#![warn(clippy::all)] +#![allow(unknown_lints)] +#![deny(missing_docs)] +#![deny(missing_debug_implementations)] + +#[macro_use] +extern crate log; + +use std::fmt; +use std::sync::Arc; +use std::time::Instant; + +// Shared types used by both DTLS versions +mod types; +pub use types::{ + CompressionMethod, ContentType, HashAlgorithm, NamedGroup, ProtocolVersion, Sequence, + SignatureAlgorithm, +}; + +// DTLS version-specific modules +mod dtls12; +mod dtls13; + +use dtls12::{Client as Client12, Server as Server12}; +use dtls13::{Client as Client13, Server as Server13}; + +use auto::ClientPending; + +mod auto; +mod time_tricks; + +pub(crate) mod buffer; +mod window; + +mod util; + +mod error; +pub(crate) use error::InternalError; +pub use error::{ + CertificateError, ConfigError, CryptoError, CryptoOperation, CryptoProviderValidationError, + Error, InvalidStateError, PskError, SecurityError, TimeoutError, UnexpectedMessageError, +}; + +mod config; +pub use config::{Config, ConfigBuilder, Psk, PskResolver}; + +#[cfg(feature = "rcgen")] +pub mod certificate; + +pub mod crypto; + +pub use crypto::{KeyingMaterial, SrtpProfile}; + +mod timer; + +mod rng; +pub(crate) use rng::SeededRng; + +/// Certificate and private key pair. +#[derive(Clone)] +pub struct DtlsCertificate { + /// Certificate in DER format. + pub certificate: Vec, + /// Private key in DER format. + pub private_key: Vec, +} + +impl fmt::Debug for DtlsCertificate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DtlsCertificate") + .field("certificate", &self.certificate.len()) + .field("private_key", &self.private_key.len()) + .finish() + } +} + +/// Sans-IO DTLS endpoint (client or server). +/// +/// New instances start in the **server role**. Call +/// [`set_active(true)`](Self::set_active) to switch to client before +/// the handshake begins. +/// +/// Drive the state machine with [`handle_packet`](Self::handle_packet), +/// [`poll_output`](Self::poll_output), and +/// [`handle_timeout`](Self::handle_timeout). +pub struct Dtls { + inner: Option, +} + +enum Inner { + Client12(Client12), + Server12(Server12), + Client13(Client13), + Server13(Server13), + ClientPending(ClientPending), +} + +fn is_dtls12_psk_only(config: &Config) -> bool { + if config.dtls13_cipher_suites().next().is_some() { + return false; + } + + let mut suites = config.dtls12_cipher_suites().map(|cs| cs.suite()); + suites + .next() + .is_some_and(|first| first.is_psk() && suites.all(|s| s.is_psk())) +} + +/// If `packet` is a Handshake record carrying a ClientHello, return the +/// inner handshake message bytes (msg_type + length + message_seq + +/// fragment_offset + fragment_length + body). Returns `None` for any +/// other content type, message type, or malformed framing. +/// +/// Shared by [`looks_like_client_hello`] (structural check only) and +/// [`client_hello_wants_psk`] (which inspects cipher suites further). +fn client_hello_handshake(packet: &[u8]) -> Option<&[u8]> { + // DTLS record header: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) = 13 + if packet.len() < 13 || packet[0] != 0x16 { + return None; + } + let record_len = u16::from_be_bytes([packet[11], packet[12]]) as usize; + let record_body = packet.get(13..13 + record_len)?; + + // Handshake header: msg_type(1) + length(3) + message_seq(2) + + // fragment_offset(3) + fragment_length(3) = 12 + if record_body.len() < 12 || record_body[0] != 0x01 { + return None; + } + Some(record_body) +} + +/// Lightweight structural test helper: does this packet look like a ClientHello? +/// +/// In addition to the record/handshake header check from +/// [`client_hello_handshake`], this validates wire-format integrity of +/// the handshake header (fragment fits inside the declared total length; +/// fragment bytes actually present in the record) and, for an +/// unfragmented CH, requires the declared length to be at least the +/// minimum a real DTLS 1.2 ClientHello can carry. A header-only fake +/// or a CH whose declared length cannot fit a valid 1.2 body fails the +/// check. +#[cfg(all(test, feature = "rcgen"))] +fn looks_like_client_hello(packet: &[u8]) -> bool { + let Some(record_body) = client_hello_handshake(packet) else { + return false; + }; + + // Handshake header (12 bytes already validated to be present): + // msg_type(1) + length(3) + message_seq(2) + fragment_offset(3) + fragment_length(3) + let length = ((record_body[1] as usize) << 16) + | ((record_body[2] as usize) << 8) + | record_body[3] as usize; + let frag_off = ((record_body[6] as usize) << 16) + | ((record_body[7] as usize) << 8) + | record_body[8] as usize; + let frag_len = ((record_body[9] as usize) << 16) + | ((record_body[10] as usize) << 8) + | record_body[11] as usize; + + // A non-first fragment alone is not enough to prove that the packet + // carries the start of a ClientHello body. + if frag_off != 0 { + return false; + } + + // Fragment must lie within the declared total CH length, and the + // declared fragment bytes must actually be present in the record. + if frag_len > length { + return false; + } + if 12usize.saturating_add(frag_len) > record_body.len() { + return false; + } + + // Minimum DTLS 1.2 ClientHello body: + // version(2) + random(32) + sid_len(1) + cookie_len(1) + + // cipher_suites_len(2) + compression_methods_len(1) + + // compression_method(1) = 40 bytes (with empty sid/cookie/suites). + // Use 41 to also require a single byte for at least one cipher suite + // half — anything below this cannot be a real CH. + const MIN_CH_BODY: usize = 41; + let is_unfragmented = frag_len == length; + if is_unfragmented && length < MIN_CH_BODY { + return false; + } + + true +} + +/// Peek at a buffered DTLS 1.2 ClientHello to decide whether the auto-sense +/// server fallback should construct a PSK-mode Server12. +/// +/// Walks the client's offered cipher suites in order and returns `true` iff +/// the first one allowed by `config` is a PSK suite. This mirrors the suite +/// selection inside `Server12` itself, so the chosen auth mode matches the +/// suite that `Server12` will pick once it reprocesses the ClientHello. +/// +/// Returns `false` if `packet` is not a ClientHello or if parsing fails — +/// a fragmented ClientHello (fragment_offset > 0) is skipped and the next +/// buffered packet is tried by the caller. +fn client_hello_wants_psk(packet: &[u8], config: &Config) -> bool { + use dtls12::message::Dtls12CipherSuite; + + let Some(record_body) = client_hello_handshake(packet) else { + return false; + }; + + let frag_off = + ((record_body[6] as u32) << 16) | ((record_body[7] as u32) << 8) | record_body[8] as u32; + if frag_off != 0 { + return false; + } + + let frag_len = ((record_body[9] as usize) << 16) + | ((record_body[10] as usize) << 8) + | record_body[11] as usize; + let Some(body) = record_body.get(12..12 + frag_len) else { + return false; + }; + + // ClientHello body: client_version(2) + random(32) + session_id(var) + + // cookie(var) + cipher_suites(var) + ... + let mut pos = 2 + 32; + let Some(&sid_len) = body.get(pos) else { + return false; + }; + pos += 1 + sid_len as usize; + let Some(&cookie_len) = body.get(pos) else { + return false; + }; + pos += 1 + cookie_len as usize; + if pos + 2 > body.len() { + return false; + } + let suites_len = u16::from_be_bytes([body[pos], body[pos + 1]]) as usize; + pos += 2; + if pos + suites_len > body.len() || suites_len % 2 != 0 { + return false; + } + + let allowed: Vec<_> = config.dtls12_cipher_suites().map(|cs| cs.suite()).collect(); + for chunk in body[pos..pos + suites_len].chunks_exact(2) { + let suite = Dtls12CipherSuite::from_u16(u16::from_be_bytes([chunk[0], chunk[1]])); + if allowed.contains(&suite) { + return suite.is_psk(); + } + } + false +} + +impl Dtls { + /// Create a new DTLS 1.2 instance in the server role. + /// + /// Call [`set_active(true)`](Self::set_active) to switch to client + /// before the handshake begins. The `now` parameter seeds the internal + /// time tracking for timeouts and retransmissions. + /// + /// During the handshake, the peer's leaf certificate is surfaced via + /// [`Output::PeerCert`]. It is up to the application to validate that + /// certificate according to its security policy. + pub fn new_12(config: Arc, certificate: DtlsCertificate, now: Instant) -> Self { + let inner = Inner::Server12(Server12::new(config, certificate, now)); + Dtls { inner: Some(inner) } + } + + /// Create a new DTLS 1.2 PSK-only instance (no certificate). + /// + /// Call [`set_active(true)`](Self::set_active) to switch to client + /// before the handshake begins. The `config` must have a + /// [`PskResolver`] configured, and for clients a PSK identity + /// via [`ConfigBuilder::with_psk_client`](ConfigBuilder). + /// + /// Panics if `config` has no PSK configured. Without PSK data the + /// PSK suite filter would leave zero negotiable suites, so failing + /// fast at construction is preferable to a late handshake error. + pub fn new_12_psk(config: Arc, now: Instant) -> Self { + assert!( + config.psk().is_some(), + "Dtls::new_12_psk requires a PSK configuration; \ + set one via ConfigBuilder::with_psk_client or with_psk_server" + ); + let inner = Inner::Server12(Server12::new_psk(config, now)); + Dtls { inner: Some(inner) } + } + + /// Create a new DTLS 1.3 instance in the server role. + /// + /// Call [`set_active(true)`](Self::set_active) to switch to client + /// before the handshake begins. + /// + /// During the handshake, the peer's leaf certificate is surfaced via + /// [`Output::PeerCert`]. It is up to the application to validate that + /// certificate according to its security policy. + pub fn new_13(config: Arc, certificate: DtlsCertificate, now: Instant) -> Self { + let inner = Inner::Server13(Server13::new(config, certificate, now)); + Dtls { inner: Some(inner) } + } + + /// Create a new DTLS instance that auto‑senses the version. + /// + /// **Server role** (default): starts as a DTLS 1.3 server. If the + /// peer's ClientHello does not offer DTLS 1.3 in `supported_versions`, + /// the server automatically falls back to DTLS 1.2. This handles + /// fragmented ClientHellos (e.g. with post-quantum key shares) + /// correctly because the DTLS 1.3 engine performs full reassembly + /// before inspecting extensions. + /// + /// **Client role** ([`set_active(true)`](Self::set_active)): the + /// instance sends a hybrid ClientHello compatible with both DTLS 1.2 + /// and 1.3 servers and forks into the correct handshake once the + /// server responds. If the configuration only enables PSK DTLS 1.2 + /// suites, `new_auto` delegates to the DTLS 1.2 PSK state machine. + pub fn new_auto(config: Arc, certificate: DtlsCertificate, now: Instant) -> Self { + let inner = if is_dtls12_psk_only(config.as_ref()) { + Inner::Server12(Server12::new_psk(config, now)) + } else { + Inner::Server13(Server13::new_auto(config, certificate, now)) + }; + Dtls { inner: Some(inner) } + } + + /// Returns the negotiated DTLS protocol version. + /// + /// Returns `None` for auto-sense instances that have not yet completed + /// version negotiation (i.e. still in a `Pending` state). + pub fn protocol_version(&self) -> Option { + match self.inner.as_ref()? { + Inner::Client12(_) | Inner::Server12(_) => Some(ProtocolVersion::DTLS1_2), + Inner::Client13(_) => Some(ProtocolVersion::DTLS1_3), + Inner::Server13(s) => { + // Still waiting for a complete ClientHello + if s.is_auto_mode() { + None + } else { + Some(ProtocolVersion::DTLS1_3) + } + } + Inner::ClientPending(_) => None, + } + } + + /// Return true while DTLS shutdown is in progress. + /// + /// This becomes true after local shutdown starts, or while a received + /// `close_notify` still needs to be reported by + /// [`poll_output`](Self::poll_output). Callers should continue polling + /// until this returns false or [`is_closed`](Self::is_closed) returns true. + /// + /// Pending auto-sense handshakes are neither closing nor closed. + pub fn is_closing(&self) -> bool { + let Some(inner) = self.inner.as_ref() else { + return false; + }; + + match inner { + Inner::Client12(client) => client.is_closing(), + Inner::Server12(server) => server.is_closing(), + Inner::Client13(client) => client.is_closing(), + Inner::Server13(server) => { + if server.is_auto_mode() { + false + } else { + server.is_closing() + } + } + Inner::ClientPending(_) => false, + } + } + + /// Return true once DTLS shutdown is terminal for the embedder. + /// + /// This only becomes true after no application data can be sent and no + /// close-related packets or events remain to be drained through + /// [`poll_output`](Self::poll_output). In particular, DTLS 1.2 can enter + /// its internal closed state before the queued `close_notify` packet has + /// been polled out; this method remains false until that output is drained. + /// + /// Pending auto-sense handshakes are neither closing nor closed. + pub fn is_closed(&self) -> bool { + let Some(inner) = self.inner.as_ref() else { + return false; + }; + + match inner { + Inner::Client12(client) => client.is_closed(), + Inner::Server12(server) => server.is_closed(), + Inner::Client13(client) => client.is_closed(), + Inner::Server13(server) => { + if server.is_auto_mode() { + false + } else { + server.is_closed() + } + } + Inner::ClientPending(_) => false, + } + } + + /// Return true if the instance is operating in the client role. + pub fn is_active(&self) -> bool { + matches!( + self.inner, + Some(Inner::Client12(_) | Inner::Client13(_) | Inner::ClientPending(_)) + ) + } + + /// Switch between server and client roles. + /// + /// Set `active` to true for client role, false for server role. + /// + /// When called on an auto‑sense instance ([`Dtls::new_auto`]) the + /// client sends a hybrid ClientHello compatible with both DTLS 1.2 + /// and 1.3. The version is determined from the server's first + /// response. + pub fn set_active(&mut self, active: bool) { + match (self.is_active(), active) { + (true, false) => { + let inner = self.inner.take().unwrap(); + match inner { + Inner::Client12(c) => { + self.inner = Some(Inner::Server12(c.into_server())); + } + Inner::Client13(c) => { + self.inner = Some(Inner::Server13(c.into_server())); + } + Inner::ClientPending(_) => { + panic!("cannot switch auto-sense client back to server: version unknown"); + } + _ => unreachable!(), + } + } + (false, true) => { + let inner = self.inner.take().unwrap(); + match inner { + Inner::Server12(s) => { + self.inner = Some(Inner::Client12(s.into_client())); + } + Inner::Server13(s) => { + if s.is_auto_mode() { + let (config, certificate, now, _) = s.into_parts(); + let cp = ClientPending::new(config, certificate, now) + .expect("failed to build hybrid ClientHello"); + self.inner = Some(Inner::ClientPending(cp)); + } else { + // Not auto mode, or already consumed — just convert + self.inner = Some(Inner::Client13(s.into_client())); + } + } + _ => unreachable!(), + } + } + _ => {} + } + } + + /// Process an incoming DTLS datagram. + pub fn handle_packet(&mut self, packet: &[u8]) -> Result<(), Error> { + // unwrap is ok. The inner is only Option to work around borrowing + // issues when doing auto-sensing of DTLS version. + let inner = self.inner.as_mut().unwrap(); + + // Auto-sense pending states handle the packet themselves + // (including replay to the newly created inner), so we + // must not fall through to the regular dispatch below. + if inner.is_pending() { + return self.handle_pending_auto(packet); + } + + match self.inner.as_mut().unwrap() { + Inner::Client12(client) => client.handle_packet(packet), + Inner::Server12(server) => server.handle_packet(packet), + Inner::Client13(client) => client.handle_packet(packet), + Inner::Server13(server) => server.handle_packet(packet), + Inner::ClientPending(_) => unreachable!(), + } + } + + fn handle_pending_auto(&mut self, packet: &[u8]) -> Result<(), Error> { + match self.inner.as_mut().unwrap() { + Inner::ClientPending(_) => self.handle_pending_auto_client(packet), + Inner::Server13(server) if server.is_auto_mode() => { + match server.handle_packet(packet) { + Ok(()) => Ok(()), + Err(Error::Dtls12Fallback) => { + // The 1.3 engine cleanly rejected a ClientHello + // that did not offer DTLS 1.3 in supported_versions. + self.handle_pending_auto_server() + } + Err(e) => Err(e), + } + } + _ => unreachable!(), + } + } + + fn handle_pending_auto_client(&mut self, packet: &[u8]) -> Result<(), Error> { + // Auto-sense client: resolve version on first server response + let version = auto::server_hello_version(packet); + + // Check version before taking inner — returning an error + // while inner is None would leave us unable to poll/timeout. + if matches!(version, auto::DetectedVersion::Unknown) { + return Err(Error::UnexpectedMessage( + crate::UnexpectedMessageError::UnrecognizedAutoServerResponse, + )); + } + + // unwrap: guarded by the matches! check above + let inner = self.inner.take().unwrap(); + let Inner::ClientPending(cp) = inner else { + unreachable!() + }; + let (hybrid, config, certificate, now) = cp.into_parts(); + match version { + auto::DetectedVersion::Dtls12 => { + let mut client12 = Client12::new_from_hybrid( + hybrid.random, + &hybrid.handshake_fragment, + config, + certificate, + now, + )?; + // Feed the HVR to Client12 — it enters + // AwaitHelloVerifyRequest and processes the cookie. + if let Err(e) = client12.handle_packet(packet) { + self.inner = Some(Inner::Client12(client12)); + return Err(e); + } + self.inner = Some(Inner::Client12(client12)); + Ok(()) + } + auto::DetectedVersion::Dtls13 => { + let mut client13 = Client13::new_from_hybrid(hybrid, config, certificate, now)?; + if let Err(e) = client13.handle_packet(packet) { + self.inner = Some(Inner::Client13(client13)); + return Err(e); + } + self.inner = Some(Inner::Client13(client13)); + Ok(()) + } + auto::DetectedVersion::Unknown => unreachable!(), + } + } + + /// Fall back from DTLS 1.3 auto-sense to a DTLS 1.2 server, replaying + /// all buffered packets from the Server13. + fn handle_pending_auto_server(&mut self) -> Result<(), Error> { + // Take buffered packets and last_now from the Server13 before replacing it. + + // unwrap: is ok, because we can only be here if the inner is a Server13. + let server = match self.inner.take().unwrap() { + Inner::Server13(server) => server, + _ => unreachable!(), + }; + + let (config, cert, now, buffered) = server.into_parts(); + + // A Server12 instance is either cert-auth or PSK-auth — the auth + // mode must be chosen before construction. Peek at the buffered + // ClientHello to see which cipher suite the server would pick, + // so PSK clients survive the fallback. + let use_psk = + config.psk().is_some() && buffered.iter().any(|p| client_hello_wants_psk(p, &config)); + + let mut server12 = if use_psk { + Server12::new_psk(config, now) + } else { + Server12::new(config, cert, now) + }; + server12.handle_timeout(now)?; + + self.inner = Some(Inner::Server12(server12)); + + for p in &buffered { + self.handle_packet(p)?; + } + Ok(()) + } + + /// Poll for pending output from the DTLS engine. + pub fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> Output<'a> { + match self.inner.as_mut().unwrap() { + Inner::Client12(client) => client.poll_output(buf), + Inner::Server12(server) => server.poll_output(buf), + Inner::Client13(client) => client.poll_output(buf), + Inner::Server13(server) => server.poll_output(buf), + Inner::ClientPending(cp) => cp.poll_output(buf), + } + } + + /// Handle time-based events such as retransmission timers. + pub fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> { + match self.inner.as_mut().unwrap() { + Inner::Client12(client) => client.handle_timeout(now), + Inner::Server12(server) => server.handle_timeout(now), + Inner::Client13(client) => client.handle_timeout(now), + Inner::Server13(server) => server.handle_timeout(now), + Inner::ClientPending(cp) => cp.handle_timeout(now), + } + } + + /// Send application data over the established DTLS session. + /// + /// Returns [`Error::HandshakePending`] if the DTLS version has not + /// yet been resolved (auto-sense pending). Callers should buffer + /// the data externally and retry after the handshake progresses. + pub fn send_application_data(&mut self, data: &[u8]) -> Result<(), Error> { + // unwrap is ok, we only have an Option to deal with pending auto. + let inner = self.inner.as_mut().unwrap(); + + if inner.is_pending() { + return Err(Error::HandshakePending); + } + + match inner { + Inner::Client12(client) => client.send_application_data(data), + Inner::Server12(server) => server.send_application_data(data), + Inner::Client13(client) => client.send_application_data(data), + Inner::Server13(server) => server.send_application_data(data), + Inner::ClientPending(_) => Err(Error::HandshakePending), + } + } + + /// Initiate graceful shutdown by sending a `close_notify` alert. + /// + /// **Connected** (`AwaitApplicationData`): queues a `close_notify` alert; + /// the next [`poll_output`](Self::poll_output) cycle yields it as + /// [`Output::Packet`]. + /// + /// **Handshake in progress**: aborts immediately without sending an + /// alert (no authenticated channel exists). Subsequent calls to + /// [`send_application_data`](Self::send_application_data) will return + /// an error. + /// + /// **Pending** (version not yet resolved): returns + /// [`Error::HandshakePending`]. Callers who want to discard a pending + /// connection can simply drop the [`Dtls`] value. + /// + /// The alert is not retransmitted (per RFC 6347 §4.2.7 / RFC 9147 §5.10). + pub fn close(&mut self) -> Result<(), Error> { + let inner = self.inner.as_mut().unwrap(); + + if inner.is_pending() { + return Err(Error::HandshakePending); + } + + match inner { + Inner::Client12(client) => client.close(), + Inner::Server12(server) => server.close(), + Inner::Client13(client) => client.close(), + Inner::Server13(server) => server.close(), + Inner::ClientPending(_) => Err(Error::HandshakePending), + } + } +} + +impl Inner { + fn is_pending(&self) -> bool { + match self { + Inner::Server13(v) => v.is_auto_mode(), + Inner::ClientPending(_) => true, + _ => false, + } + } +} + +impl fmt::Debug for Dtls { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (role, state) = match &self.inner { + Some(Inner::Client12(c)) => ("Client12", c.state_name()), + Some(Inner::Server12(s)) => ("Server12", s.state_name()), + Some(Inner::Client13(c)) => ("Client13", c.state_name()), + Some(Inner::Server13(s)) => ("Server13", s.state_name()), + Some(Inner::ClientPending(_)) => ("ClientPending", ""), + None => ("None", ""), + }; + f.debug_struct("Dtls") + .field("role", &role) + .field("state", &state) + .finish() + } +} + +/// Output events produced by the DTLS engine when polled. +#[non_exhaustive] +pub enum Output<'a> { + /// A DTLS record to transmit on the wire. + Packet(&'a [u8]), + /// The provided output buffer is too small for the next pending output. + /// + /// Retry [`Dtls::poll_output`] with a buffer of at least `needed` bytes. + /// The pending output is retained until it can be emitted. + BufferTooSmall { + /// Minimum buffer length required to emit the pending output. + needed: usize, + }, + /// Schedule a timer and call [`Dtls::handle_timeout`] at this instant. + /// + /// This is always the last variant returned by a poll cycle. + /// Internal state is only consistent after reaching `Timeout`. + Timeout(Instant), + /// The handshake completed and the connection is established. + Connected, + /// The peer's leaf certificate in DER encoding. + /// + /// Applications must validate this certificate independently (chain, + /// name/EKU checks, pinning, etc.). + PeerCert(&'a [u8]), + /// Extracted DTLS-SRTP keying material and selected SRTP profile. + KeyingMaterial(KeyingMaterial, SrtpProfile), + /// Received application data plaintext. + ApplicationData(&'a [u8]), + /// The peer sent a `close_notify` alert, indicating graceful connection closure. + CloseNotify, +} + +impl fmt::Debug for Output<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Packet(v) => write!(f, "Packet({})", v.len()), + Self::BufferTooSmall { needed } => write!(f, "BufferTooSmall({needed})"), + Self::Timeout(v) => write!(f, "Timeout({:?})", v), + Self::Connected => write!(f, "Connected"), + Self::PeerCert(v) => write!(f, "PeerCert({})", v.len()), + Self::KeyingMaterial(v, p) => write!(f, "KeyingMaterial({}, {:?})", v.len(), p), + Self::ApplicationData(v) => write!(f, "ApplicationData({})", v.len()), + Self::CloseNotify => write!(f, "CloseNotify"), + } + } +} + +#[cfg(test)] +#[cfg(feature = "rcgen")] +mod test { + use std::panic::UnwindSafe; + + use crate::certificate::generate_self_signed_certificate; + use crate::crypto::Dtls12CipherSuite; + + use super::*; + + struct FixedPsk; + + impl PskResolver for FixedPsk { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"0123456789abcdef".to_vec()) + } + } + + fn new_instance() -> Dtls { + let client_cert = + generate_self_signed_certificate().expect("Failed to generate client cert"); + let config = Arc::new(Config::default()); + Dtls::new_12(config, client_cert, Instant::now()) + } + + fn new_instance_12_no_cookie() -> Dtls { + let cert = generate_self_signed_certificate().expect("Failed to generate cert"); + let config = Arc::new( + Config::builder() + .use_server_cookie(false) + .build() + .expect("config"), + ); + Dtls::new_12(config, cert, Instant::now()) + } + + fn new_instance_13() -> Dtls { + let cert = generate_self_signed_certificate().expect("Failed to generate cert"); + let config = Arc::new(Config::default()); + Dtls::new_13(config, cert, Instant::now()) + } + + fn new_instance_auto() -> Dtls { + let cert = generate_self_signed_certificate().expect("Failed to generate cert"); + let config = Arc::new(Config::default()); + Dtls::new_auto(config, cert, Instant::now()) + } + + #[test] + fn test_dtls_default() { + let mut dtls = new_instance(); + assert!(!dtls.is_active()); + dtls.set_active(true); + assert!(dtls.is_active()); + dtls.set_active(false); + } + + #[test] + fn test_dtls13_default() { + let mut dtls = new_instance_13(); + assert!(!dtls.is_active()); + dtls.set_active(true); + assert!(dtls.is_active()); + dtls.set_active(false); + } + + #[test] + fn test_auto_sense_set_active_creates_client_pending() { + let mut dtls = new_instance_auto(); + assert!(!dtls.is_active()); + dtls.set_active(true); + assert!(dtls.is_active()); + assert!(matches!(dtls.inner, Some(Inner::ClientPending(_)))); + } + + #[test] + fn test_auto_sense_client_sends_hybrid_ch() { + let mut dtls = new_instance_auto(); + dtls.set_active(true); + let now = Instant::now(); + dtls.handle_timeout(now).unwrap(); + let output = &mut [0u8; 2048]; + // First poll returns the hybrid ClientHello packet + let result = dtls.poll_output(output); + assert!(matches!(result, Output::Packet(_))); + // Second poll returns Timeout + let result = dtls.poll_output(output); + assert!(matches!(result, Output::Timeout(_))); + } + + #[test] + fn test_auto_client_unknown_version_no_panic() { + // Regression: handle_packet returning UnexpectedMessage for an + // unrecognized server response must not leave inner as None, + // which would panic on the next poll_output/handle_timeout. + let mut dtls = new_instance_auto(); + dtls.set_active(true); + let now = Instant::now(); + dtls.handle_timeout(now).unwrap(); + + // Drain the hybrid ClientHello + let mut buf = [0u8; 2048]; + loop { + if matches!(dtls.poll_output(&mut buf), Output::Timeout(_)) { + break; + } + } + + // Feed a garbage packet that won't be recognized as DTLS 1.2 or 1.3 + let garbage = [0xFF; 64]; + let err = dtls.handle_packet(&garbage).unwrap_err(); + assert!(matches!(err, Error::UnexpectedMessage(_))); + + // These must NOT panic — inner should still be intact + dtls.handle_timeout(now).unwrap(); + let _ = dtls.poll_output(&mut buf); + } + + #[test] + fn test_auto_psk_only_dtls12_uses_dtls12_path() { + let cert = generate_self_signed_certificate().expect("Failed to generate cert"); + let config = Arc::new( + Config::builder() + .with_psk_client(b"identity".to_vec(), Arc::new(FixedPsk)) + .dtls12_cipher_suites(&[Dtls12CipherSuite::PSK_AES128_CCM_8]) + .dtls13_cipher_suites(&[]) + .build() + .expect("PSK-only DTLS 1.2 config should build"), + ); + + let mut dtls = Dtls::new_auto(config, cert, Instant::now()); + dtls.set_active(true); + + assert!(dtls.is_active(), "client should become active"); + assert!( + matches!(dtls.inner, Some(Inner::Client12(_))), + "PSK-only DTLS 1.2 auto config should reuse the DTLS 1.2 client path" + ); + } + + #[test] + fn is_send() { + fn is_send(_t: T) {} + fn is_sync(_t: T) {} + is_send(new_instance()); + is_sync(new_instance()); + is_send(new_instance_13()); + is_sync(new_instance_13()); + is_send(new_instance_auto()); + is_sync(new_instance_auto()); + } + + #[test] + fn is_unwind_safe() { + fn is_unwind_safe(_t: T) {} + is_unwind_safe(new_instance()); + is_unwind_safe(new_instance_13()); + is_unwind_safe(new_instance_auto()); + } + + #[test] + fn test_protocol_version_12() { + let dtls = new_instance(); + assert_eq!(dtls.protocol_version(), Some(ProtocolVersion::DTLS1_2)); + } + + #[test] + fn test_protocol_version_13() { + let dtls = new_instance_13(); + assert_eq!(dtls.protocol_version(), Some(ProtocolVersion::DTLS1_3)); + } + + #[test] + fn test_protocol_version_auto_pending() { + let dtls = new_instance_auto(); + assert_eq!(dtls.protocol_version(), None); + } + + #[test] + #[should_panic(expected = "requires a PSK configuration")] + fn new_12_psk_panics_without_psk_config() { + let config = Arc::new(Config::default()); + let _ = Dtls::new_12_psk(config, Instant::now()); + } + + #[test] + #[should_panic(expected = "Server certificate cannot be empty")] + fn new_12_panics_on_empty_certificate() { + let cert = generate_self_signed_certificate().expect("Failed to generate cert"); + let config = Arc::new(Config::default()); + let empty = DtlsCertificate { + certificate: vec![], + private_key: cert.private_key, + }; + let _ = Dtls::new_12(config, empty, Instant::now()); + } + + #[test] + fn test_auto_server_send_application_data_pending() { + let mut dtls = new_instance_auto(); + let err = dtls.send_application_data(b"early data").unwrap_err(); + assert!(matches!(err, Error::HandshakePending)); + } + + #[test] + fn test_auto_close_pending() { + let mut dtls = new_instance_auto(); + let err = dtls.close().unwrap_err(); + assert!(matches!(err, Error::HandshakePending)); + } + + fn make_record(content_type: u8, body: &[u8]) -> Vec { + let mut pkt = Vec::with_capacity(13 + body.len()); + pkt.push(content_type); + pkt.extend_from_slice(&[0xFE, 0xFD]); // version + pkt.extend_from_slice(&[0x00, 0x00]); // epoch + pkt.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // seq + pkt.extend_from_slice(&(body.len() as u16).to_be_bytes()); + pkt.extend_from_slice(body); + pkt + } + + /// Build a handshake message: 12-byte header + body bytes. + fn make_handshake( + msg_type: u8, + length: u32, + frag_off: u32, + frag_len: u32, + body: &[u8], + ) -> Vec { + let mut hs = Vec::with_capacity(12 + body.len()); + hs.push(msg_type); + hs.extend_from_slice(&length.to_be_bytes()[1..]); // 3-byte length + hs.extend_from_slice(&[0x00, 0x00]); // message_seq + hs.extend_from_slice(&frag_off.to_be_bytes()[1..]); // 3-byte fragment_offset + hs.extend_from_slice(&frag_len.to_be_bytes()[1..]); // 3-byte fragment_length + hs.extend_from_slice(body); + hs + } + + /// Minimum-shape DTLS 1.2 ClientHello body (41 bytes): + /// version(2) + random(32) + sid_len=0(1) + cookie_len=0(1) + + /// suites_len=2(2) + 2 bytes of suite + comp_len=1(1) + null comp(1) + /// = 42. We use 41 to match the gate's lower bound; an extra byte is + /// fine. Returns a fixed valid-shape body for use in unit tests. + fn min_ch_body() -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&[0xFE, 0xFD]); // version + body.extend_from_slice(&[0u8; 32]); // random + body.push(0); // session_id_length = 0 + body.push(0); // cookie_length = 0 + body.extend_from_slice(&[0x00, 0x02]); // cipher_suites_length = 2 + body.extend_from_slice(&[0xC0, 0x2B]); // one suite (ECDHE_ECDSA_AES128_GCM) + body.push(1); // compression_methods_length = 1 + body.push(0); // null compression + body + } + + fn dtls13_ch_body_with_extension(extension_type: u16, extension_data: &[u8]) -> Vec { + let mut extensions = Vec::new(); + extensions.extend_from_slice(&extension_type.to_be_bytes()); + extensions.extend_from_slice(&(extension_data.len() as u16).to_be_bytes()); + extensions.extend_from_slice(extension_data); + dtls13_ch_body_with_extensions(&extensions) + } + + fn dtls13_ch_body_with_extensions(extensions: &[u8]) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&[0xFE, 0xFD]); // legacy_version + body.extend_from_slice(&[0u8; 32]); // random + body.push(0); // legacy_session_id length + body.push(0); // legacy_cookie length + body.extend_from_slice(&[0x00, 0x02]); // cipher_suites length + body.extend_from_slice(&[0x13, 0x01]); // TLS_AES_128_GCM_SHA256 + body.push(1); // compression_methods length + body.push(0); // null compression + + body.extend_from_slice(&(extensions.len() as u16).to_be_bytes()); + body.extend_from_slice(extensions); + body + } + + fn dtls12_ch_body_with_extensions(extensions: &[u8]) -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&[0xFE, 0xFD]); // client_version + body.extend_from_slice(&[0u8; 32]); // random + body.push(0); // session_id length + body.push(0); // cookie length + body.extend_from_slice(&[0x00, 0x02]); // cipher_suites length + body.extend_from_slice(&[0xC0, 0x2B]); // ECDHE_ECDSA_AES128_GCM_SHA256 + body.push(1); // compression_methods length + body.push(0); // null compression + body.extend_from_slice(&(extensions.len() as u16).to_be_bytes()); + body.extend_from_slice(extensions); + body + } + + #[test] + fn looks_like_client_hello_accepts_minimum_shape_ch() { + let body = min_ch_body(); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + assert!(looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_non_handshake_record() { + let body = min_ch_body(); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x17, &hs); // ApplicationData + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_other_handshake_msg_types() { + // ServerHello, HelloVerifyRequest, Finished, etc. + let body = min_ch_body(); + let len = body.len() as u32; + for msg_type in [0x02, 0x03, 0x04, 0x0B, 0x0E, 0x14] { + let hs = make_handshake(msg_type, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + assert!( + !looks_like_client_hello(&pkt), + "msg_type {:#x} should not look like a CH", + msg_type + ); + } + } + + #[test] + fn looks_like_client_hello_rejects_truncated_packets() { + assert!(!looks_like_client_hello(&[])); + assert!(!looks_like_client_hello(&[0x16; 12])); // too short for record header + // Record header claims body length 100 but no body bytes follow. + let mut pkt = vec![0x16, 0xFE, 0xFD, 0, 0, 0, 0, 0, 0, 0, 0]; + pkt.extend_from_slice(&100u16.to_be_bytes()); + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_short_handshake_body() { + // Valid record header but handshake body too short (< 12 bytes). + let pkt = make_record(0x16, &[0x01, 0x00, 0x00]); + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_header_only_ch() { + // Handshake header with msg_type=ClientHello but length=0 and no body. + // Pre-tightening this passed; it must now be rejected. + let hs = make_handshake(0x01, 0, 0, 0, &[]); + let pkt = make_record(0x16, &hs); + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_undersized_unfragmented_ch() { + // Unfragmented CH (frag_off=0, frag_len=length) but length=20 — way + // below the 41-byte minimum a real DTLS 1.2 CH can have. + let body = vec![0xAA; 20]; + let hs = make_handshake(0x01, 20, 0, 20, &body); + let pkt = make_record(0x16, &hs); + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_inconsistent_fragment_overflow() { + // fragment_offset + fragment_length > length — wire-format + // contradiction; the fragment claims to extend past the total CH. + let body = min_ch_body(); + let hs = make_handshake(0x01, 50, 0, 100, &body); + let pkt = make_record(0x16, &hs); + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_missing_fragment_bytes() { + // fragment_length declares 200 bytes of body but only ~40 are + // present in the record. The fragment's bytes are not actually + // there. + let body = min_ch_body(); + let hs = make_handshake(0x01, 200, 0, 200, &body); + let pkt = make_record(0x16, &hs); + assert!(!looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_accepts_first_fragment_of_fragmented_ch() { + // frag_off=0, frag_len=20, length=200 — first fragment of a + // larger CH. The minimum-body check only applies to unfragmented + // CHs, so this must pass even though length<41 wouldn't apply + // here either. + let body = vec![0xAA; 20]; + let hs = make_handshake(0x01, 200, 0, 20, &body); + let pkt = make_record(0x16, &hs); + assert!(looks_like_client_hello(&pkt)); + } + + #[test] + fn looks_like_client_hello_rejects_non_first_fragment() { + // frag_off > 0: a non-first fragment arriving alone could be a + // spoofed packet aimed at forcing a downgrade. Real fragmented + // CHs always include a frag_off=0 fragment, and the clean + // Dtls12Fallback path (gated by supported_versions, not by this + // check) handles fully reassembled fragmented 1.2 CHs. + let body = vec![0xBB; 20]; + let hs = make_handshake(0x01, 200, 20, 20, &body); + let pkt = make_record(0x16, &hs); + assert!(!looks_like_client_hello(&pkt)); + } + + /// CH-shaped body whose `cipher_suites_length` exceeds the bytes that + /// follow it. The structural gate accepts this as ClientHello-shaped, but + /// the parser must reject it without forcing auto-sense fallback. + fn ch_shaped_malformed_body() -> Vec { + let mut body = Vec::new(); + body.extend_from_slice(&[0xFE, 0xFD]); // version + body.extend_from_slice(&[0u8; 32]); // random + body.push(0); // session_id_length = 0 + body.push(0); // cookie_length = 0 + body.extend_from_slice(&[0x00, 0x04]); // cipher_suites_length exceeds available suites + body.extend_from_slice(&[0xC0, 0x2B]); // 2 bytes that pretend to be a suite + body.push(1); // compression_methods_length = 1 + body.push(0); // null compression + body + } + + #[test] + fn auto_server_discards_ch_shaped_malformed_packet_without_fallback() { + let body = ch_shaped_malformed_body(); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + assert!( + looks_like_client_hello(&pkt), + "fixture must pass the structural gate" + ); + + let mut dtls = new_instance_auto(); + dtls.handle_packet(&pkt) + .expect("malformed ClientHello-shaped packet should be discarded"); + assert!(matches!( + dtls.inner, + Some(Inner::Server13(ref server)) if server.is_auto_mode() + )); + } + + #[test] + fn dtls13_server_accepts_distinct_supported_key_shares_before_cookie_hrr() { + let supported_versions = [ + 0x02, // One protocol version. + 0xFE, 0xFC, // DTLS 1.3. + ]; + + let mut supported_groups = Vec::new(); + supported_groups + .extend_from_slice(&(NamedGroup::supported().len() as u16 * 2).to_be_bytes()); + for group in NamedGroup::supported() { + supported_groups.extend_from_slice(&group.as_u16().to_be_bytes()); + } + + let mut key_share = Vec::new(); + key_share.extend_from_slice(&(NamedGroup::supported().len() as u16 * 5).to_be_bytes()); + for group in NamedGroup::supported() { + key_share.extend_from_slice(&group.as_u16().to_be_bytes()); + key_share.extend_from_slice(&1u16.to_be_bytes()); + key_share.push(0x42); + } + + let mut extensions = Vec::new(); + extensions.extend_from_slice(&0x002Bu16.to_be_bytes()); // supported_versions + extensions.extend_from_slice(&(supported_versions.len() as u16).to_be_bytes()); + extensions.extend_from_slice(&supported_versions); + extensions.extend_from_slice(&0x000Au16.to_be_bytes()); // supported_groups + extensions.extend_from_slice(&(supported_groups.len() as u16).to_be_bytes()); + extensions.extend_from_slice(&supported_groups); + extensions.extend_from_slice(&0x0033u16.to_be_bytes()); // key_share + extensions.extend_from_slice(&(key_share.len() as u16).to_be_bytes()); + extensions.extend_from_slice(&key_share); + + let body = dtls13_ch_body_with_extensions(&extensions); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + + let mut dtls = new_instance_13(); + dtls.handle_packet(&pkt).expect( + "all distinct supported key shares should fit server-side parsing before cookie HRR", + ); + } + + #[test] + fn dtls13_server_accepts_unknown_supported_versions_before_cookie_hrr() { + let supported_versions = [ + 0x08, // Four protocol versions. + 0xFE, 0xFE, // Unknown/GREASE-like value. + 0xFE, 0xFC, // DTLS 1.3. + 0xFE, 0xFD, // DTLS 1.2. + 0xFE, 0xFF, // DTLS 1.0. + ]; + let body = dtls13_ch_body_with_extension(0x002B, &supported_versions); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + + let mut dtls = new_instance_13(); + dtls.handle_packet(&pkt) + .expect("unknown supported_versions values should not overflow server-side parsing"); + } + + #[test] + fn dtls12_server_discards_oversized_ec_point_formats_extension() { + let mut extensions = Vec::new(); + extensions.extend_from_slice(&[0x00, 0x0B]); // ec_point_formats + extensions.extend_from_slice(&[0x00, 0x05]); // extension body length + extensions.extend_from_slice(&[ + 0x04, // Four point formats. + 0x00, // Uncompressed. + 0x00, // Uncompressed. + 0x00, // Uncompressed. + 0x00, // Uncompressed. + ]); + extensions.extend_from_slice(&[0x00, 0x17]); // extended_master_secret + extensions.extend_from_slice(&[0x00, 0x00]); // empty extension body + + let body = dtls12_ch_body_with_extensions(&extensions); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + + let mut dtls = new_instance_12_no_cookie(); + dtls.handle_packet(&pkt) + .expect("malformed extension should be discarded"); + } + + #[test] + fn dtls12_server_discards_trailing_ec_point_formats_extension() { + let mut extensions = Vec::new(); + extensions.extend_from_slice(&[0x00, 0x0B]); // ec_point_formats + extensions.extend_from_slice(&[0x00, 0x03]); // extension body length + extensions.extend_from_slice(&[ + 0x01, // One point format. + 0x00, // Uncompressed. + 0xFF, // Trailing extension body byte beyond the inner vector. + ]); + extensions.extend_from_slice(&[0x00, 0x17]); // extended_master_secret + extensions.extend_from_slice(&[0x00, 0x00]); // empty extension body + + let body = dtls12_ch_body_with_extensions(&extensions); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + + let mut dtls = new_instance_12_no_cookie(); + dtls.handle_packet(&pkt) + .expect("malformed extension should be discarded"); + } + + #[test] + fn dtls12_server_accepts_unknown_ec_point_formats_extension() { + let mut extensions = Vec::new(); + extensions.extend_from_slice(&[0x00, 0x0B]); // ec_point_formats + extensions.extend_from_slice(&[0x00, 0x04]); // extension body length + extensions.extend_from_slice(&[ + 0x03, // Three point formats. + 0x02, // ANSI X9.62 compressed char2. + 0x00, // Uncompressed. + 0xFF, // Unknown/private point format. + ]); + extensions.extend_from_slice(&[0x00, 0x17]); // extended_master_secret + extensions.extend_from_slice(&[0x00, 0x00]); // empty extension body + + let body = dtls12_ch_body_with_extensions(&extensions); + let len = body.len() as u32; + let hs = make_handshake(0x01, len, 0, len, &body); + let pkt = make_record(0x16, &hs); + + let mut dtls = new_instance_12_no_cookie(); + dtls.handle_timeout(Instant::now()).unwrap(); + dtls.handle_packet(&pkt) + .expect("unknown ec_point_formats values should not fail server-side parsing"); + } + + #[test] + fn auto_server_drops_garbage_without_falling_back() { + let mut dtls = new_instance_auto(); + // Random non-handshake bytes — the 1.3 engine will error, but the + // auto-sense path must not downgrade to 1.2. + let garbage = [0xFF; 64]; + let _ = dtls.handle_packet(&garbage); + // Inner must remain Server13 in auto-sense mode. + let still_pending = match &dtls.inner { + Some(Inner::Server13(s)) => s.is_auto_mode(), + _ => false, + }; + assert!( + still_pending, + "auto-sense server must not fall back to DTLS 1.2 on garbage input" + ); + } +} diff --git a/third_party/dimpl/src/rng.rs b/third_party/dimpl/src/rng.rs new file mode 100644 index 0000000..8980ace --- /dev/null +++ b/third_party/dimpl/src/rng.rs @@ -0,0 +1,100 @@ +//! Seedable random number generator for deterministic testing. +//! +//! When a seed is provided via [`Config::rng_seed`], all non-cryptographic +//! randomness will be deterministic. This is useful for testing and debugging. + +use rand::distr::{Distribution, StandardUniform}; +use rand::rngs::StdRng; +use rand::{Rng, SeedableRng}; + +/// A random number generator that can be seeded for deterministic behavior. +/// +/// When created with a seed, it produces deterministic random values. +/// When created without a seed, it uses the thread-local random generator. +pub struct SeededRng { + inner: Option, +} + +impl SeededRng { + /// Create a new RNG with an optional seed. + /// + /// If `seed` is `Some`, the RNG will produce deterministic values. + /// If `seed` is `None`, it will use the thread-local random generator. + pub fn new(seed: Option) -> Self { + let inner = seed.map(StdRng::seed_from_u64); + Self { inner } + } + + /// Generate a random value of type T. + pub fn random(&mut self) -> T + where + StandardUniform: Distribution, + { + match self.inner.as_mut() { + Some(rng) => rng.random(), + None => rand::random(), + } + } +} + +impl std::fmt::Debug for SeededRng { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let is_seeded = self.inner.is_some(); + f.debug_struct("SeededRng") + .field("seeded", &is_seeded) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn seeded_rng_is_deterministic() { + let mut rng1 = SeededRng::new(Some(12345)); + let mut rng2 = SeededRng::new(Some(12345)); + + let values1: [u8; 10] = [ + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + rng1.random(), + ]; + + let values2: [u8; 10] = [ + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + rng2.random(), + ]; + + assert_eq!(values1, values2, "Same seed should produce same values"); + } + + #[test] + fn different_seeds_produce_different_values() { + let mut rng1 = SeededRng::new(Some(12345)); + let mut rng2 = SeededRng::new(Some(54321)); + + let value1: u64 = rng1.random(); + let value2: u64 = rng2.random(); + + assert_ne!( + value1, value2, + "Different seeds should produce different values" + ); + } +} diff --git a/third_party/dimpl/src/time_tricks.rs b/third_party/dimpl/src/time_tricks.rs new file mode 100644 index 0000000..37026ba --- /dev/null +++ b/third_party/dimpl/src/time_tricks.rs @@ -0,0 +1,65 @@ +use std::time::SystemTime; +use std::time::{Duration, Instant}; + +use once_cell::sync::Lazy; + +// The goal here is to make a constant "beginning of time" in both Instant and SystemTime +// that we can use as relative values for the rest of dimpl. +// This is indeed a bit dodgy, but we want dimpl's internal idea of time to be completely +// driven from the external API using `Instant`. What works against us is that Instant can't +// represent things like UNIX EPOCH (but SystemTime can). +static BEGINNING_OF_TIME: Lazy<(Instant, SystemTime)> = Lazy::new(|| { + // These two should be "frozen" the same instant. Hopefully they are not differing too much. + let now = Instant::now(); + let now_sys = SystemTime::now(); + + // Find an Instant in the past which is up to an hour back. + let beginning_of_time = { + let mut secs = 3600; + loop { + let dur = Duration::from_secs(secs); + if let Some(v) = now.checked_sub(dur) { + break v; + } + secs -= 1; + if secs == 0 { + panic!("Failed to find a beginning of time instant"); + } + } + }; + + // This might be less than 1 hour if the machine uptime is less. + let since_beginning_of_time = Instant::now() - beginning_of_time; + + let beginning_of_time_sys = now_sys - since_beginning_of_time; + + // This pair represents our "beginning of time" for the same moment. + (beginning_of_time, beginning_of_time_sys) +}); + +pub trait InstantExt { + /// Convert an Instant to a Duration for unix time. + /// + /// First ever time must be "now". + /// + /// panics if `time` goes backwards, i.e. we use this for one Instant and then an earlier Instant. + fn to_unix_duration(&self) -> Duration; +} + +impl InstantExt for Instant { + fn to_unix_duration(&self) -> Duration { + // This is a bit fishy. We "freeze" a moment in time for Instant and SystemTime, + // so we can make relative comparisons of Instant - Instant and translate that to + // SystemTime - unix epoch. Hopefully the error is quite small. + if *self < BEGINNING_OF_TIME.0 { + warn!("Time went backwards from beginning_of_time Instant"); + } + + let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0); + let system_time = BEGINNING_OF_TIME.1 + duration_since_time_0; + + system_time + .duration_since(SystemTime::UNIX_EPOCH) + .expect("clock to go forwards from unix epoch") + } +} diff --git a/third_party/dimpl/src/timer.rs b/third_party/dimpl/src/timer.rs new file mode 100644 index 0000000..ad5fe5f --- /dev/null +++ b/third_party/dimpl/src/timer.rs @@ -0,0 +1,116 @@ +use std::ops::Mul; +use std::time::Duration; + +use crate::SeededRng; + +// In seconds. +const JITTER_RANGE: f32 = 0.5; + +pub struct ExponentialBackoff { + start_rto: Duration, + retries: usize, + rto: Duration, + jitter: f32, + left: usize, +} + +impl ExponentialBackoff { + pub fn new(start_rto: Duration, retries: usize, rng: &mut SeededRng) -> Self { + Self { + start_rto, + retries, + rto: start_rto, + jitter: Self::jitter(rng), + left: retries, + } + } + + pub fn reset(&mut self, rng: &mut SeededRng) { + self.rto = self.start_rto; + self.jitter = Self::jitter(rng); + self.left = self.retries; + } + + pub fn rto(&self) -> Duration { + if self.jitter < 0.0 { + let duration = Duration::from_secs_f32(self.jitter.abs()); + self.rto.saturating_sub(duration) + } else { + self.rto + Duration::from_secs_f32(self.jitter) + } + .max(Duration::from_millis(50)) + } + + // A value between -0.25s and 0.25s + fn jitter(rng: &mut SeededRng) -> f32 { + rng.random::() * JITTER_RANGE - (JITTER_RANGE / 2.0) + } + + pub fn attempt(&mut self, rng: &mut SeededRng) { + let (n, overflow) = self.left.overflowing_sub(1); + + if overflow { + return; + } + + self.left = n; + self.jitter = Self::jitter(rng); + self.rto = self.rto.mul(2); + } + + pub fn can_retry(&self) -> bool { + self.left > 0 + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn attempts() { + let mut rng = SeededRng::new(Some(42)); + let mut exp = ExponentialBackoff::new(Duration::from_secs(1), 5, &mut rng); + + let n1 = dbg!(exp.rto().as_millis()); + assert_eq!(exp.rto().as_millis(), n1); + + exp.attempt(&mut rng); + + let n2 = dbg!(exp.rto().as_millis()); + assert_eq!(exp.rto().as_millis(), n2); + assert!(n2 > n1); + + exp.attempt(&mut rng); + + let n3 = dbg!(exp.rto().as_millis()); + assert_eq!(exp.rto().as_millis(), n3); + assert!(n3 > n2); + + exp.attempt(&mut rng); + + let n4 = dbg!(exp.rto().as_millis()); + assert_eq!(exp.rto().as_millis(), n4); + assert!(n4 > n3); + assert!(exp.can_retry()); + + exp.attempt(&mut rng); + + let n5 = dbg!(exp.rto().as_millis()); + assert_eq!(exp.rto().as_millis(), n5); + assert!(n5 > n4); + assert!(exp.can_retry()); + + exp.attempt(&mut rng); + + let n6 = dbg!(exp.rto().as_millis()); + assert_eq!(exp.rto().as_millis(), n6); + assert!(n6 > n5); + assert!(!exp.can_retry()); + + exp.attempt(&mut rng); + + assert_eq!(exp.rto().as_millis(), n6); + assert!(!exp.can_retry()); + } +} diff --git a/third_party/dimpl/src/types.rs b/third_party/dimpl/src/types.rs new file mode 100644 index 0000000..08a1a32 --- /dev/null +++ b/third_party/dimpl/src/types.rs @@ -0,0 +1,1275 @@ +//! Shared types used by both DTLS 1.2 and DTLS 1.3. +//! +//! These types represent cryptographic primitives and protocol elements +//! that are common across DTLS versions. + +use std::cmp::Ordering; +use std::fmt; +use std::time::Instant; + +use arrayvec::ArrayVec; +use nom::IResult; +use nom::bytes::complete::take; +use nom::number::complete::{be_u8, be_u16}; + +use crate::SeededRng; +use crate::buffer::Buf; +use crate::time_tricks::InstantExt; + +pub type NamedGroupVec = ArrayVec; + +// ============================================================================ +// Random +// ============================================================================ + +/// ClientHello / ServerHello random value (32 bytes on the wire). +/// +/// Used by both DTLS 1.2 and DTLS 1.3. Construction differs: +/// - DTLS 1.2: first 4 bytes are `gmt_unix_time` ([`Random::new_with_time`]). +/// - DTLS 1.3: all 32 bytes are random ([`Random::new`]). +/// +/// After construction neither version accesses sub-fields — all consumers +/// use [`bytes`](Self::bytes) or [`serialize`](Self::serialize). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Random { + /// The 32 raw bytes of the random value. + pub bytes: [u8; 32], +} + +impl Random { + /// All-random (DTLS 1.3 / hybrid style). + pub fn new(rng: &mut SeededRng) -> Self { + Self { + bytes: rng.random(), + } + } + + /// Timestamp in first 4 bytes (DTLS 1.2 style). + pub fn new_with_time(now: Instant, rng: &mut SeededRng) -> Self { + let gmt_duration = now.to_unix_duration(); + // This is valid until year 2106, at which point I will be beyond caring. + let gmt_unix_time = gmt_duration.as_secs() as u32; + + let random_bytes: [u8; 28] = rng.random(); + + let mut bytes = [0u8; 32]; + bytes[..4].copy_from_slice(&gmt_unix_time.to_be_bytes()); + bytes[4..].copy_from_slice(&random_bytes); + + Self { bytes } + } + + /// Parse a 32-byte `Random` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], Random> { + let (input, data) = take(32_usize)(input)?; + let mut bytes = [0u8; 32]; + bytes.copy_from_slice(data); + Ok((input, Random { bytes })) + } + + /// Serialize this `Random` to wire format. + pub fn serialize(&self, output: &mut Buf) { + output.extend_from_slice(&self.bytes); + } +} + +// ============================================================================ +// Named Groups (Key Exchange) +// ============================================================================ + +/// Elliptic curves and key exchange groups (RFC 8422, RFC 8446). +/// +/// Used for Elliptic Curve Diffie-Hellman Ephemeral (ECDHE) key exchange. +/// The same named groups are used in both DTLS 1.2 and DTLS 1.3. +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct NamedGroup(u16); + +#[allow(non_upper_case_globals)] +impl NamedGroup { + /// sect163k1 (deprecated). + pub const Sect163k1: Self = Self(1); + /// sect163r1 (deprecated). + pub const Sect163r1: Self = Self(2); + /// sect163r2 (deprecated). + pub const Sect163r2: Self = Self(3); + /// sect193r1 (deprecated). + pub const Sect193r1: Self = Self(4); + /// sect193r2 (deprecated). + pub const Sect193r2: Self = Self(5); + /// sect233k1 (deprecated). + pub const Sect233k1: Self = Self(6); + /// sect233r1 (deprecated). + pub const Sect233r1: Self = Self(7); + /// sect239k1 (deprecated). + pub const Sect239k1: Self = Self(8); + /// sect283k1 (deprecated). + pub const Sect283k1: Self = Self(9); + /// sect283r1 (deprecated). + pub const Sect283r1: Self = Self(10); + /// sect409k1 (deprecated). + pub const Sect409k1: Self = Self(11); + /// sect409r1 (deprecated). + pub const Sect409r1: Self = Self(12); + /// sect571k1 (deprecated). + pub const Sect571k1: Self = Self(13); + /// sect571r1 (deprecated). + pub const Sect571r1: Self = Self(14); + /// secp160k1 (deprecated). + pub const Secp160k1: Self = Self(15); + /// secp160r1 (deprecated). + pub const Secp160r1: Self = Self(16); + /// secp160r2 (deprecated). + pub const Secp160r2: Self = Self(17); + /// secp192k1 (deprecated). + pub const Secp192k1: Self = Self(18); + /// secp192r1 (deprecated). + pub const Secp192r1: Self = Self(19); + /// secp224k1. + pub const Secp224k1: Self = Self(20); + /// secp224r1. + pub const Secp224r1: Self = Self(21); + /// secp256k1. + pub const Secp256k1: Self = Self(22); + /// secp256r1 / P-256 (supported by dimpl). + pub const Secp256r1: Self = Self(23); + /// secp384r1 / P-384 (supported by dimpl). + pub const Secp384r1: Self = Self(24); + /// secp521r1 / P-521. + pub const Secp521r1: Self = Self(25); + /// X25519 (Curve25519 for ECDHE). + pub const X25519: Self = Self(29); + /// X448 (Curve448 for ECDHE). + pub const X448: Self = Self(30); + + /// Convert a wire format u16 value to a `NamedGroup`. + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + /// Convert this `NamedGroup` to its wire format u16 value. + pub const fn as_u16(&self) -> u16 { + self.0 + } + + /// Returns true if this is not a known TLS named group wire value. + pub const fn is_unknown(&self) -> bool { + !matches!(*self, Self(1..=25 | 29..=30)) + } + + /// Parse a `NamedGroup` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], NamedGroup> { + let (input, value) = be_u16(input)?; + Ok((input, NamedGroup::from_u16(value))) + } + + /// Returns true if this named group is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// All recognized named groups (every non-`Unknown` variant). + pub const fn all() -> &'static [NamedGroup; 27] { + &[ + NamedGroup::Sect163k1, + NamedGroup::Sect163r1, + NamedGroup::Sect163r2, + NamedGroup::Sect193r1, + NamedGroup::Sect193r2, + NamedGroup::Sect233k1, + NamedGroup::Sect233r1, + NamedGroup::Sect239k1, + NamedGroup::Sect283k1, + NamedGroup::Sect283r1, + NamedGroup::Sect409k1, + NamedGroup::Sect409r1, + NamedGroup::Sect571k1, + NamedGroup::Sect571r1, + NamedGroup::Secp160k1, + NamedGroup::Secp160r1, + NamedGroup::Secp160r2, + NamedGroup::Secp192k1, + NamedGroup::Secp192r1, + NamedGroup::Secp224k1, + NamedGroup::Secp224r1, + NamedGroup::Secp256k1, + NamedGroup::Secp256r1, + NamedGroup::Secp384r1, + NamedGroup::Secp521r1, + NamedGroup::X25519, + NamedGroup::X448, + ] + } + + /// Supported named groups in preference order. + pub const fn supported() -> &'static [NamedGroup; 4] { + &[ + NamedGroup::X25519, + NamedGroup::Secp256r1, + NamedGroup::Secp384r1, + NamedGroup::Secp521r1, + ] + } +} + +impl fmt::Debug for NamedGroup { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + NamedGroup::Sect163k1 => f.write_str("Sect163k1"), + NamedGroup::Sect163r1 => f.write_str("Sect163r1"), + NamedGroup::Sect163r2 => f.write_str("Sect163r2"), + NamedGroup::Sect193r1 => f.write_str("Sect193r1"), + NamedGroup::Sect193r2 => f.write_str("Sect193r2"), + NamedGroup::Sect233k1 => f.write_str("Sect233k1"), + NamedGroup::Sect233r1 => f.write_str("Sect233r1"), + NamedGroup::Sect239k1 => f.write_str("Sect239k1"), + NamedGroup::Sect283k1 => f.write_str("Sect283k1"), + NamedGroup::Sect283r1 => f.write_str("Sect283r1"), + NamedGroup::Sect409k1 => f.write_str("Sect409k1"), + NamedGroup::Sect409r1 => f.write_str("Sect409r1"), + NamedGroup::Sect571k1 => f.write_str("Sect571k1"), + NamedGroup::Sect571r1 => f.write_str("Sect571r1"), + NamedGroup::Secp160k1 => f.write_str("Secp160k1"), + NamedGroup::Secp160r1 => f.write_str("Secp160r1"), + NamedGroup::Secp160r2 => f.write_str("Secp160r2"), + NamedGroup::Secp192k1 => f.write_str("Secp192k1"), + NamedGroup::Secp192r1 => f.write_str("Secp192r1"), + NamedGroup::Secp224k1 => f.write_str("Secp224k1"), + NamedGroup::Secp224r1 => f.write_str("Secp224r1"), + NamedGroup::Secp256k1 => f.write_str("Secp256k1"), + NamedGroup::Secp256r1 => f.write_str("Secp256r1"), + NamedGroup::Secp384r1 => f.write_str("Secp384r1"), + NamedGroup::Secp521r1 => f.write_str("Secp521r1"), + NamedGroup::X25519 => f.write_str("X25519"), + NamedGroup::X448 => f.write_str("X448"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// Hash Algorithms +// ============================================================================ + +/// Hash algorithms used in DTLS (RFC 5246, RFC 8446). +/// +/// Specifies the hash algorithm to be used in digital signatures, +/// PRF/HKDF operations, and transcript hashing. +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct HashAlgorithm(u8); + +impl Default for HashAlgorithm { + fn default() -> Self { + Self::None + } +} + +#[allow(non_upper_case_globals)] +impl HashAlgorithm { + /// No hash (not typically used). + pub const None: Self = Self(0); + /// MD5 hash (deprecated, not supported). + pub const MD5: Self = Self(1); + /// SHA-1 hash (deprecated, not supported). + pub const SHA1: Self = Self(2); + /// SHA-224 hash. + pub const SHA224: Self = Self(3); + /// SHA-256 hash (supported by dimpl). + pub const SHA256: Self = Self(4); + /// SHA-384 hash (supported by dimpl). + pub const SHA384: Self = Self(5); + /// SHA-512 hash. + pub const SHA512: Self = Self(6); + + pub(crate) const UNKNOWN_DERIVED: Self = Self(u8::MAX); + + /// Convert a wire format u8 value to a `HashAlgorithm`. + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + /// Convert this `HashAlgorithm` to its wire format u8 value. + pub const fn as_u8(&self) -> u8 { + self.0 + } + + /// Returns true if this is not a known DTLS hash algorithm wire value. + pub const fn is_unknown(&self) -> bool { + self.0 > Self::SHA512.0 + } + + /// Parse a `HashAlgorithm` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], HashAlgorithm> { + let (input, value) = be_u8(input)?; + Ok((input, HashAlgorithm::from_u8(value))) + } + + /// Returns the output length in bytes for this hash algorithm. + pub const fn output_len(&self) -> usize { + match *self { + HashAlgorithm::None => 0, + HashAlgorithm::MD5 => 16, + HashAlgorithm::SHA1 => 20, + HashAlgorithm::SHA224 => 28, + HashAlgorithm::SHA256 => 32, + HashAlgorithm::SHA384 => 48, + HashAlgorithm::SHA512 => 64, + _ => 0, + } + } +} + +impl fmt::Debug for HashAlgorithm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + HashAlgorithm::None => f.write_str("None"), + HashAlgorithm::MD5 => f.write_str("MD5"), + HashAlgorithm::SHA1 => f.write_str("SHA1"), + HashAlgorithm::SHA224 => f.write_str("SHA224"), + HashAlgorithm::SHA256 => f.write_str("SHA256"), + HashAlgorithm::SHA384 => f.write_str("SHA384"), + HashAlgorithm::SHA512 => f.write_str("SHA512"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// Signature Algorithms +// ============================================================================ + +/// Signature algorithms used in DTLS handshakes. +/// +/// Represents the underlying signature primitive (RSA, ECDSA, etc.). +/// Used internally for signing operations across both DTLS versions. +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct SignatureAlgorithm(u8); + +impl Default for SignatureAlgorithm { + fn default() -> Self { + Self::Anonymous + } +} + +#[allow(non_upper_case_globals)] +impl SignatureAlgorithm { + /// Anonymous (no certificate). + pub const Anonymous: Self = Self(0); + /// RSA signatures. + pub const RSA: Self = Self(1); + /// DSA signatures. + pub const DSA: Self = Self(2); + /// ECDSA signatures. + pub const ECDSA: Self = Self(3); + + pub(crate) const UNKNOWN_DERIVED: Self = Self(u8::MAX); + + /// Convert an 8-bit value into a `SignatureAlgorithm`. + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + /// Convert this `SignatureAlgorithm` into its 8-bit representation. + pub const fn as_u8(&self) -> u8 { + self.0 + } + + /// Returns true if this is not a known DTLS signature algorithm wire value. + pub const fn is_unknown(&self) -> bool { + self.0 > Self::ECDSA.0 + } + + /// Parse a `SignatureAlgorithm` from network bytes. + pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureAlgorithm> { + let (input, value) = be_u8(input)?; + Ok((input, SignatureAlgorithm::from_u8(value))) + } +} + +impl fmt::Debug for SignatureAlgorithm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + SignatureAlgorithm::Anonymous => f.write_str("Anonymous"), + SignatureAlgorithm::RSA => f.write_str("RSA"), + SignatureAlgorithm::DSA => f.write_str("DSA"), + SignatureAlgorithm::ECDSA => f.write_str("ECDSA"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// Content Type +// ============================================================================ + +/// DTLS record content types. +/// +/// Identifies the type of data in a DTLS record. These values are the same +/// for both DTLS 1.2 and DTLS 1.3. +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct ContentType(u8); + +#[allow(non_upper_case_globals)] +impl ContentType { + /// Change Cipher Spec (used in DTLS 1.2, compatibility-only in 1.3). + pub const ChangeCipherSpec: Self = Self(20); + /// Alert message. + pub const Alert: Self = Self(21); + /// Handshake message. + pub const Handshake: Self = Self(22); + /// Application data. + pub const ApplicationData: Self = Self(23); + /// ACK (DTLS 1.3 only, RFC 9147 Section 7). + pub const Ack: Self = Self(26); + + /// Convert a u8 value to a `ContentType`. + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + /// Convert this `ContentType` to its u8 value. + pub const fn as_u8(&self) -> u8 { + self.0 + } + + /// Returns true if this is not a known DTLS record content type. + pub const fn is_unknown(&self) -> bool { + !matches!(*self, Self(20..=23 | 26)) + } + + /// Parse a `ContentType` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], ContentType> { + let (input, byte) = be_u8(input)?; + Ok((input, Self::from_u8(byte))) + } +} + +impl fmt::Debug for ContentType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + ContentType::ChangeCipherSpec => f.write_str("ChangeCipherSpec"), + ContentType::Alert => f.write_str("Alert"), + ContentType::Handshake => f.write_str("Handshake"), + ContentType::ApplicationData => f.write_str("ApplicationData"), + ContentType::Ack => f.write_str("Ack"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// Sequence Number +// ============================================================================ + +/// DTLS record sequence number (epoch + sequence). +/// +/// Both DTLS 1.2 and DTLS 1.3 use an epoch and sequence number for +/// replay protection and AEAD nonce construction. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Sequence { + /// The epoch (incremented on key change). + pub epoch: u16, + /// The sequence number within the epoch (technically u48). + pub sequence_number: u64, +} + +impl Sequence { + /// Create a new sequence with the given epoch and sequence number 0. + pub fn new(epoch: u16) -> Self { + Self { + epoch, + sequence_number: 0, + } + } +} + +impl fmt::Display for Sequence { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "[epoch: {}, sequence_number: {}]", + self.epoch, self.sequence_number, + ) + } +} + +impl Ord for Sequence { + fn cmp(&self, other: &Self) -> Ordering { + if self.epoch < other.epoch { + Ordering::Less + } else if self.epoch > other.epoch { + Ordering::Greater + } else { + self.sequence_number.cmp(&other.sequence_number) + } + } +} + +impl PartialOrd for Sequence { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +// ============================================================================ +// Signature Schemes (TLS 1.3) +// ============================================================================ + +/// Signature schemes used in TLS 1.3/DTLS 1.3 (RFC 8446). +/// +/// In TLS 1.3, signature schemes combine the signature algorithm with the +/// hash algorithm into a single identifier, unlike TLS 1.2 where they were +/// separate. +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct SignatureScheme(u16); + +impl SignatureScheme { + /// ECDSA with P-256 and SHA-256. + pub const ECDSA_SECP256R1_SHA256: Self = Self(0x0403); + /// ECDSA with P-384 and SHA-384. + pub const ECDSA_SECP384R1_SHA384: Self = Self(0x0503); + /// ECDSA with P-521 and SHA-512. + pub const ECDSA_SECP521R1_SHA512: Self = Self(0x0603); + /// Ed25519. + pub const ED25519: Self = Self(0x0807); + /// Ed448. + pub const ED448: Self = Self(0x0808); + /// RSA-PSS with SHA-256 (rsaEncryption OID). + pub const RSA_PSS_RSAE_SHA256: Self = Self(0x0804); + /// RSA-PSS with SHA-384 (rsaEncryption OID). + pub const RSA_PSS_RSAE_SHA384: Self = Self(0x0805); + /// RSA-PSS with SHA-512 (rsaEncryption OID). + pub const RSA_PSS_RSAE_SHA512: Self = Self(0x0806); + /// RSA-PSS with SHA-256 (id-rsassa-pss OID). + pub const RSA_PSS_PSS_SHA256: Self = Self(0x0809); + /// RSA-PSS with SHA-384 (id-rsassa-pss OID). + pub const RSA_PSS_PSS_SHA384: Self = Self(0x080a); + /// RSA-PSS with SHA-512 (id-rsassa-pss OID). + pub const RSA_PSS_PSS_SHA512: Self = Self(0x080b); + /// RSA PKCS#1 v1.5 with SHA-256 (legacy). + pub const RSA_PKCS1_SHA256: Self = Self(0x0401); + /// RSA PKCS#1 v1.5 with SHA-384 (legacy). + pub const RSA_PKCS1_SHA384: Self = Self(0x0501); + /// RSA PKCS#1 v1.5 with SHA-512 (legacy). + pub const RSA_PKCS1_SHA512: Self = Self(0x0601); + + /// Convert a wire format u16 value to a `SignatureScheme`. + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + /// Convert this `SignatureScheme` to its wire format u16 value. + pub const fn as_u16(&self) -> u16 { + self.0 + } + + /// Returns true if this is not a known TLS signature scheme wire value. + pub const fn is_unknown(&self) -> bool { + !matches!( + *self, + Self(0x0401 | 0x0403 | 0x0501 | 0x0503 | 0x0601 | 0x0603 | 0x0804..=0x080b) + ) + } + + /// Parse a `SignatureScheme` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], SignatureScheme> { + let (input, value) = be_u16(input)?; + Ok((input, SignatureScheme::from_u16(value))) + } + + /// Returns true if this signature scheme is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::SUPPORTED.contains(self) + } + + /// All recognized signature schemes (every non-`Unknown` variant). + pub const fn all() -> &'static [SignatureScheme] { + &[ + SignatureScheme::ECDSA_SECP256R1_SHA256, + SignatureScheme::ECDSA_SECP384R1_SHA384, + SignatureScheme::ECDSA_SECP521R1_SHA512, + SignatureScheme::ED25519, + SignatureScheme::ED448, + SignatureScheme::RSA_PSS_RSAE_SHA256, + SignatureScheme::RSA_PSS_RSAE_SHA384, + SignatureScheme::RSA_PSS_RSAE_SHA512, + SignatureScheme::RSA_PSS_PSS_SHA256, + SignatureScheme::RSA_PSS_PSS_SHA384, + SignatureScheme::RSA_PSS_PSS_SHA512, + SignatureScheme::RSA_PKCS1_SHA256, + SignatureScheme::RSA_PKCS1_SHA384, + SignatureScheme::RSA_PKCS1_SHA512, + ] + } + + const SUPPORTED: &[SignatureScheme] = &[ + SignatureScheme::ECDSA_SECP256R1_SHA256, + SignatureScheme::ECDSA_SECP384R1_SHA384, + ]; + + /// Supported signature schemes in preference order. + pub fn supported() -> ArrayVec { + let mut schemes = ArrayVec::new(); + schemes.push(SignatureScheme::ECDSA_SECP256R1_SHA256); + schemes.push(SignatureScheme::ECDSA_SECP384R1_SHA384); + schemes + } + + /// Returns the named group (EC curve) implied by this signature scheme, if any. + /// + /// In DTLS 1.3, ECDSA signature schemes encode the expected curve. + /// Returns `None` for non-ECDSA schemes. + pub fn named_group(&self) -> Option { + match *self { + SignatureScheme::ECDSA_SECP256R1_SHA256 => Some(NamedGroup::Secp256r1), + SignatureScheme::ECDSA_SECP384R1_SHA384 => Some(NamedGroup::Secp384r1), + _ => None, + } + } + + /// Returns the hash algorithm associated with this signature scheme. + pub fn hash_algorithm(&self) -> HashAlgorithm { + match *self { + SignatureScheme::ECDSA_SECP256R1_SHA256 + | SignatureScheme::RSA_PSS_RSAE_SHA256 + | SignatureScheme::RSA_PSS_PSS_SHA256 + | SignatureScheme::RSA_PKCS1_SHA256 => HashAlgorithm::SHA256, + SignatureScheme::ECDSA_SECP384R1_SHA384 + | SignatureScheme::RSA_PSS_RSAE_SHA384 + | SignatureScheme::RSA_PSS_PSS_SHA384 + | SignatureScheme::RSA_PKCS1_SHA384 => HashAlgorithm::SHA384, + SignatureScheme::ECDSA_SECP521R1_SHA512 + | SignatureScheme::RSA_PSS_RSAE_SHA512 + | SignatureScheme::RSA_PSS_PSS_SHA512 + | SignatureScheme::RSA_PKCS1_SHA512 => HashAlgorithm::SHA512, + // Ed25519 and Ed448 have intrinsic hash algorithms + SignatureScheme::ED25519 | SignatureScheme::ED448 => HashAlgorithm::None, + _ => HashAlgorithm::UNKNOWN_DERIVED, + } + } +} + +impl fmt::Debug for SignatureScheme { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + SignatureScheme::ECDSA_SECP256R1_SHA256 => f.write_str("ECDSA_SECP256R1_SHA256"), + SignatureScheme::ECDSA_SECP384R1_SHA384 => f.write_str("ECDSA_SECP384R1_SHA384"), + SignatureScheme::ECDSA_SECP521R1_SHA512 => f.write_str("ECDSA_SECP521R1_SHA512"), + SignatureScheme::ED25519 => f.write_str("ED25519"), + SignatureScheme::ED448 => f.write_str("ED448"), + SignatureScheme::RSA_PSS_RSAE_SHA256 => f.write_str("RSA_PSS_RSAE_SHA256"), + SignatureScheme::RSA_PSS_RSAE_SHA384 => f.write_str("RSA_PSS_RSAE_SHA384"), + SignatureScheme::RSA_PSS_RSAE_SHA512 => f.write_str("RSA_PSS_RSAE_SHA512"), + SignatureScheme::RSA_PSS_PSS_SHA256 => f.write_str("RSA_PSS_PSS_SHA256"), + SignatureScheme::RSA_PSS_PSS_SHA384 => f.write_str("RSA_PSS_PSS_SHA384"), + SignatureScheme::RSA_PSS_PSS_SHA512 => f.write_str("RSA_PSS_PSS_SHA512"), + SignatureScheme::RSA_PKCS1_SHA256 => f.write_str("RSA_PKCS1_SHA256"), + SignatureScheme::RSA_PKCS1_SHA384 => f.write_str("RSA_PKCS1_SHA384"), + SignatureScheme::RSA_PKCS1_SHA512 => f.write_str("RSA_PKCS1_SHA512"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// DTLS 1.3 Cipher Suites +// ============================================================================ + +/// Cipher suites for DTLS 1.3 (RFC 9147). +/// +/// Unlike DTLS 1.2, TLS 1.3 cipher suites only specify the AEAD algorithm +/// and hash function. Key exchange is negotiated separately via key_share. +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Dtls13CipherSuite(u16); + +impl Dtls13CipherSuite { + /// TLS_AES_128_GCM_SHA256. + pub const AES_128_GCM_SHA256: Self = Self(0x1301); + /// TLS_AES_256_GCM_SHA384. + pub const AES_256_GCM_SHA384: Self = Self(0x1302); + /// TLS_CHACHA20_POLY1305_SHA256. + pub const CHACHA20_POLY1305_SHA256: Self = Self(0x1303); + /// TLS_AES_128_CCM_SHA256. + pub const AES_128_CCM_SHA256: Self = Self(0x1304); + /// TLS_AES_128_CCM_8_SHA256 (shorter tag, for constrained devices). + pub const AES_128_CCM_8_SHA256: Self = Self(0x1305); + + /// Convert a wire format u16 value to a `Dtls13CipherSuite`. + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + /// Convert this `Dtls13CipherSuite` to its wire format u16 value. + pub const fn as_u16(&self) -> u16 { + self.0 + } + + /// Returns true if this is not a known DTLS 1.3 cipher suite wire value. + pub const fn is_unknown(&self) -> bool { + !matches!(*self, Self(0x1301..=0x1305)) + } + + /// Parse a `Dtls13CipherSuite` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], Dtls13CipherSuite> { + let (input, value) = be_u16(input)?; + Ok((input, Dtls13CipherSuite::from_u16(value))) + } + + /// Returns the hash algorithm used by this cipher suite. + pub fn hash_algorithm(&self) -> HashAlgorithm { + match *self { + Dtls13CipherSuite::AES_128_GCM_SHA256 + | Dtls13CipherSuite::CHACHA20_POLY1305_SHA256 + | Dtls13CipherSuite::AES_128_CCM_SHA256 + | Dtls13CipherSuite::AES_128_CCM_8_SHA256 => HashAlgorithm::SHA256, + Dtls13CipherSuite::AES_256_GCM_SHA384 => HashAlgorithm::SHA384, + _ => HashAlgorithm::UNKNOWN_DERIVED, + } + } + + /// Returns true if this cipher suite is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// All recognized DTLS 1.3 cipher suites (every non-`Unknown` variant). + pub const fn all() -> &'static [Dtls13CipherSuite] { + &[ + Dtls13CipherSuite::AES_128_GCM_SHA256, + Dtls13CipherSuite::AES_256_GCM_SHA384, + Dtls13CipherSuite::CHACHA20_POLY1305_SHA256, + Dtls13CipherSuite::AES_128_CCM_SHA256, + Dtls13CipherSuite::AES_128_CCM_8_SHA256, + ] + } + + /// Supported DTLS 1.3 cipher suites in preference order. + pub const fn supported() -> &'static [Dtls13CipherSuite] { + &[ + Dtls13CipherSuite::AES_128_GCM_SHA256, + Dtls13CipherSuite::AES_256_GCM_SHA384, + Dtls13CipherSuite::CHACHA20_POLY1305_SHA256, + ] + } + + /// Length in bytes of verify_data for Finished messages. + pub fn verify_data_length(&self) -> usize { + self.hash_algorithm().output_len() + } +} + +impl fmt::Debug for Dtls13CipherSuite { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Dtls13CipherSuite::AES_128_GCM_SHA256 => f.write_str("AES_128_GCM_SHA256"), + Dtls13CipherSuite::AES_256_GCM_SHA384 => f.write_str("AES_256_GCM_SHA384"), + Dtls13CipherSuite::CHACHA20_POLY1305_SHA256 => f.write_str("CHACHA20_POLY1305_SHA256"), + Dtls13CipherSuite::AES_128_CCM_SHA256 => f.write_str("AES_128_CCM_SHA256"), + Dtls13CipherSuite::AES_128_CCM_8_SHA256 => f.write_str("AES_128_CCM_8_SHA256"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// Protocol Version +// ============================================================================ + +/// DTLS protocol version identifiers. +/// +/// Used in record headers and handshake messages for both DTLS 1.2 and 1.3. +#[repr(transparent)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct ProtocolVersion(u16); + +impl ProtocolVersion { + /// DTLS 1.0. + pub const DTLS1_0: Self = Self(0xFEFF); + /// DTLS 1.2. + pub const DTLS1_2: Self = Self(0xFEFD); + /// DTLS 1.3. + pub const DTLS1_3: Self = Self(0xFEFC); + + /// Convert a wire format u16 value to a `ProtocolVersion`. + pub const fn from_u16(value: u16) -> Self { + Self(value) + } + + /// Convert this `ProtocolVersion` to its wire format u16 value. + pub const fn as_u16(&self) -> u16 { + self.0 + } + + /// Returns true if this is not a known DTLS protocol version wire value. + pub const fn is_unknown(&self) -> bool { + !matches!(*self, Self(0xFEFF | 0xFEFD | 0xFEFC)) + } + + /// Parse a `ProtocolVersion` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], ProtocolVersion> { + let (input, version) = be_u16(input)?; + Ok((input, ProtocolVersion::from_u16(version))) + } + + /// Serialize this `ProtocolVersion` to wire format. + pub fn serialize(&self, output: &mut Buf) { + output.extend_from_slice(&self.as_u16().to_be_bytes()); + } +} + +impl fmt::Debug for ProtocolVersion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + ProtocolVersion::DTLS1_0 => f.write_str("DTLS1_0"), + ProtocolVersion::DTLS1_2 => f.write_str("DTLS1_2"), + ProtocolVersion::DTLS1_3 => f.write_str("DTLS1_3"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +// ============================================================================ +// Compression Method +// ============================================================================ + +/// TLS compression methods. +/// +/// Used in ClientHello/ServerHello for both DTLS 1.2 and 1.3. +/// TLS 1.3 only uses Null compression but includes it for compatibility. +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct CompressionMethod(u8); + +impl Default for CompressionMethod { + fn default() -> Self { + Self::Null + } +} + +#[allow(non_upper_case_globals)] +impl CompressionMethod { + /// No compression. + pub const Null: Self = Self(0x00); + /// DEFLATE compression. + pub const Deflate: Self = Self(0x01); + + /// Convert a u8 value to a `CompressionMethod`. + pub const fn from_u8(value: u8) -> Self { + Self(value) + } + + /// Returns true if this compression method is supported by this implementation. + pub fn is_supported(&self) -> bool { + Self::supported().contains(self) + } + + /// All recognized compression methods (every non-`Unknown` variant). + pub const fn all() -> &'static [CompressionMethod; 2] { + &[CompressionMethod::Null, CompressionMethod::Deflate] + } + + /// Supported compression methods. + /// + /// Only null compression is supported. TLS 1.3 / DTLS 1.3 (RFC 8446 + /// §4.1.2) mandates exactly one compression method (null). DEFLATE + /// is recognized by parsing but not accepted. + pub const fn supported() -> &'static [CompressionMethod; 1] { + &[CompressionMethod::Null] + } + + /// Convert this `CompressionMethod` to its u8 value. + pub const fn as_u8(&self) -> u8 { + self.0 + } + + /// Returns true if this is not a known TLS compression method wire value. + pub const fn is_unknown(&self) -> bool { + self.0 > Self::Deflate.0 + } + + /// Parse a `CompressionMethod` from wire format. + pub fn parse(input: &[u8]) -> IResult<&[u8], CompressionMethod> { + let (input, value) = be_u8(input)?; + Ok((input, CompressionMethod::from_u8(value))) + } +} + +impl fmt::Debug for CompressionMethod { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + CompressionMethod::Null => f.write_str("Null"), + CompressionMethod::Deflate => f.write_str("Deflate"), + _ => f.debug_tuple("Unknown").field(&self.0).finish(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn named_group_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(NamedGroup::default().as_u16(), 0); + assert!(NamedGroup::default().is_unknown()); + } + + #[test] + fn named_group_wire_roundtrip() { + for group in NamedGroup::all() { + assert_eq!(NamedGroup::from_u16(group.as_u16()), *group); + assert!(!group.is_unknown()); + } + + let unknown = NamedGroup::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn named_group_debug_stays_enum_like() { + assert_eq!(format!("{:?}", NamedGroup::Secp256r1), "Secp256r1"); + assert_eq!(format!("{:?}", NamedGroup::X25519), "X25519"); + assert_eq!( + format!("{:?}", NamedGroup::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn hash_algorithm_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(HashAlgorithm::default().as_u8(), 0); + assert_eq!(HashAlgorithm::default(), HashAlgorithm::None); + } + + #[test] + fn hash_algorithm_wire_roundtrip() { + let known = [ + (0, HashAlgorithm::None), + (1, HashAlgorithm::MD5), + (2, HashAlgorithm::SHA1), + (3, HashAlgorithm::SHA224), + (4, HashAlgorithm::SHA256), + (5, HashAlgorithm::SHA384), + (6, HashAlgorithm::SHA512), + ]; + + for (wire, algorithm) in known { + assert_eq!(HashAlgorithm::from_u8(wire), algorithm); + assert_eq!(algorithm.as_u8(), wire); + assert!(!algorithm.is_unknown()); + } + + let unknown = HashAlgorithm::from_u8(7); + assert_eq!(unknown.as_u8(), 7); + assert!(unknown.is_unknown()); + } + + #[test] + fn hash_algorithm_output_len() { + assert_eq!(HashAlgorithm::None.output_len(), 0); + assert_eq!(HashAlgorithm::MD5.output_len(), 16); + assert_eq!(HashAlgorithm::SHA1.output_len(), 20); + assert_eq!(HashAlgorithm::SHA224.output_len(), 28); + assert_eq!(HashAlgorithm::SHA256.output_len(), 32); + assert_eq!(HashAlgorithm::SHA384.output_len(), 48); + assert_eq!(HashAlgorithm::SHA512.output_len(), 64); + assert_eq!(HashAlgorithm::from_u8(7).output_len(), 0); + } + + #[test] + fn hash_algorithm_debug_stays_enum_like() { + assert_eq!(format!("{:?}", HashAlgorithm::None), "None"); + assert_eq!(format!("{:?}", HashAlgorithm::SHA256), "SHA256"); + assert_eq!(format!("{:?}", HashAlgorithm::from_u8(7)), "Unknown(7)"); + } + + #[test] + fn signature_algorithm_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(SignatureAlgorithm::default().as_u8(), 0); + assert_eq!(SignatureAlgorithm::default(), SignatureAlgorithm::Anonymous); + } + + #[test] + fn signature_algorithm_wire_roundtrip() { + let known = [ + (0, SignatureAlgorithm::Anonymous), + (1, SignatureAlgorithm::RSA), + (2, SignatureAlgorithm::DSA), + (3, SignatureAlgorithm::ECDSA), + ]; + + for (wire, algorithm) in known { + assert_eq!(SignatureAlgorithm::from_u8(wire), algorithm); + assert_eq!(algorithm.as_u8(), wire); + assert!(!algorithm.is_unknown()); + } + + let unknown = SignatureAlgorithm::from_u8(4); + assert_eq!(unknown.as_u8(), 4); + assert!(unknown.is_unknown()); + } + + #[test] + fn signature_algorithm_debug_stays_enum_like() { + assert_eq!(format!("{:?}", SignatureAlgorithm::Anonymous), "Anonymous"); + assert_eq!(format!("{:?}", SignatureAlgorithm::ECDSA), "ECDSA"); + assert_eq!( + format!("{:?}", SignatureAlgorithm::from_u8(4)), + "Unknown(4)" + ); + } + + #[test] + fn compression_method_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(CompressionMethod::default().as_u8(), 0); + assert_eq!(CompressionMethod::default(), CompressionMethod::Null); + } + + #[test] + fn compression_method_wire_roundtrip() { + let known = [ + (0x00, CompressionMethod::Null), + (0x01, CompressionMethod::Deflate), + ]; + + for (wire, method) in known { + assert_eq!(CompressionMethod::from_u8(wire), method); + assert_eq!(method.as_u8(), wire); + assert!(!method.is_unknown()); + } + + let unknown = CompressionMethod::from_u8(0x02); + assert_eq!(unknown.as_u8(), 0x02); + assert!(unknown.is_unknown()); + } + + #[test] + fn compression_method_debug_stays_enum_like() { + assert_eq!(format!("{:?}", CompressionMethod::Null), "Null"); + assert_eq!(format!("{:?}", CompressionMethod::Deflate), "Deflate"); + assert_eq!( + format!("{:?}", CompressionMethod::from_u8(0x02)), + "Unknown(2)" + ); + } + + #[test] + fn content_type_newtype_shape() { + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(ContentType::default().as_u8(), 0); + assert!(ContentType::default().is_unknown()); + } + + #[test] + fn content_type_wire_roundtrip() { + let known = [ + (20, ContentType::ChangeCipherSpec), + (21, ContentType::Alert), + (22, ContentType::Handshake), + (23, ContentType::ApplicationData), + (26, ContentType::Ack), + ]; + + for (wire, content_type) in known { + assert_eq!(ContentType::from_u8(wire), content_type); + assert_eq!(content_type.as_u8(), wire); + assert!(!content_type.is_unknown()); + } + + let unknown = ContentType::from_u8(24); + assert_eq!(unknown.as_u8(), 24); + assert!(unknown.is_unknown()); + } + + #[test] + fn content_type_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", ContentType::ChangeCipherSpec), + "ChangeCipherSpec" + ); + assert_eq!(format!("{:?}", ContentType::Handshake), "Handshake"); + assert_eq!(format!("{:?}", ContentType::from_u8(24)), "Unknown(24)"); + } + + #[test] + fn signature_scheme_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(SignatureScheme::default().as_u16(), 0); + assert!(SignatureScheme::default().is_unknown()); + } + + #[test] + fn signature_scheme_wire_roundtrip() { + for scheme in SignatureScheme::all() { + assert_eq!(SignatureScheme::from_u16(scheme.as_u16()), *scheme); + assert!(!scheme.is_unknown()); + } + + let unknown = SignatureScheme::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn signature_scheme_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", SignatureScheme::ECDSA_SECP256R1_SHA256), + "ECDSA_SECP256R1_SHA256" + ); + assert_eq!( + format!("{:?}", SignatureScheme::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn dtls13_cipher_suite_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(Dtls13CipherSuite::default().as_u16(), 0); + assert!(Dtls13CipherSuite::default().is_unknown()); + } + + #[test] + fn dtls13_cipher_suite_wire_roundtrip() { + for suite in Dtls13CipherSuite::all() { + assert_eq!(Dtls13CipherSuite::from_u16(suite.as_u16()), *suite); + assert!(!suite.is_unknown()); + } + + let unknown = Dtls13CipherSuite::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn dtls13_cipher_suite_debug_stays_enum_like() { + assert_eq!( + format!("{:?}", Dtls13CipherSuite::AES_128_GCM_SHA256), + "AES_128_GCM_SHA256" + ); + assert_eq!( + format!("{:?}", Dtls13CipherSuite::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn protocol_version_newtype_shape() { + assert_eq!(std::mem::size_of::(), 2); + assert_eq!(ProtocolVersion::default().as_u16(), 0); + assert!(ProtocolVersion::default().is_unknown()); + } + + #[test] + fn protocol_version_wire_roundtrip() { + let known = [ + (0xFEFF, ProtocolVersion::DTLS1_0), + (0xFEFD, ProtocolVersion::DTLS1_2), + (0xFEFC, ProtocolVersion::DTLS1_3), + ]; + + for (wire, version) in known { + assert_eq!(ProtocolVersion::from_u16(wire), version); + assert_eq!(version.as_u16(), wire); + assert!(!version.is_unknown()); + } + + let unknown = ProtocolVersion::from_u16(0xFFFF); + assert_eq!(unknown.as_u16(), 0xFFFF); + assert!(unknown.is_unknown()); + } + + #[test] + fn protocol_version_debug_stays_enum_like() { + assert_eq!(format!("{:?}", ProtocolVersion::DTLS1_2), "DTLS1_2"); + assert_eq!( + format!("{:?}", ProtocolVersion::from_u16(0xFFFF)), + "Unknown(65535)" + ); + } + + #[test] + fn random_parse() { + let data = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, + 0x1D, 0x1E, 0x1F, 0x20, + ]; + + let expected = Random { bytes: data }; + + let (_, parsed) = Random::parse(&data).unwrap(); + assert_eq!(parsed, expected); + } + + #[test] + fn random_serialize() { + let random = Random { + bytes: [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, + 0x1D, 0x1E, 0x1F, 0x20, + ], + }; + + let mut serialized = Buf::new(); + random.serialize(&mut serialized); + + assert_eq!(&*serialized, &random.bytes); + } + + #[test] + fn compression_supported_has_only_null() { + let supported = CompressionMethod::supported(); + assert_eq!( + supported, + &[CompressionMethod::Null], + "Only Null compression should be supported" + ); + } + + #[test] + fn signature_scheme_named_group_ecdsa() { + assert_eq!( + SignatureScheme::ECDSA_SECP256R1_SHA256.named_group(), + Some(NamedGroup::Secp256r1) + ); + assert_eq!( + SignatureScheme::ECDSA_SECP384R1_SHA384.named_group(), + Some(NamedGroup::Secp384r1) + ); + } + + #[test] + fn signature_scheme_named_group_non_ecdsa() { + assert_eq!(SignatureScheme::RSA_PSS_RSAE_SHA256.named_group(), None); + assert_eq!(SignatureScheme::ED25519.named_group(), None); + assert_eq!(SignatureScheme::ECDSA_SECP521R1_SHA512.named_group(), None); + assert_eq!(SignatureScheme::from_u16(0xFFFF).named_group(), None); + } + + #[test] + fn random_parse_roundtrip() { + let data = [ + 0x5F, 0x37, 0xA9, 0x4B, // could be gmt_unix_time in 1.2 + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, + ]; + + let (_, parsed) = Random::parse(&data).unwrap(); + let mut serialized = Buf::new(); + parsed.serialize(&mut serialized); + + assert_eq!(&*serialized, &data[..]); + } +} diff --git a/third_party/dimpl/src/util.rs b/third_party/dimpl/src/util.rs new file mode 100644 index 0000000..68efa90 --- /dev/null +++ b/third_party/dimpl/src/util.rs @@ -0,0 +1,119 @@ +use arrayvec::ArrayVec; +use nom::error::{ErrorKind, ParseError, make_error}; +use nom::{Err, IResult, Input, Parser}; + +/// A combinator that parses items using the provided parser but only collects +/// items that pass a filter predicate. Allows zero matches. +#[inline(always)] +pub fn many0( + mut parser: F, + predicate: P, +) -> impl FnMut(I) -> IResult, E> +where + I: Clone + Input, + F: Parser, + P: Fn(&O) -> bool, + E: ParseError, +{ + move |mut i: I| { + let mut acc = ArrayVec::new(); + + loop { + let len = i.input_len(); + if len == 0 { + break; + } + + match parser.parse(i.clone()) { + Err(Err::Error(_)) => break, + Err(e) => return Err(e), + Ok((i1, o)) => { + // infinite loop check: the parser must always consume + if i1.input_len() == len { + return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many0))); + } + + i = i1; + // Only collect items that pass the filter + if predicate(&o) && acc.try_push(o).is_err() { + return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many0))); + } + } + } + } + + Ok((i, acc)) + } +} + +/// A combinator that parses items using the provided parser but only collects +/// items that pass a filter predicate. Requires at least one item to pass the filter. +#[inline(always)] +pub fn many1( + mut parser: F, + predicate: P, +) -> impl FnMut(I) -> IResult, E> +where + I: Clone + Input, + F: Parser, + P: Fn(&O) -> bool, + E: ParseError, +{ + move |mut i: I| { + let mut acc = ArrayVec::new(); + let original_input = i.clone(); + + loop { + let len = i.input_len(); + if len == 0 { + break; + } + + match parser.parse(i.clone()) { + Err(Err::Error(_)) => break, + Err(e) => return Err(e), + Ok((i1, o)) => { + // infinite loop check: the parser must always consume + if i1.input_len() == len { + return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1))); + } + + i = i1; + // Only collect items that pass the filter + if predicate(&o) && acc.try_push(o).is_err() { + return Err(Err::Error(E::from_error_kind(i, ErrorKind::Many1))); + } + } + } + } + + // Require at least one item to pass the filter + if acc.is_empty() { + Err(Err::Error(E::from_error_kind( + original_input, + ErrorKind::Many1, + ))) + } else { + Ok((i, acc)) + } + } +} + +pub fn be_u48>(input: I) -> IResult +where + I: Input, +{ + let bound: usize = 6; + + if input.input_len() < bound { + Err(Err::Error(make_error(input, ErrorKind::Eof))) + } else { + let mut res = 0u64; + + for byte in input.iter_elements().take(bound) { + res = (res << 8) + byte as u64; + } + + Ok((input.take_from(bound), res)) + } +} diff --git a/third_party/dimpl/src/window.rs b/third_party/dimpl/src/window.rs new file mode 100644 index 0000000..66b93e0 --- /dev/null +++ b/third_party/dimpl/src/window.rs @@ -0,0 +1,143 @@ +/// Sliding replay window for DTLS record sequence numbers. +/// +/// Maintains the latest accepted sequence number and a 64-bit bitmap of the +/// last 64 seen sequence numbers to reject duplicates and old records. +/// +/// Each epoch should have its own `ReplayWindow` instance. The caller is +/// responsible for routing records to the correct per-epoch window. +#[derive(Debug, Default)] +pub struct ReplayWindow { + max_seq: u64, + window: u64, +} + +impl ReplayWindow { + pub fn new() -> Self { + Self::default() + } + + /// Check if the given sequence number is acceptable (not a replay, not too old). + /// Read-only: does not modify the window state. + pub fn check(&self, seqno: u64) -> bool { + if seqno > self.max_seq { + true + } else { + let offset = self.max_seq - seqno; + if offset >= 64 { + return false; // too old + } + let mask = 1u64 << offset; + (self.window & mask) == 0 // false if duplicate + } + } + + /// Update the window state to record that `seqno` has been received. + /// Must only be called after the record has been authenticated (decrypted successfully). + pub fn update(&mut self, seqno: u64) { + if seqno > self.max_seq { + let delta = seqno - self.max_seq; + if delta > 63 { + // Jump exceeds window size: clear entirely, only newest is seen + self.window = 1; + } else { + self.window <<= delta; + self.window |= 1; // mark newest as seen + } + self.max_seq = seqno; + } else { + let offset = self.max_seq - seqno; + if offset < 64 { + self.window |= 1u64 << offset; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Helper: check and update in one step (simulates authenticated record). + fn check_and_update(w: &mut ReplayWindow, seqno: u64) -> bool { + if w.check(seqno) { + w.update(seqno); + true + } else { + false + } + } + + #[test] + fn accepts_fresh_and_rejects_duplicate() { + let mut w = ReplayWindow::new(); + assert!(check_and_update(&mut w, 1)); + assert!(!check_and_update(&mut w, 1)); // duplicate + assert!(check_and_update(&mut w, 2)); // next fresh + } + + #[test] + fn accepts_out_of_order_within_window() { + let mut w = ReplayWindow::new(); + assert!(check_and_update(&mut w, 10)); // establish max=10 + assert!(check_and_update(&mut w, 8)); // unseen within 64 + assert!(!check_and_update(&mut w, 8)); // duplicate now + assert!(check_and_update(&mut w, 9)); // unseen within 64 + } + + #[test] + fn rejects_too_old() { + let mut w = ReplayWindow::new(); + assert!(check_and_update(&mut w, 100)); + // offset = 64 -> too old + assert!(!check_and_update(&mut w, 36)); + // offset = 63 -> allowed once + assert!(check_and_update(&mut w, 37)); + } + + #[test] + fn handles_large_jump_and_window_shift() { + let mut w = ReplayWindow::new(); + assert!(check_and_update(&mut w, 1)); + // Large forward jump clears the window entirely + assert!(check_and_update(&mut w, 80)); + // Within window of new max and unseen + assert!(check_and_update(&mut w, 79)); + // Too old relative to new max + assert!(!check_and_update(&mut w, 15)); + } + + #[test] + fn large_jump_does_not_leave_stale_bits() { + let mut w = ReplayWindow::new(); + assert!(check_and_update(&mut w, 0)); + // Jump of 200 exceeds window size (64). The window must be fully + // cleared so no stale bits from seq 0 remain. + assert!(check_and_update(&mut w, 200)); + // seq 137 is within the window (offset = 200 - 137 = 63) and was + // never seen, so it must be accepted. + assert!(check_and_update(&mut w, 137)); + } + + #[test] + fn check_does_not_modify_window() { + let mut w = ReplayWindow::new(); + w.update(10); + // check alone should not change state + assert!(w.check(11)); + assert!(w.check(11)); // still acceptable because update was never called + w.update(11); + assert!(!w.check(11)); // now it's a duplicate + } + + #[test] + fn failed_auth_does_not_advance_window() { + let mut w = ReplayWindow::new(); + w.update(5); + // Simulate receiving seq 200 that passes check but fails authentication + assert!(w.check(200)); + // Do NOT call update (authentication failed) + // Legitimate packet at seq 6 should still be accepted + assert!(w.check(6)); + w.update(6); + } +} diff --git a/third_party/dimpl/tests/auto/common.rs b/third_party/dimpl/tests/auto/common.rs new file mode 100644 index 0000000..ef9babe --- /dev/null +++ b/third_party/dimpl/tests/auto/common.rs @@ -0,0 +1,90 @@ +//! Shared helpers for auto-negotiation integration tests. + +#![allow(unused)] + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Output, SrtpProfile}; + +/// Collected outputs from polling an endpoint to `Timeout`. +#[derive(Default, Debug)] +pub struct DrainedOutputs { + pub packets: Vec>, + pub connected: bool, + pub peer_cert: Option>, + pub keying_material: Option<(Vec, SrtpProfile)>, + pub app_data: Vec>, + pub timeout: Option, + pub close_notify: bool, +} + +/// Poll until `Timeout`, collecting only packets. +pub fn collect_packets(endpoint: &mut Dtls) -> Vec> { + let mut out = Vec::new(); + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => out.push(p.to_vec()), + Output::Timeout(_) => break, + _ => {} + } + } + out +} + +/// Poll until `Timeout`, collecting everything. +pub fn drain_outputs(endpoint: &mut Dtls) -> DrainedOutputs { + let mut result = DrainedOutputs::default(); + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => result.packets.push(p.to_vec()), + Output::Connected => result.connected = true, + Output::PeerCert(cert) => result.peer_cert = Some(cert.to_vec()), + Output::KeyingMaterial(km, profile) => { + result.keying_material = Some((km.to_vec(), profile)); + } + Output::ApplicationData(data) => result.app_data.push(data.to_vec()), + Output::CloseNotify => result.close_notify = true, + Output::Timeout(t) => { + result.timeout = Some(t); + break; + } + _ => {} + } + } + result +} + +/// Deliver a slice of packets to a destination endpoint. +pub fn deliver_packets(packets: &[Vec], dest: &mut Dtls) { + for p in packets { + let _ = dest.handle_packet(p); + } +} + +/// Create a default config. +pub fn default_config() -> Arc { + Arc::new(Config::builder().build().expect("Failed to build config")) +} + +/// Create a config with the server cookie exchange disabled. +pub fn no_cookie_config() -> Arc { + Arc::new( + Config::builder() + .use_server_cookie(false) + .build() + .expect("Failed to build config"), + ) +} + +/// Create a config with a small MTU to force ClientHello fragmentation. +pub fn small_mtu_config(mtu: usize) -> Arc { + Arc::new( + Config::builder() + .mtu(mtu) + .build() + .expect("Failed to build config"), + ) +} diff --git a/third_party/dimpl/tests/auto/cross_matrix.rs b/third_party/dimpl/tests/auto/cross_matrix.rs new file mode 100644 index 0000000..33795aa --- /dev/null +++ b/third_party/dimpl/tests/auto/cross_matrix.rs @@ -0,0 +1,441 @@ +//! Cross-version matrix tests for DTLS auto-sense. +//! +//! Tests every combination of (client_version × server_version × mtu) to +//! verify that auto-sense, explicit 1.2, and explicit 1.3 all interoperate +//! correctly, including with fragmented ClientHellos. +//! +//! Matrix (expected outcome): +//! +//! | Client \ Server | auto | 1.2 | 1.3 | +//! |-----------------|--------|--------|--------| +//! | auto | 1.3 | 1.2 | 1.3 | +//! | 1.2 | 1.2 | 1.2 | FAIL | +//! | 1.3 | 1.3 | FAIL | 1.3 | +//! +//! Each passing combination is tested at normal MTU and at small MTU (200) +//! to exercise fragmented handshake messages. + +#![cfg(feature = "rcgen")] + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::certificate::generate_self_signed_certificate; +use dimpl::{Config, Dtls, ProtocolVersion, SrtpProfile}; + +use crate::common::*; + +// ── Helpers ──────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Copy)] +enum Ver { + Auto, + V12, + V13, +} + +fn make_endpoint(ver: Ver, config: Arc, active: bool) -> Dtls { + let cert = generate_self_signed_certificate().unwrap(); + let now = Instant::now(); + let mut d = match ver { + Ver::Auto => Dtls::new_auto(config, cert, now), + Ver::V12 => Dtls::new_12(config, cert, now), + Ver::V13 => Dtls::new_13(config, cert, now), + }; + if active { + d.set_active(true); + } + d +} + +fn cfg(mtu: usize) -> Arc { + Arc::new(Config::builder().mtu(mtu).build().unwrap()) +} + +/// Drive a handshake to completion. Returns `None` if it fails to connect +/// within the iteration limit (expected for incompatible combinations). +fn try_handshake( + client: &mut Dtls, + server: &mut Dtls, +) -> Option<(ProtocolVersion, ProtocolVersion)> { + let mut now = Instant::now(); + let mut cc = false; + let mut sc = false; + + for _ in 0..80 { + if client.handle_timeout(now).is_err() { + return None; + } + if server.handle_timeout(now).is_err() { + return None; + } + + let co = drain_outputs(client); + let so = drain_outputs(server); + + if co.connected { + cc = true; + } + if so.connected { + sc = true; + } + + // Deliver packets, ignoring errors (incompatible version → errors are expected) + for p in &co.packets { + let _ = server.handle_packet(p); + } + for p in &so.packets { + let _ = client.handle_packet(p); + } + + if cc && sc { + return Some(( + client.protocol_version().unwrap(), + server.protocol_version().unwrap(), + )); + } + + now += Duration::from_millis(10); + } + + None +} + +/// Helper: successful handshake + verify versions + data exchange. +fn assert_connects(client_ver: Ver, server_ver: Ver, mtu: usize, expected_proto: ProtocolVersion) { + let _ = env_logger::try_init(); + + let client_cfg = cfg(mtu); + let server_cfg = cfg(mtu); + + let mut client = make_endpoint(client_ver, client_cfg, true); + let mut server = make_endpoint(server_ver, server_cfg, false); + + let result = try_handshake(&mut client, &mut server); + let (cv, sv) = result.unwrap_or_else(|| { + panic!( + "{:?} client (mtu={}) → {:?} server should connect as {:?}", + client_ver, mtu, server_ver, expected_proto + ) + }); + + assert_eq!( + cv, expected_proto, + "{:?} client version mismatch (mtu={})", + client_ver, mtu + ); + assert_eq!( + sv, expected_proto, + "{:?} server version mismatch (mtu={})", + server_ver, mtu + ); + + // Verify bidirectional data exchange. + let msg_c = b"from client"; + let msg_s = b"from server"; + let mut now = Instant::now() + Duration::from_millis(500); + + client.send_application_data(msg_c).unwrap(); + server.send_application_data(msg_s).unwrap(); + + for _ in 0..20 { + client.handle_timeout(now).unwrap(); + server.handle_timeout(now).unwrap(); + + let co = drain_outputs(&mut client); + let so = drain_outputs(&mut server); + + deliver_packets(&co.packets, &mut server); + deliver_packets(&so.packets, &mut client); + + let co2 = drain_outputs(&mut client); + let so2 = drain_outputs(&mut server); + + if so2.app_data.iter().any(|d| d == msg_c) && co2.app_data.iter().any(|d| d == msg_s) { + return; // success + } + + now += Duration::from_millis(10); + } + + panic!( + "{:?} client → {:?} server (mtu={}): data exchange failed", + client_ver, server_ver, mtu + ); +} + +/// Helper: verify that an incompatible combination does NOT connect. +fn assert_fails(client_ver: Ver, server_ver: Ver, mtu: usize) { + let _ = env_logger::try_init(); + + let client_cfg = cfg(mtu); + let server_cfg = cfg(mtu); + + let mut client = make_endpoint(client_ver, client_cfg, true); + let mut server = make_endpoint(server_ver, server_cfg, false); + + let result = try_handshake(&mut client, &mut server); + assert!( + result.is_none(), + "{:?} client (mtu={}) → {:?} server should NOT connect, but got {:?}", + client_ver, + mtu, + server_ver, + result + ); +} + +// ── Normal MTU (1150) ────────────────────────────────────────────────── + +const NORMAL: usize = 1150; + +// auto × auto → 1.3 + +#[test] +fn cross_auto_auto_normal() { + assert_connects(Ver::Auto, Ver::Auto, NORMAL, ProtocolVersion::DTLS1_3); +} + +// auto × 1.2 → 1.2 + +#[test] +fn cross_auto_v12_normal() { + assert_connects(Ver::Auto, Ver::V12, NORMAL, ProtocolVersion::DTLS1_2); +} + +// auto × 1.3 → 1.3 + +#[test] +fn cross_auto_v13_normal() { + assert_connects(Ver::Auto, Ver::V13, NORMAL, ProtocolVersion::DTLS1_3); +} + +// 1.2 × auto → 1.2 + +#[test] +fn cross_v12_auto_normal() { + assert_connects(Ver::V12, Ver::Auto, NORMAL, ProtocolVersion::DTLS1_2); +} + +// 1.2 × 1.2 → 1.2 + +#[test] +fn cross_v12_v12_normal() { + assert_connects(Ver::V12, Ver::V12, NORMAL, ProtocolVersion::DTLS1_2); +} + +// 1.2 × 1.3 → FAIL + +#[test] +fn cross_v12_v13_normal() { + assert_fails(Ver::V12, Ver::V13, NORMAL); +} + +// 1.3 × auto → 1.3 + +#[test] +fn cross_v13_auto_normal() { + assert_connects(Ver::V13, Ver::Auto, NORMAL, ProtocolVersion::DTLS1_3); +} + +// 1.3 × 1.2 → FAIL + +#[test] +fn cross_v13_v12_normal() { + assert_fails(Ver::V13, Ver::V12, NORMAL); +} + +// 1.3 × 1.3 → 1.3 + +#[test] +fn cross_v13_v13_normal() { + assert_connects(Ver::V13, Ver::V13, NORMAL, ProtocolVersion::DTLS1_3); +} + +// ── Small MTU (200) — fragmented ClientHello ─────────────────────────── + +const FRAG: usize = 200; + +// auto × auto → 1.3 + +#[test] +fn cross_auto_auto_frag() { + assert_connects(Ver::Auto, Ver::Auto, FRAG, ProtocolVersion::DTLS1_3); +} + +// auto × 1.2 → 1.2 + +#[test] +fn cross_auto_v12_frag() { + assert_connects(Ver::Auto, Ver::V12, FRAG, ProtocolVersion::DTLS1_2); +} + +// auto × 1.3 → 1.3 + +#[test] +fn cross_auto_v13_frag() { + assert_connects(Ver::Auto, Ver::V13, FRAG, ProtocolVersion::DTLS1_3); +} + +// 1.2 × auto → 1.2 + +#[test] +fn cross_v12_auto_frag() { + assert_connects(Ver::V12, Ver::Auto, FRAG, ProtocolVersion::DTLS1_2); +} + +// 1.2 × 1.2 → 1.2 + +#[test] +fn cross_v12_v12_frag() { + assert_connects(Ver::V12, Ver::V12, FRAG, ProtocolVersion::DTLS1_2); +} + +// 1.2 × 1.3 → FAIL + +#[test] +fn cross_v12_v13_frag() { + assert_fails(Ver::V12, Ver::V13, FRAG); +} + +// 1.3 × auto → 1.3 + +#[test] +fn cross_v13_auto_frag() { + assert_connects(Ver::V13, Ver::Auto, FRAG, ProtocolVersion::DTLS1_3); +} + +// 1.3 × 1.2 → FAIL + +#[test] +fn cross_v13_v12_frag() { + assert_fails(Ver::V13, Ver::V12, FRAG); +} + +// 1.3 × 1.3 → 1.3 + +#[test] +fn cross_v13_v13_frag() { + assert_connects(Ver::V13, Ver::V13, FRAG, ProtocolVersion::DTLS1_3); +} + +// ── Very small MTU (100) — heavy fragmentation ──────────────────────── + +const HEAVY: usize = 150; + +#[test] +fn cross_auto_auto_heavy() { + assert_connects(Ver::Auto, Ver::Auto, HEAVY, ProtocolVersion::DTLS1_3); +} + +#[test] +fn cross_v13_auto_heavy() { + assert_connects(Ver::V13, Ver::Auto, HEAVY, ProtocolVersion::DTLS1_3); +} + +#[test] +fn cross_v13_v13_heavy() { + assert_connects(Ver::V13, Ver::V13, HEAVY, ProtocolVersion::DTLS1_3); +} + +#[test] +fn cross_v12_auto_heavy() { + assert_connects(Ver::V12, Ver::Auto, HEAVY, ProtocolVersion::DTLS1_2); +} + +#[test] +fn cross_v12_v12_heavy() { + assert_connects(Ver::V12, Ver::V12, HEAVY, ProtocolVersion::DTLS1_2); +} + +#[test] +fn cross_auto_v13_heavy() { + assert_connects(Ver::Auto, Ver::V13, HEAVY, ProtocolVersion::DTLS1_3); +} + +#[test] +fn cross_auto_v12_heavy() { + assert_connects(Ver::Auto, Ver::V12, HEAVY, ProtocolVersion::DTLS1_2); +} + +// ── Keying material tests (fragmented) ───────────────────────────────── + +fn assert_keying_material(client_ver: Ver, server_ver: Ver, mtu: usize) { + let _ = env_logger::try_init(); + + let client_cfg = cfg(mtu); + let server_cfg = cfg(mtu); + + let mut client = make_endpoint(client_ver, client_cfg, true); + let mut server = make_endpoint(server_ver, server_cfg, false); + + let mut now = Instant::now(); + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..80 { + client.handle_timeout(now).unwrap(); + server.handle_timeout(now).unwrap(); + + let co = drain_outputs(&mut client); + let so = drain_outputs(&mut server); + + if let Some(km) = co.keying_material { + client_km = Some(km); + } + if let Some(km) = so.keying_material { + server_km = Some(km); + } + + deliver_packets(&co.packets, &mut server); + deliver_packets(&so.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let ckm = client_km.expect("Client should have keying material"); + let skm = server_km.expect("Server should have keying material"); + + assert_eq!(ckm.0, skm.0, "Keying material should match"); + assert_eq!(ckm.1, skm.1, "SRTP profile should match"); + assert!(!ckm.0.is_empty()); +} + +#[test] +fn keying_auto_auto_frag() { + assert_keying_material(Ver::Auto, Ver::Auto, FRAG); +} + +#[test] +fn keying_v13_auto_frag() { + assert_keying_material(Ver::V13, Ver::Auto, FRAG); +} + +#[test] +fn keying_v12_auto_frag() { + assert_keying_material(Ver::V12, Ver::Auto, FRAG); +} + +#[test] +fn keying_auto_v13_frag() { + assert_keying_material(Ver::Auto, Ver::V13, FRAG); +} + +#[test] +fn keying_auto_v12_frag() { + assert_keying_material(Ver::Auto, Ver::V12, FRAG); +} + +#[test] +fn keying_v13_v13_frag() { + assert_keying_material(Ver::V13, Ver::V13, FRAG); +} + +#[test] +fn keying_v12_v12_frag() { + assert_keying_material(Ver::V12, Ver::V12, FRAG); +} diff --git a/third_party/dimpl/tests/auto/handshake.rs b/third_party/dimpl/tests/auto/handshake.rs new file mode 100644 index 0000000..920d169 --- /dev/null +++ b/third_party/dimpl/tests/auto/handshake.rs @@ -0,0 +1,714 @@ +//! Auto-negotiation handshake integration tests. +//! +//! Tests the `Dtls::new_auto()` + `set_active(true)` (client) path against +//! explicit DTLS 1.2, DTLS 1.3, and auto-sense servers. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Dtls, Error, Output}; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls13_server() { + //! An auto-sensing client should complete a full handshake against an + //! explicit DTLS 1.3 server. + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Auto client should connect to DTLS 1.3 server" + ); + assert!( + server_connected, + "DTLS 1.3 server should connect to auto client" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls13_server_keying_material() { + //! Verify that an auto-client and DTLS 1.3 server derive identical + //! SRTP keying material. + use dimpl::SrtpProfile; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + assert_eq!( + client_km.0, server_km.0, + "Client and server keying material should match" + ); + assert_eq!( + client_km.1, server_km.1, + "Client and server SRTP profile should match" + ); + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_auto_server() { + //! Both sides use auto-sense. They should negotiate DTLS 1.3 (the + //! hybrid CH includes supported_versions with DTLS 1.3 first). + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Auto client should connect to auto server" + ); + assert!( + server_connected, + "Auto server should connect to auto client" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls12_server() { + //! An auto-sensing client against an explicit DTLS 1.2 server. + //! The server sends HelloVerifyRequest, triggering the 1.2 fork. + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Auto client should connect to DTLS 1.2 server" + ); + assert!( + server_connected, + "DTLS 1.2 server should connect to auto client" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls12_server_keying_material() { + //! Verify that an auto-client and DTLS 1.2 server derive identical + //! SRTP keying material after HVR-based version negotiation. + use dimpl::SrtpProfile; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + assert_eq!( + client_km.0, server_km.0, + "Client and server keying material should match" + ); + assert_eq!( + client_km.1, server_km.1, + "Client and server SRTP profile should match" + ); + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls13_server_application_data() { + //! After handshake, auto-client and DTLS 1.3 server can exchange + //! application data in both directions. + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Complete the handshake + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected && server_connected, + "Handshake should complete" + ); + + // Send data client -> server + let msg = b"hello from auto client"; + client.send_application_data(msg).expect("client send"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d == msg), + "Server should receive client's application data" + ); + + // Send data server -> client + let reply = b"hello from server"; + server.send_application_data(reply).expect("server send"); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.app_data.iter().any(|d| d == reply), + "Client should receive server's application data" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls12_server_no_cookie() { + //! An auto-sensing client against a DTLS 1.2 server that skips + //! HelloVerifyRequest (use_server_cookie = false). The server sends + //! ServerHello directly. + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let client_config = default_config(); + let server_config = no_cookie_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(server_config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Auto client should connect to DTLS 1.2 server (no cookie)" + ); + assert!( + server_connected, + "DTLS 1.2 server (no cookie) should connect to auto client" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_to_dtls13_server_no_cookie() { + //! An auto-sensing client against a DTLS 1.3 server that skips + //! HelloRetryRequest cookie exchange (use_server_cookie = false). + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let client_config = default_config(); + let server_config = no_cookie_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(server_config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Auto client should connect to DTLS 1.3 server (no cookie)" + ); + assert!( + server_connected, + "DTLS 1.3 server (no cookie) should connect to auto client" + ); +} + +/// Auto-sense client defers the hybrid ClientHello when the poll buffer +/// is too small, and emits it on the next poll with a large enough buffer. +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_poll_output_undersized_buffer() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let cert = generate_self_signed_certificate().expect("gen cert"); + let config = default_config(); + + let now = Instant::now(); + let mut client = Dtls::new_auto(config, cert, now); + client.set_active(true); + + // Trigger the hybrid ClientHello + client.handle_timeout(now).expect("handle_timeout"); + + // Poll with a buffer that is too small for the wire packet. + // Before the fix this would panic with an index-out-of-bounds. + let mut tiny_buf = [0u8; 4]; + let output = client.poll_output(&mut tiny_buf); + + // Should report the required size while keeping the packet deferred. + assert!( + matches!(output, Output::BufferTooSmall { .. }), + "undersized buffer should yield BufferTooSmall, got: {output:?}" + ); + + // Now poll with a large buffer — the deferred packet should come through. + let mut big_buf = vec![0u8; 2048]; + let output = client.poll_output(&mut big_buf); + assert!( + matches!(output, Output::Packet(_)), + "large buffer should yield Packet, got: {output:?}" + ); +} + +/// Auto-sense client returns an error when the server response cannot be +/// identified as any known DTLS version. +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_rejects_unknown_version_response() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let cert = generate_self_signed_certificate().expect("gen cert"); + let config = default_config(); + + let now = Instant::now(); + let mut client = Dtls::new_auto(config, cert, now); + client.set_active(true); + + // Trigger the hybrid ClientHello + client.handle_timeout(now).expect("handle_timeout"); + drain_outputs(&mut client); + + // Feed a garbage "server response" that won't parse as any known version. + // server_hello_version returns Unknown for non-handshake content types. + let garbage = vec![0xFF, 0x00, 0x01, 0x02]; + let result = client.handle_packet(&garbage); + + assert!( + result.is_err(), + "Unknown version response should be an error" + ); + match result.unwrap_err() { + Error::UnexpectedMessage(dimpl::UnexpectedMessageError::UnrecognizedAutoServerResponse) => { + } + other => panic!("expected UnexpectedMessage, got: {other:?}"), + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_protocol_version_after_negotiating_dtls13() { + //! After completing a handshake against a DTLS 1.3 server, the + //! auto-sense client should report `Some(ProtocolVersion::DTLS1_3)`. + use dimpl::ProtocolVersion; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Before negotiation, auto-sense returns None. + assert_eq!(client.protocol_version(), None); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(10); + } + + assert!( + client_connected && server_connected, + "Handshake should complete" + ); + assert_eq!(client.protocol_version(), Some(ProtocolVersion::DTLS1_3)); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_client_protocol_version_after_negotiating_dtls12() { + //! After completing a handshake against a DTLS 1.2 server, the + //! auto-sense client should report `Some(ProtocolVersion::DTLS1_2)`. + use dimpl::ProtocolVersion; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = default_config(); + let mut now = Instant::now(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Before negotiation, auto-sense returns None. + assert_eq!(client.protocol_version(), None); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(10); + } + + assert!( + client_connected && server_connected, + "Handshake should complete" + ); + assert_eq!(client.protocol_version(), Some(ProtocolVersion::DTLS1_2)); +} diff --git a/third_party/dimpl/tests/auto/main.rs b/third_party/dimpl/tests/auto/main.rs new file mode 100644 index 0000000..195d12b --- /dev/null +++ b/third_party/dimpl/tests/auto/main.rs @@ -0,0 +1,4 @@ +mod common; +mod cross_matrix; +mod handshake; +mod server_fallback; diff --git a/third_party/dimpl/tests/auto/server_fallback.rs b/third_party/dimpl/tests/auto/server_fallback.rs new file mode 100644 index 0000000..b694b24 --- /dev/null +++ b/third_party/dimpl/tests/auto/server_fallback.rs @@ -0,0 +1,742 @@ +//! Auto-sense server fallback tests. +//! +//! Tests the `Dtls::new_auto()` server path where the server starts as +//! DTLS 1.3 and falls back to DTLS 1.2 when the client doesn't offer 1.3. +//! Also tests that DTLS 1.3 clients connect without fallback. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Error, Output, ProtocolVersion, PskResolver}; + +use crate::common::*; + +/// Helper: run a handshake loop between client and server, return +/// (client_connected, server_connected, client_version, server_version). +fn run_handshake( + client: &mut Dtls, + server: &mut Dtls, +) -> (bool, bool, Option, Option) { + let mut now = Instant::now(); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(client); + let server_out = drain_outputs(server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, server); + deliver_packets(&server_out.packets, client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + ( + client_connected, + server_connected, + client.protocol_version(), + server.protocol_version(), + ) +} + +// ============================================================================ +// Auto server + explicit DTLS 1.3 client → DTLS 1.3 (no fallback) +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_dtls13_client() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect"); + assert!(sc, "Server should connect"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_3)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_3)); +} + +// ============================================================================ +// Auto server + explicit DTLS 1.2 client → DTLS 1.2 (fallback) +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_send_application_data_pending() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, Instant::now()); + + let err = server + .send_application_data(b"early auto-server data") + .unwrap_err(); + assert!(matches!(err, Error::HandshakePending)); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect after pending send"); + assert!(sc, "Server should connect after pending send"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_2)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_2)); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_protocol_version_pending() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, Instant::now()); + + assert_eq!(server.protocol_version(), None); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect after pending protocol check"); + assert!(sc, "Server should connect after pending protocol check"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_2)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_2)); +} + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_dtls12_client() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect"); + assert!(sc, "Server should connect"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_2)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_2)); +} + +// ============================================================================ +// Auto server + auto client → DTLS 1.3 +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_auto_client() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut client = Dtls::new_auto(Arc::clone(&config), client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect"); + assert!(sc, "Server should connect"); + // Both auto: should negotiate DTLS 1.3 + assert_eq!(cv, Some(ProtocolVersion::DTLS1_3)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_3)); +} + +// ============================================================================ +// Auto server + DTLS 1.2 client (no cookie) → fallback +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_dtls12_client_no_cookie() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let client_config = default_config(); + let server_config = no_cookie_config(); + + let mut client = Dtls::new_12(client_config, client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect"); + assert!(sc, "Server should connect"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_2)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_2)); +} + +// ============================================================================ +// Auto server + DTLS 1.3 client (no cookie) → DTLS 1.3 +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_dtls13_client_no_cookie() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let client_config = default_config(); + let server_config = no_cookie_config(); + + let mut client = Dtls::new_13(client_config, client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect"); + assert!(sc, "Server should connect"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_3)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_3)); +} + +// ============================================================================ +// Auto server + DTLS 1.2 client → fallback, then exchange application data +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_dtls12_fallback_application_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, now); + + // Complete handshake + let (cc, sc, _, _) = run_handshake(&mut client, &mut server); + assert!(cc && sc, "Handshake should complete"); + + // Send data client → server + let msg = b"hello from dtls12 client"; + client.send_application_data(msg).expect("client send"); + now = Instant::now() + Duration::from_millis(100); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d == msg), + "Server should receive client's application data" + ); + + // Send data server → client + let reply = b"hello from auto server"; + server.send_application_data(reply).expect("server send"); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.app_data.iter().any(|d| d == reply), + "Client should receive server's application data" + ); +} + +// ============================================================================ +// Auto server + DTLS 1.3 client → no fallback, exchange application data +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_dtls13_application_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, now); + + // Complete handshake + let (cc, sc, _, _) = run_handshake(&mut client, &mut server); + assert!(cc && sc, "Handshake should complete"); + + // Send data client → server + let msg = b"hello from dtls13 client"; + client.send_application_data(msg).expect("client send"); + now = Instant::now() + Duration::from_millis(100); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d == msg), + "Server should receive client's application data" + ); + + // Send data server → client + let reply = b"hello from auto server (1.3)"; + server.send_application_data(reply).expect("server send"); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.app_data.iter().any(|d| d == reply), + "Client should receive server's application data" + ); +} + +// ============================================================================ +// Auto server + DTLS 1.2 client → keying material matches +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_dtls12_fallback_keying_material() { + use dimpl::SrtpProfile; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, now); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + assert_eq!(client_km.0, server_km.0, "Keying material should match"); + assert_eq!(client_km.1, server_km.1, "SRTP profile should match"); + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} + +// ============================================================================ +// Auto server + DTLS 1.3 client → keying material matches +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_dtls13_keying_material() { + use dimpl::SrtpProfile; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(config, server_cert, now); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + assert_eq!(client_km.0, server_km.0, "Keying material should match"); + assert_eq!(client_km.1, server_km.1, "SRTP profile should match"); + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} + +// ============================================================================ +// Auto server set_active(true) creates ClientPending +// ============================================================================ + +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_set_active_creates_client_pending() { + use dimpl::certificate::generate_self_signed_certificate; + + let cert = generate_self_signed_certificate().unwrap(); + let config = default_config(); + + let mut dtls = Dtls::new_auto(config, cert, Instant::now()); + assert!(!dtls.is_active()); + + dtls.set_active(true); + assert!(dtls.is_active()); + + // Should be able to produce a hybrid ClientHello + dtls.handle_timeout(Instant::now()).unwrap(); + let mut buf = vec![0u8; 2048]; + let output = dtls.poll_output(&mut buf); + assert!( + matches!(output, Output::Packet(_)), + "Should send hybrid ClientHello" + ); +} + +// ============================================================================ +// Fragmented ClientHello tests — small MTU forces multi-fragment CH +// ============================================================================ + +/// DTLS 1.3 client with small MTU → fragmented ClientHello → auto server connects as 1.3. +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_fragmented_dtls13_client_hello() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + + // MTU=200 forces the ClientHello to be fragmented across multiple records + let client_config = small_mtu_config(200); + let server_config = default_config(); + + let mut client = Dtls::new_13(client_config, client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect with fragmented CH"); + assert!(sc, "Server should connect with fragmented CH"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_3)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_3)); +} + +/// DTLS 1.3 client with very small MTU (100 bytes) → heavily fragmented CH → auto server 1.3. +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_with_heavily_fragmented_dtls13_client_hello() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + + // MTU=100 — heavy fragmentation (CH will be ~5-6 fragments) + let client_config = small_mtu_config(100); + let server_config = default_config(); + + let mut client = Dtls::new_13(client_config, client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, Instant::now()); + + let (cc, sc, _cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect with heavily fragmented CH"); + assert!(sc, "Server should connect with heavily fragmented CH"); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_3)); +} + +/// Both client and server with small MTU → fragmented CH → auto server 1.3 + data exchange. +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_fragmented_ch_application_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + + let client_config = small_mtu_config(200); + let server_config = default_config(); + + let mut now = Instant::now(); + let mut client = Dtls::new_13(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, now); + + // Complete handshake + let (cc, sc, _, _) = run_handshake(&mut client, &mut server); + assert!(cc && sc, "Handshake should complete with fragmented CH"); + + // Send data client → server + let msg = b"data after fragmented handshake"; + client.send_application_data(msg).expect("client send"); + now = Instant::now() + Duration::from_millis(100); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d == msg), + "Server should receive data after fragmented CH handshake" + ); +} + +/// Fragmented DTLS 1.3 ClientHello with no-cookie config → auto server 1.3. +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_fragmented_ch_no_cookie() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + + let client_config = small_mtu_config(200); + let server_config = no_cookie_config(); + + let mut client = Dtls::new_13(client_config, client_cert, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, Instant::now()); + + let (cc, sc, _cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "Client should connect with fragmented CH, no cookie"); + assert!(sc, "Server should connect with fragmented CH, no cookie"); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_3)); +} + +// ============================================================================ +// Auto server + DTLS 1.2 PSK client → fallback picks PSK-mode Server12 +// ============================================================================ + +/// Regression for https://github.com/algesten/dimpl/issues/100 — a +/// `Dtls::new_auto` server configured with `with_psk_server` must accept a +/// DTLS 1.2 PSK client. Before the fix the fallback always constructed a +/// certificate-auth Server12 and failed with "No mutually acceptable cipher +/// suite". +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_psk_fallback_with_dtls12_psk_client() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + struct FixedPsk; + impl PskResolver for FixedPsk { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(b"0123456789abcdef".to_vec()) + } + } + + let server_cert = generate_self_signed_certificate().unwrap(); + + let client_config = Arc::new( + Config::builder() + .with_psk_client(b"test-device".to_vec(), Arc::new(FixedPsk)) + .build() + .expect("build PSK client config"), + ); + let server_config = Arc::new( + Config::builder() + .with_psk_server(Some(b"hint".to_vec()), Arc::new(FixedPsk)) + .build() + .expect("build PSK server config"), + ); + + let mut client = Dtls::new_12_psk(client_config, Instant::now()); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, Instant::now()); + + let (cc, sc, cv, sv) = run_handshake(&mut client, &mut server); + + assert!(cc, "PSK client should connect after auto-server fallback"); + assert!(sc, "Auto server should connect to DTLS 1.2 PSK client"); + assert_eq!(cv, Some(ProtocolVersion::DTLS1_2)); + assert_eq!(sv, Some(ProtocolVersion::DTLS1_2)); +} + +/// Fragmented DTLS 1.3 ClientHello → keying material matches between client and auto server. +#[test] +#[cfg(feature = "rcgen")] +fn auto_server_fragmented_ch_keying_material() { + use dimpl::SrtpProfile; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().unwrap(); + let server_cert = generate_self_signed_certificate().unwrap(); + + let client_config = small_mtu_config(200); + let server_config = default_config(); + + let mut now = Instant::now(); + let mut client = Dtls::new_13(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_auto(server_config, server_cert, now); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + assert_eq!(client_km.0, server_km.0, "Keying material should match"); + assert_eq!(client_km.1, server_km.1, "SRTP profile should match"); + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} diff --git a/third_party/dimpl/tests/dtls12/common.rs b/third_party/dimpl/tests/dtls12/common.rs new file mode 100644 index 0000000..7fc8710 --- /dev/null +++ b/third_party/dimpl/tests/dtls12/common.rs @@ -0,0 +1,233 @@ +//! Shared helpers for DTLS 1.2 integration tests. + +#![allow(unused)] + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Output, SrtpProfile}; + +/// Parsed DTLS 1.2 record header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RecHdr { + pub ctype: u8, + pub epoch: u16, + pub seq: u64, +} + +/// Handshake message types (RFC 5246 / 6347). +pub const CLIENT_HELLO: u8 = 1; +pub const SERVER_HELLO: u8 = 2; +pub const HELLO_VERIFY_REQUEST: u8 = 3; +pub const CERTIFICATE: u8 = 11; +pub const SERVER_HELLO_DONE: u8 = 14; + +/// Parse DTLS 1.2 record headers from a datagram. +pub fn parse_records(datagram: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut i = 0usize; + while i + 13 <= datagram.len() { + let ctype = datagram[i]; + let epoch = u16::from_be_bytes([datagram[i + 3], datagram[i + 4]]); + let seq_bytes = [ + 0u8, + 0u8, + datagram[i + 5], + datagram[i + 6], + datagram[i + 7], + datagram[i + 8], + datagram[i + 9], + datagram[i + 10], + ]; + let seq = u64::from_be_bytes(seq_bytes); + let len = u16::from_be_bytes([datagram[i + 11], datagram[i + 12]]) as usize; + out.push(RecHdr { ctype, epoch, seq }); + i += 13 + len; + } + out +} + +/// Collect record headers from a slice of datagrams. +pub fn collect_headers(datagrams: &[Vec]) -> Vec { + datagrams.iter().flat_map(|d| parse_records(d)).collect() +} + +/// Parse handshake message types from a datagram (content_type=22). +pub fn parse_handshake_types(datagram: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut i = 0usize; + while i + 13 <= datagram.len() { + let ctype = datagram[i]; + let len = u16::from_be_bytes([datagram[i + 11], datagram[i + 12]]) as usize; + + // Only parse handshake records (content_type=22) + if ctype == 22 && i + 14 <= datagram.len() { + // Handshake message type is first byte of payload + let hs_type = datagram[i + 13]; + out.push(hs_type); + } + i += 13 + len; + } + out +} + +/// Assert that retransmitted records have the same epochs but increased sequence numbers. +pub fn assert_epochs_and_seq_increased(init: &[RecHdr], resend: &[RecHdr]) { + assert_eq!( + init.len(), + resend.len(), + "record count must match between initial and resend" + ); + for (a, b) in init.iter().zip(resend.iter()) { + assert_eq!( + a.epoch, b.epoch, + "epoch must match for the same record on resend" + ); + assert!( + b.seq > a.seq, + "sequence must increase on resend: {:?} -> {:?}", + a, + b + ); + } +} + +/// Poll until `Timeout`, collecting only packets. +pub fn collect_packets(endpoint: &mut Dtls) -> Vec> { + let mut out = Vec::new(); + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => out.push(p.to_vec()), + Output::Timeout(_) => break, + _ => {} + } + } + out +} + +/// Collected outputs from polling an endpoint to `Timeout`. +#[derive(Default, Debug)] +pub struct DrainedOutputs { + pub packets: Vec>, + pub connected: bool, + pub peer_cert: Option>, + pub keying_material: Option<(Vec, SrtpProfile)>, + pub app_data: Vec>, + pub timeout: Option, + pub close_notify: bool, +} + +/// Poll until `Timeout`, collecting everything. +pub fn drain_outputs(endpoint: &mut Dtls) -> DrainedOutputs { + let mut result = DrainedOutputs::default(); + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => result.packets.push(p.to_vec()), + Output::Connected => result.connected = true, + Output::PeerCert(cert) => result.peer_cert = Some(cert.to_vec()), + Output::KeyingMaterial(km, profile) => { + result.keying_material = Some((km.to_vec(), profile)); + } + Output::ApplicationData(data) => result.app_data.push(data.to_vec()), + Output::CloseNotify => result.close_notify = true, + Output::Timeout(t) => { + result.timeout = Some(t); + break; + } + _ => {} + } + } + result +} + +/// Deliver a slice of packets to a destination endpoint. +pub fn deliver_packets(packets: &[Vec], dest: &mut Dtls) { + for p in packets { + // Ignore errors - they may be expected for duplicates/replays + let _ = dest.handle_packet(p); + } +} + +/// Trigger a timeout by advancing time 2 seconds. +pub fn trigger_timeout(ep: &mut Dtls, now: &mut Instant) { + *now += Duration::from_secs(2); + ep.handle_timeout(*now).expect("handle_timeout"); +} + +/// Create a DTLS 1.2 config with default settings. +pub fn dtls12_config() -> Arc { + Arc::new(Config::default()) +} + +/// Create a DTLS 1.2 config with custom MTU. +pub fn dtls12_config_with_mtu(mtu: usize) -> Arc { + Arc::new( + Config::builder() + .mtu(mtu) + .build() + .expect("Failed to build config"), + ) +} + +/// Complete a full DTLS 1.2 handshake between client and server. +/// +/// Returns the final `Instant` (time advanced during the handshake). +/// Panics if the handshake does not complete within the iteration limit. +pub fn complete_dtls12_handshake( + client: &mut Dtls, + server: &mut Dtls, + mut now: Instant, +) -> Instant { + let mut client_connected = false; + let mut server_connected = false; + + for i in 0..60 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(client); + let server_out = drain_outputs(server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, server); + deliver_packets(&server_out.packets, client); + + if client_connected && server_connected { + return now; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(50); + } + } + + panic!("DTLS 1.2 handshake did not complete within iteration limit"); +} + +/// Create a connected DTLS 1.2 client/server pair with self-signed certificates. +/// +/// Returns `(client, server, now)` with the handshake already completed. +#[cfg(feature = "rcgen")] +pub fn setup_connected_12_pair(now: Instant) -> (Dtls, Dtls, Instant) { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls12_config(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let now = complete_dtls12_handshake(&mut client, &mut server, now); + (client, server, now) +} diff --git a/third_party/dimpl/tests/dtls12/crypto.rs b/third_party/dimpl/tests/dtls12/crypto.rs new file mode 100644 index 0000000..68bfdca --- /dev/null +++ b/third_party/dimpl/tests/dtls12/crypto.rs @@ -0,0 +1,328 @@ +//! DTLS 1.2 cipher suite tests (all supported suites). + +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::Instant; + +use dimpl::crypto::{Dtls12CipherSuite, SignatureAlgorithm}; +use dimpl::{Config, Dtls, Output}; + +use crate::ossl_helper::{DtlsCertOptions, DtlsEvent, DtlsPKeyType, OsslDtlsCert}; + +const GROUPS_PREFER_X25519: &str = "X25519:P-256:P-384"; +const NAMED_GROUP_X25519: u16 = 0x001D; + +fn read_u24(bytes: &[u8]) -> usize { + ((bytes[0] as usize) << 16) | ((bytes[1] as usize) << 8) | (bytes[2] as usize) +} + +fn find_server_key_exchange_group(packet: &[u8]) -> Option { + let mut rec_offset = 0usize; + while rec_offset + 13 <= packet.len() { + let content_type = packet[rec_offset]; + let rec_len = + u16::from_be_bytes([packet[rec_offset + 11], packet[rec_offset + 12]]) as usize; + let rec_start = rec_offset + 13; + let rec_end = rec_start + rec_len; + if rec_end > packet.len() { + return None; + } + + // Handshake records only (22) + if content_type == 22 { + let mut hs_offset = rec_start; + while hs_offset + 12 <= rec_end { + let hs_type = packet[hs_offset]; + let _hs_len = read_u24(&packet[hs_offset + 1..hs_offset + 4]); + let frag_offset = read_u24(&packet[hs_offset + 6..hs_offset + 9]); + let frag_len = read_u24(&packet[hs_offset + 9..hs_offset + 12]); + let body_start = hs_offset + 12; + let body_end = body_start + frag_len; + if body_end > rec_end { + break; + } + + // ServerKeyExchange (12), first fragment, ECDHE params: + // curve_type(1) + named_group(2) + pubkey_len(1) + pubkey + signature... + if hs_type == 12 && frag_offset == 0 && frag_len >= 4 && packet[body_start] == 3 { + let group = + u16::from_be_bytes([packet[body_start + 1], packet[body_start + 2]]); + return Some(group); + } + + if frag_len == 0 { + break; + } + hs_offset = body_end; + } + } + + rec_offset = rec_end; + } + None +} + +#[test] +fn dtls12_all_cipher_suites() { + let _ = env_logger::try_init(); + + // Loop over all supported cipher suites and ensure we can connect + // Skip PSK suites — they require PSK config, not certificate-based interop + for &suite in Dtls12CipherSuite::all().iter().filter(|s| !s.is_psk()) { + eprintln!("Testing suite (dimpl client â†”ī¸ ossl server): {:?}", suite); + + run_dimpl_client_vs_ossl_server_for_suite(suite); + + eprintln!("Testing suite (ossl client â†”ī¸ dimpl server): {:?}", suite); + run_ossl_client_vs_dimpl_server_for_suite(suite); + } +} + +fn config_for_suite(suite: Dtls12CipherSuite) -> Arc { + let mut provider = Config::default().crypto_provider().clone(); + let selected = provider + .cipher_suites + .iter() + .copied() + .find(|cs| cs.suite() == suite) + .unwrap_or_else(|| panic!("Suite {:?} not found in provider", suite)); + + // Leak a tiny fixed-size slice so it can satisfy the provider's 'static requirement. + let suites = Box::leak(Box::new([selected])); + provider.cipher_suites = suites; + + Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("build config for single suite"), + ) +} + +fn run_dimpl_client_vs_ossl_server_for_suite(suite: Dtls12CipherSuite) { + // Generate certificates for both client and server matching the suite's signature algorithm + let pkey_type = match suite.signature_algorithm() { + Some(SignatureAlgorithm::ECDSA) => DtlsPKeyType::EcDsaP256, + Some(SignatureAlgorithm::RSA) => DtlsPKeyType::Rsa2048, + _ => panic!("Unsupported signature algorithm in suite: {:?}", suite), + }; + + let client_cert = OsslDtlsCert::new(DtlsCertOptions { + common_name: "WebRTC".into(), + pkey_type: pkey_type.clone(), + }); + + let server_cert = OsslDtlsCert::new(DtlsCertOptions { + common_name: "WebRTC".into(), + pkey_type, + }); + + // Create OpenSSL server impl + let mut server = server_cert + .new_dtls_impl_with_groups(GROUPS_PREFER_X25519) + .expect("Failed to create DTLS server"); + server.set_active(false); + + // Initialize dimpl client restricted to the single suite. + let config = config_for_suite(suite); + + // DER encodings for our client + let client_x509_der = client_cert.x509.to_der().expect("client cert der"); + let client_pkey_der = client_cert + .pkey + .private_key_to_der() + .expect("client key der"); + + let now = Instant::now(); + + let mut client = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: client_x509_der, + private_key: client_pkey_der, + }, + now, + ); + client.set_active(true); + + let mut server_events = VecDeque::new(); + let mut client_connected = false; + let mut server_connected = false; + let mut server_kx_group = None; + + let mut out_buf = vec![0u8; 2048]; + for _ in 0..60 { + client.handle_timeout(Instant::now()).unwrap(); + // Drain client outputs + loop { + match client.poll_output(&mut out_buf) { + Output::Packet(data) => { + server + .handle_receive(data, &mut server_events) + .expect("Server failed to handle client packet"); + } + Output::Connected => { + client_connected = true; + } + Output::Timeout(_) => break, + _ => {} + } + } + + // Process server events + while let Some(event) = server_events.pop_front() { + if let DtlsEvent::Connected = event { + server_connected = true; + } + } + + // Send server datagrams back to client + while let Some(datagram) = server.poll_datagram() { + if server_kx_group.is_none() { + server_kx_group = find_server_key_exchange_group(&datagram); + } + client + .handle_packet(&datagram) + .expect("Failed to handle server packet"); + } + + if client_connected && server_connected { + break; + } + } + + assert!( + client_connected, + "Client should connect for suite {:?}", + suite + ); + assert!( + server_connected, + "Server should connect for suite {:?}", + suite + ); + assert_eq!( + server_kx_group, + Some(NAMED_GROUP_X25519), + "OpenSSL server should negotiate X25519 for suite {:?}", + suite + ); +} + +fn run_ossl_client_vs_dimpl_server_for_suite(suite: Dtls12CipherSuite) { + // Generate certificates for both ends + let pkey_type = match suite.signature_algorithm() { + Some(SignatureAlgorithm::ECDSA) => DtlsPKeyType::EcDsaP256, + Some(SignatureAlgorithm::RSA) => DtlsPKeyType::Rsa2048, + _ => panic!("Unsupported signature algorithm in suite: {:?}", suite), + }; + + let server_cert = OsslDtlsCert::new(DtlsCertOptions { + common_name: "WebRTC".into(), + pkey_type: pkey_type.clone(), + }); + let client_cert = OsslDtlsCert::new(DtlsCertOptions { + common_name: "WebRTC".into(), + pkey_type, + }); + + // OpenSSL DTLS client + let mut ossl_client = client_cert + .new_dtls_impl_with_groups(GROUPS_PREFER_X25519) + .expect("Failed to create DTLS client"); + ossl_client.set_active(true); + + // dimpl server with single-suite config. + let config = config_for_suite(suite); + + let server_x509_der = server_cert.x509.to_der().expect("server cert der"); + let server_pkey_der = server_cert + .pkey + .private_key_to_der() + .expect("server key der"); + + let now = Instant::now(); + + let mut server = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: server_x509_der, + private_key: server_pkey_der, + }, + now, + ); + server.set_active(false); + + // Drive handshake until both sides report connected + let mut client_events = VecDeque::new(); + let mut server_connected = false; + let mut client_connected = false; + let mut server_kx_group = None; + + let mut out_buf = vec![0u8; 2048]; + for _ in 0..60 { + server.handle_timeout(Instant::now()).unwrap(); + ossl_client.handle_handshake(&mut client_events).unwrap(); + + // 1) Drain client (OpenSSL) outgoing datagrams to the server + while let Some(datagram) = ossl_client.poll_datagram() { + server + .handle_packet(&datagram) + .expect("Server failed to handle client packet"); + } + + // 2) Poll server outputs and feed to client + loop { + match server.poll_output(&mut out_buf) { + Output::Packet(data) => { + if server_kx_group.is_none() { + server_kx_group = find_server_key_exchange_group(data); + } + ossl_client + .handle_receive(data, &mut client_events) + .expect("Client failed to handle server packet"); + } + Output::Connected => { + server_connected = true; + } + Output::Timeout(_) => break, + _ => {} + } + } + + // 3) Process client (OpenSSL) events + while let Some(event) = client_events.pop_front() { + if let DtlsEvent::Connected = event { + client_connected = true; + } + } + + // 4) Deliver any further client datagrams produced after events + while let Some(datagram) = ossl_client.poll_datagram() { + server + .handle_packet(&datagram) + .expect("Server failed to handle client packet"); + } + + if server_connected && client_connected { + break; + } + } + + assert!( + server_connected, + "Server should connect for suite {:?}", + suite + ); + assert!( + client_connected, + "Client should connect for suite {:?}", + suite + ); + assert_eq!( + server_kx_group, + Some(NAMED_GROUP_X25519), + "dimpl server should negotiate X25519 for suite {:?}", + suite + ); +} diff --git a/third_party/dimpl/tests/dtls12/data.rs b/third_party/dimpl/tests/dtls12/data.rs new file mode 100644 index 0000000..1ba23b5 --- /dev/null +++ b/third_party/dimpl/tests/dtls12/data.rs @@ -0,0 +1,433 @@ +//! DTLS 1.2 application data tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::Dtls; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_application_data_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let client_data = b"hello"; + let server_data = b"world"; + + let mut client_connected = false; + let mut server_connected = false; + let mut client_received: Vec = Vec::new(); + let mut server_received: Vec = Vec::new(); + let mut client_sent = false; + let mut server_sent = false; + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Collect received app data + for data in &client_out.app_data { + client_received.extend_from_slice(data); + } + for data in &server_out.app_data { + server_received.extend_from_slice(data); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + // Send data once connected + if client_connected && !client_sent { + client + .send_application_data(client_data) + .expect("client send"); + client_sent = true; + } + if server_connected && !server_sent { + server + .send_application_data(server_data) + .expect("server send"); + server_sent = true; + } + + if !client_received.is_empty() && !server_received.is_empty() { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + assert_eq!( + server_received, client_data, + "Server should receive client's data" + ); + assert_eq!( + client_received, server_data, + "Client should receive server's data" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_multiple_application_data_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // First complete handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Now send 5 distinct messages + let messages = vec![ + b"Message 1".to_vec(), + b"Message 2".to_vec(), + b"Message 3 is a bit longer".to_vec(), + b"Message 4".to_vec(), + b"Message 5 - the final one".to_vec(), + ]; + + for msg in &messages { + client.send_application_data(msg).expect("client send"); + } + + let mut server_received: Vec> = Vec::new(); + + for _ in 0..20 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + let server_out = drain_outputs(&mut server); + for data in server_out.app_data { + server_received.push(data); + } + + if server_received.len() >= messages.len() { + break; + } + + now += Duration::from_millis(10); + } + + // Flatten and compare to verify all messages received in order + let expected: Vec = messages.iter().flatten().copied().collect(); + let received: Vec = server_received.iter().flatten().copied().collect(); + + assert_eq!( + received, expected, + "All 5 messages should be received in order" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_bidirectional_data_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Exchange data in both directions simultaneously for 10 rounds + let rounds = 10; + let mut client_received_count = 0; + let mut server_received_count = 0; + + for i in 0..rounds { + let client_msg = format!("Client message {}", i); + let server_msg = format!("Server message {}", i); + + client + .send_application_data(client_msg.as_bytes()) + .expect("client send"); + server + .send_application_data(server_msg.as_bytes()) + .expect("server send"); + + for _ in 0..10 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_received_count += client_out.app_data.len(); + server_received_count += server_out.app_data.len(); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + now += Duration::from_millis(5); + } + } + + assert_eq!( + client_received_count, rounds, + "Client should receive all {} server messages", + rounds + ); + assert_eq!( + server_received_count, rounds, + "Server should receive all {} client messages", + rounds + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_many_small_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Send 100 small messages from client to server. + // Drain and deliver after each send to respect the Sans-IO poll-to-timeout + // contract and the transmit queue capacity. + let message_count = 100usize; + let mut received_count = 0usize; + + for i in 0..message_count { + let msg = format!("M{}", i); + client.send_application_data(msg.as_bytes()).expect("send"); + + let client_pkts = collect_packets(&mut client); + deliver_packets(&client_pkts, &mut server); + + let server_out = drain_outputs(&mut server); + for data in &server_out.app_data { + assert_eq!(data, msg.as_bytes(), "message {} should match", i); + received_count += 1; + } + } + + assert_eq!( + received_count, message_count, + "All 100 small messages should be received" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_large_application_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Send data larger than default MTU (1150 bytes) + let large_data: Vec = (0..2000).map(|i| (i % 256) as u8).collect(); + + client + .send_application_data(&large_data) + .expect("client send large data"); + + let mut server_received: Vec = Vec::new(); + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + let server_out = drain_outputs(&mut server); + for data in server_out.app_data { + server_received.extend_from_slice(&data); + } + + if server_received.len() >= large_data.len() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!( + server_received, large_data, + "Server should receive the full 2000-byte payload intact" + ); +} diff --git a/third_party/dimpl/tests/dtls12/edge.rs b/third_party/dimpl/tests/dtls12/edge.rs new file mode 100644 index 0000000..279b4ba --- /dev/null +++ b/third_party/dimpl/tests/dtls12/edge.rs @@ -0,0 +1,1216 @@ +//! DTLS 1.2 edge case and error recovery tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +#[cfg(feature = "rcgen")] +use dimpl::certificate::generate_self_signed_certificate; +use dimpl::crypto::Dtls12CipherSuite; +use dimpl::{Config, Dtls, Output}; + +use crate::common::*; + +fn dtls12_alert_record(seq: u64, level: u8, description: u8) -> Vec { + let mut out = Vec::new(); + out.push(21); // Alert + out.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 + out.extend_from_slice(&0u16.to_be_bytes()); // epoch 0 + out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number + out.extend_from_slice(&2u16.to_be_bytes()); // alert payload length + out.extend_from_slice(&[level, description]); + out +} + +fn dtls12_epoch1_record(seq: u64, len: usize) -> Vec { + let mut out = Vec::with_capacity(13 + len); + out.push(23); // ApplicationData + out.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 + out.extend_from_slice(&1u16.to_be_bytes()); // epoch 1 + out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number + out.extend_from_slice(&(len as u16).to_be_bytes()); + out.resize(13 + len, 0); + out +} + +#[test] +#[cfg(feature = "rcgen")] +fn oversized_application_data_reports_buffer_too_small() { + let now = Instant::now(); + let (mut client, mut server, _now) = setup_connected_12_pair(now); + let payload = vec![0x5a; 4000]; + + client + .send_application_data(&payload) + .expect("send application data"); + + let mut large_buf = vec![0u8; 8192]; + let mut packets = Vec::new(); + loop { + match client.poll_output(&mut large_buf) { + Output::Packet(packet) => packets.push(packet.to_vec()), + Output::Timeout(_) => break, + _ => {} + } + } + + deliver_packets(&packets, &mut server); + + let mut small_buf = vec![0u8; 2048]; + match server.poll_output(&mut small_buf) { + Output::BufferTooSmall { needed } => assert_eq!(needed, payload.len()), + output => panic!("expected BufferTooSmall, got {output:?}"), + } + + match server.poll_output(&mut large_buf) { + Output::ApplicationData(data) => assert_eq!(data, payload.as_slice()), + output => panic!("expected retained application data, got {output:?}"), + } +} + +fn dtls12_config_for_suite(suite: Dtls12CipherSuite) -> Arc { + let mut provider = Config::default().crypto_provider().clone(); + let selected = provider + .cipher_suites + .iter() + .copied() + .find(|cs| cs.suite() == suite) + .unwrap_or_else(|| panic!("suite {:?} not found in provider", suite)); + + let suites = Box::leak(Box::new([selected])); + provider.cipher_suites = suites; + + Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("build config for single suite"), + ) +} + +fn dtls12_min_protected_fragment_len(suite: Dtls12CipherSuite) -> usize { + match suite { + Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384 + | Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256 => 24, + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256 => 16, + Dtls12CipherSuite::PSK_AES128_CCM_8 => 16, + _ => panic!("unknown cipher suite"), + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_malformed_datagram_is_discarded_without_processing_alerts() { + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls12_config(); + let now = Instant::now(); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut packet = dtls12_alert_record(1, 2, 40); + packet.push(0xFF); // trailing truncated record header + + server + .handle_packet(&packet) + .expect("malformed datagram should be discarded"); + + let mut buf = [0; 1500]; + assert!(!matches!(server.poll_output(&mut buf), Output::CloseNotify)); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_too_many_control_records_are_discarded() { + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls12_config(); + let now = Instant::now(); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut packet = Vec::new(); + for seq in 1..=9 { + packet.extend_from_slice(&dtls12_alert_record(seq, 1, 0)); + } + + server + .handle_packet(&packet) + .expect("too many records should be discarded"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_recovers_from_corrupted_packet() { + //! During handshake, corrupt 2 bytes in one packet before delivery so the + //! DTLS record header is invalid. The receiver drops the corrupted packet. + //! After a timeout the sender retransmits, and the handshake completes + //! normally via the retransmission path. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // FLIGHT 1: Client sends ClientHello + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let f1 = collect_packets(&mut client); + assert!(!f1.is_empty(), "client should emit ClientHello"); + + // Corrupt the record header itself (version field at bytes 1-2) so + // the record is rejected at parse time and nothing enters queue_rx. + for mut p in f1 { + if p.len() > 5 { + p[1] ^= 0xFF; + p[2] ^= 0xFF; + } + // Server should reject the record due to invalid version + let _ = server.handle_packet(&p); + } + + // Server has no valid packet yet — arm its timers so it's ready + server.handle_timeout(now).expect("server arm"); + let s_pkts = collect_packets(&mut server); + assert!(s_pkts.is_empty(), "server should have nothing to send yet"); + + // Trigger client retransmission timeout (initial RTO is ~1s) + trigger_timeout(&mut client, &mut now); + let f1_resend = collect_packets(&mut client); + assert!( + !f1_resend.is_empty(), + "client should retransmit ClientHello after timeout" + ); + + // Deliver the clean retransmission to server + for p in &f1_resend { + server.handle_packet(p).expect("server recv clean CH"); + } + + // FLIGHT 2: Server sends HelloVerifyRequest + server.handle_timeout(now).expect("server arm flight 2"); + let f2 = collect_packets(&mut server); + assert!(!f2.is_empty(), "server should emit HelloVerifyRequest"); + for p in &f2 { + client.handle_packet(p).expect("client recv HVR"); + } + + // FLIGHT 3: Client sends ClientHello with cookie + client.handle_timeout(now).expect("client arm flight 3"); + let f3 = collect_packets(&mut client); + assert!(!f3.is_empty(), "client should emit ClientHello with cookie"); + for p in &f3 { + server.handle_packet(p).expect("server recv CH+cookie"); + } + + // FLIGHT 4: Server sends ServerHello, Certificate, etc. + server.handle_timeout(now).expect("server arm flight 4"); + let f4 = collect_packets(&mut server); + assert!(!f4.is_empty(), "server should emit ServerHello flight"); + for p in &f4 { + client.handle_packet(p).expect("client recv flight 4"); + } + + // FLIGHT 5: Client sends CKX, CCS, Finished + client.handle_timeout(now).expect("client arm flight 5"); + let f5 = collect_packets(&mut client); + assert!(!f5.is_empty(), "client should emit flight 5"); + for p in &f5 { + server.handle_packet(p).expect("server recv flight 5"); + } + + // FLIGHT 6: Server sends CCS, Finished (Connected may be emitted here) + server.handle_timeout(now).expect("server arm flight 6"); + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "server should emit flight 6" + ); + for p in &server_out.packets { + client.handle_packet(p).expect("client recv flight 6"); + } + + // Drain client outputs to check for Connected event + client.handle_timeout(now).expect("client final timeout"); + let client_out = drain_outputs(&mut client); + + assert!( + client_out.connected, + "Client should be connected after recovering from corrupted packet" + ); + assert!( + server_out.connected, + "Server should be connected after recovering from corrupted packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_discards_wrong_epoch_record() { + //! After a completed handshake (epoch 1), inject a crafted packet with + //! epoch 0 and content_type handshake (22). Verify it is silently dropped + //! and application data exchange still works. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + // Craft a DTLS 1.2 record with epoch 0 (pre-handshake) and content_type 22 (handshake). + // DTLS 1.2 record header: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) + let bogus = vec![ + 22, // content_type: handshake + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (wrong — should be 1 post-handshake) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, // sequence number + 0x00, 0x05, // length: 5 + 0x01, // handshake type: ClientHello + 0x00, 0x00, 0x00, 0x00, // dummy payload + ]; + + // Should be silently discarded (no error) + client + .handle_packet(&bogus) + .expect("wrong epoch record should be silently discarded"); + + // Verify application data exchange still works after the bogus packet. + client + .send_application_data(b"ping") + .expect("client send app data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), + "Server should receive application data after wrong-epoch bogus packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_short_encrypted_records_do_not_panic() { + let _ = env_logger::try_init(); + + for suite in [ + Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256, + Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256, + ] { + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls12_config_for_suite(suite); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + now = complete_dtls12_handshake(&mut client, &mut server, now); + + for len in 0..dtls12_min_protected_fragment_len(suite) { + let short = dtls12_epoch1_record(0x100 + len as u64, len); + client + .handle_packet(&short) + .expect("short encrypted record should be silently discarded"); + } + + server + .send_application_data(b"still alive") + .expect("server send app data"); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out + .app_data + .iter() + .any(|d| d.as_slice() == b"still alive"), + "client should receive application data after short encrypted {suite:?} records" + ); + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_discards_truncated_record() { + //! Deliver a 3-byte packet (too short to be a valid DTLS 1.2 record header, + //! which requires 13 bytes). Verify it is silently dropped and the + //! handshake/connection continues. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Inject a truncated packet before the handshake begins + let truncated = vec![0x16, 0xFE, 0xFD]; // 3 bytes — too short for any DTLS record + let result = client.handle_packet(&truncated); + // Should either return Ok (silently discarded) or a non-fatal error + match result { + Ok(()) => {} // silently discarded — expected + Err(e) => { + // Some parse errors are acceptable as long as the endpoint survives + eprintln!("Truncated packet returned error (non-fatal): {}", e); + } + } + + // Now complete the handshake to prove the endpoint is still functional + now = complete_dtls12_handshake(&mut client, &mut server, now); + + // Also inject a truncated packet after the handshake and verify app data works + let truncated_post = vec![0x17, 0xFE, 0xFD]; // 3 bytes, content_type = app data + let result = client.handle_packet(&truncated_post); + match result { + Ok(()) => {} + Err(e) => { + eprintln!( + "Post-handshake truncated packet returned error (non-fatal): {}", + e + ); + } + } + + // Verify application data exchange still works + client + .send_application_data(b"hello") + .expect("client send app data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"hello"), + "Server should receive application data after truncated bogus packets" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_discards_unauthenticated_close_notify() { + //! After a completed handshake (epoch 1), inject a plaintext close_notify + //! alert at epoch 0. Since the connection is authenticated, the + //! unauthenticated alert must be silently discarded and the connection + //! must remain operational. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + // Craft a close_notify alert record at epoch 0 (plaintext alert). + // Since DTLS 1.2 post-handshake records should be at epoch 1 and encrypted, + // an epoch 0 plaintext alert should be silently discarded. + let close_notify_epoch0 = vec![ + 21, // content_type: alert + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (plaintext — will be discarded post-handshake) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, // sequence number + 0x00, 0x02, // length: 2 + 0x01, // level: warning + 0x00, // description: close_notify + ]; + + // Epoch 0 alert post-handshake must be silently discarded (not an error). + server + .handle_packet(&close_notify_epoch0) + .expect("epoch 0 alert must be silently discarded post-handshake"); + + // Verify the server can still process data after the alert + client + .send_application_data(b"after-alert") + .expect("client send after alert"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"after-alert"), + "Server should still receive app data after close_notify alert at epoch 0" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_rejects_renegotiation() { + //! After a completed handshake, inject a ClientHello record to simulate + //! a renegotiation attempt. Verify it is rejected (either silently dropped + //! or returns `Error::RenegotiationAttempt`). + + let _ = env_logger::try_init(); + let now = Instant::now(); + let (_client, mut server, _now) = setup_connected_12_pair(now); + + // Craft a ClientHello record at epoch 0 to simulate a renegotiation attempt. + // This is a plaintext handshake record with a minimal ClientHello. + let renegotiation_hello = vec![ + 22, // content_type: handshake + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, // sequence number + 0x00, 0x2F, // length: 47 bytes of handshake payload + // Handshake header + 0x01, // msg_type: ClientHello + 0x00, 0x00, 0x23, // length: 35 + 0x00, 0x01, // message_seq: 1 + 0x00, 0x00, 0x00, // fragment_offset: 0 + 0x00, 0x00, 0x23, // fragment_length: 35 + // ClientHello body + 0xFE, 0xFD, // client_version: DTLS 1.2 + // random (32 bytes) + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, + 0x1F, 0x20, 0x00, // session_id length: 0 + 0x00, // cookie length: 0 + 0x00, // cipher_suites length will make this invalid, but that's fine + ]; + + // The server should reject the renegotiation attempt. + // It may return an error or silently discard it. + let result = server.handle_packet(&renegotiation_hello); + match result { + Ok(()) => { + // Silently discarded — acceptable (epoch 0 record post-handshake) + } + Err(e) => { + // RenegotiationAttempt or other error — also acceptable + eprintln!("Renegotiation attempt correctly rejected with error: {}", e); + } + } + + // Verify the connection still works after the renegotiation attempt — we need + // a client to send data, so re-create using the existing pair's server. + // Since _client was moved, just verify server can still queue data. + let result = server.send_application_data(b"post-reneg"); + assert!( + result.is_ok(), + "Server should still accept sends after renegotiation attempt was rejected" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_mixed_datagram_plaintext_first_then_valid() { + //! Test that a UDP datagram with bogus plaintext ApplicationData FIRST + //! followed by a valid encrypted record is handled correctly: the bogus + //! record is silently discarded and the valid one is still processed. + + let _ = env_logger::try_init(); + let now = Instant::now(); + let (mut client, mut server, now) = setup_connected_12_pair(now); + + // Send valid application data from client and capture the encrypted packet. + client + .send_application_data(b"valid-data") + .expect("send valid data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "Should have valid packet"); + let valid_packet = &client_out.packets[0]; + + // Craft a plaintext ApplicationData record (epoch 0). + let bogus_record = vec![ + 0x17, // content_type: ApplicationData + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (plaintext) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, // sequence_number + 0x00, 0x06, // length: 6 + 0x62, 0x6F, 0x67, 0x75, 0x73, 0x21, // "bogus!" + ]; + + // Construct a mixed datagram: bogus plaintext record FIRST, then valid record. + let mut mixed_datagram = bogus_record; + mixed_datagram.extend_from_slice(valid_packet); + + // Deliver the mixed datagram to server. + server + .handle_packet(&mixed_datagram) + .expect("mixed datagram should not error"); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + // The valid record should still be processed despite the bogus first record. + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"valid-data"), + "Server should receive the valid encrypted ApplicationData even when bogus record comes first" + ); + + // The bogus plaintext record should NOT produce any output. + assert_eq!( + server_out.app_data.len(), + 1, + "Should receive exactly 1 app data (the valid one), not the bogus plaintext" + ); + assert!( + !server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"bogus!"), + "Bogus plaintext ApplicationData must not be delivered" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_mixed_datagram_valid_first_then_bogus() { + //! Test that a UDP datagram with a valid encrypted record FIRST followed + //! by bogus plaintext ApplicationData is handled correctly: the valid + //! record is processed and the trailing bogus record is discarded. + + let _ = env_logger::try_init(); + let now = Instant::now(); + let (mut client, mut server, now) = setup_connected_12_pair(now); + + // Send valid application data from client and capture the encrypted packet. + client + .send_application_data(b"valid-data") + .expect("send valid data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "Should have valid packet"); + let valid_packet = &client_out.packets[0]; + + // Craft a plaintext ApplicationData record (epoch 0). + let bogus_record = vec![ + 0x17, // content_type: ApplicationData + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (plaintext) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, // sequence_number + 0x00, 0x06, // length: 6 + 0x62, 0x6F, 0x67, 0x75, 0x73, 0x21, // "bogus!" + ]; + + // Construct a mixed datagram: valid record FIRST, then bogus plaintext. + let mut mixed_datagram = valid_packet.clone(); + mixed_datagram.extend_from_slice(&bogus_record); + + // Deliver the mixed datagram to server. + server + .handle_packet(&mixed_datagram) + .expect("mixed datagram should not error"); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + // The valid record should be processed. + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"valid-data"), + "Server should receive the valid encrypted ApplicationData even when bogus record follows" + ); + + // The bogus trailing record should NOT produce any output. + assert_eq!( + server_out.app_data.len(), + 1, + "Should receive exactly 1 app data (the valid one), not the bogus plaintext" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_bad_encrypted_prefix_does_not_drop_valid_tail() { + let _ = env_logger::try_init(); + let now = Instant::now(); + let (mut client, mut server, now) = setup_connected_12_pair(now); + + client + .send_application_data(b"bad-prefix-clean-resend") + .expect("send first application data"); + client.handle_timeout(now).expect("client timeout"); + let first_out = drain_outputs(&mut client); + let first_packet = first_out + .packets + .first() + .expect("first application data packet") + .clone(); + + client + .send_application_data(b"valid-tail") + .expect("send second application data"); + client.handle_timeout(now).expect("client timeout"); + let second_out = drain_outputs(&mut client); + let second_packet = second_out + .packets + .first() + .expect("second application data packet") + .clone(); + + let mut corrupted_first = first_packet.clone(); + *corrupted_first + .last_mut() + .expect("encrypted packet has ciphertext") ^= 0x55; + + let mut mixed_datagram = corrupted_first; + mixed_datagram.extend_from_slice(&second_packet); + + server + .handle_packet(&mixed_datagram) + .expect("bad encrypted prefix should be discarded without dropping valid tail"); + let server_out = drain_outputs(&mut server); + assert_eq!( + server_out.app_data, + vec![b"valid-tail".to_vec()], + "valid tail record should be delivered despite bad encrypted prefix" + ); + + server + .handle_packet(&first_packet) + .expect("clean first packet should remain replay-acceptable"); + let server_out = drain_outputs(&mut server); + assert_eq!( + server_out.app_data, + vec![b"bad-prefix-clean-resend".to_vec()] + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_relabelled_encrypted_handshake_failure_is_not_silently_discarded() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls12_config(); + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let f1 = collect_packets(&mut client); + for p in &f1 { + server.handle_packet(p).expect("server recv ClientHello"); + } + + server.handle_timeout(now).expect("server arm flight 2"); + let f2 = collect_packets(&mut server); + for p in &f2 { + client + .handle_packet(p) + .expect("client recv HelloVerifyRequest"); + } + + client.handle_timeout(now).expect("client arm flight 3"); + let f3 = collect_packets(&mut client); + for p in &f3 { + server + .handle_packet(p) + .expect("server recv ClientHello with cookie"); + } + + server.handle_timeout(now).expect("server arm flight 4"); + let f4 = collect_packets(&mut server); + for p in &f4 { + client.handle_packet(p).expect("client recv server flight"); + } + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client arm flight 5"); + let mut f5 = collect_packets(&mut client); + assert!(!f5.is_empty(), "client should emit flight 5"); + + let mut relabelled = false; + let mut observed_error = None; + for p in &mut f5 { + let mut offset = 0; + while offset + 13 <= p.len() { + let epoch = u16::from_be_bytes([p[offset + 3], p[offset + 4]]); + let len = u16::from_be_bytes([p[offset + 11], p[offset + 12]]) as usize; + if p[offset] == 22 && epoch >= 1 { + p[offset] = 23; + relabelled = true; + break; + } + offset += 13 + len; + } + + match server.handle_packet(p) { + Ok(()) => {} + Err(e) => { + observed_error = Some(e); + break; + } + } + } + + assert!( + relabelled, + "flight 5 should contain an encrypted Handshake record" + ); + assert!( + matches!( + observed_error, + Some(dimpl::Error::CryptoError(_) | dimpl::Error::SecurityError(_)) + ), + "relabeled encrypted handshake must remain fatal, got {observed_error:?}" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_app_data_after_close_notify_is_ignored() { + //! Simulate UDP reordering: the client sends app data, then close_notify, + //! but the close_notify datagram arrives at the server first. The app data + //! datagram arriving afterwards must be silently discarded. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + // Step 1: Client sends app data — capture the packet but don't deliver yet. + client + .send_application_data(b"before-close") + .expect("send app data"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let app_data_out = drain_outputs(&mut client); + let app_data_packets = app_data_out.packets.clone(); + assert!(!app_data_packets.is_empty(), "Should have app data packet"); + + // Step 2: Client sends close_notify. + client.close().unwrap(); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let close_out = drain_outputs(&mut client); + assert!( + !close_out.packets.is_empty(), + "Should have close_notify packet" + ); + + // Step 3: Deliver close_notify FIRST (simulating UDP reordering). + deliver_packets(&close_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + assert!(server_out.close_notify, "Server should emit CloseNotify"); + + // Step 4: Now deliver the app data datagram that was sent BEFORE the alert + // but arrived AFTER — it must be discarded. + deliver_packets(&app_data_packets, &mut server); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + assert!( + server_out.app_data.is_empty(), + "ApplicationData arriving after close_notify must be discarded" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_close_during_handshake_emits_no_packets() { + //! Call close() on the client while the handshake is in progress. + //! Per `Dtls::close` API contract, close() during handshake silently + //! discards state without sending any packets. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Start handshake — client sends ClientHello + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "Client should emit ClientHello" + ); + + // Deliver to server, server responds + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let _server_out = drain_outputs(&mut server); + + // Now abort the client mid-handshake + client.close().unwrap(); + + // After close(), polling must not emit any more packets (library policy, not RFC mandate). + let client_out = drain_outputs(&mut client); + assert!( + client_out.packets.is_empty(), + "Client should not emit packets after close() during handshake" + ); + + // Even after a timeout, no packets should appear. + let later = now + Duration::from_secs(5); + // handle_timeout may error since state is Closed, which is fine + let _ = client.handle_timeout(later); + let client_out = drain_outputs(&mut client); + assert!( + client_out.packets.is_empty(), + "Client should not emit packets after timeout post-close()" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_reciprocal_close_notify_and_no_further_sends() { + //! When the server receives a close_notify from the client, it must send + //! a reciprocal close_notify back (RFC 5246 §7.2.1) and transition to + //! Closed. DTLS 1.2 does not support half-close: subsequent + //! send_application_data calls on both sides must fail. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + assert!(!client.is_closing()); + assert!(!client.is_closed()); + assert!(!server.is_closing()); + assert!(!server.is_closed()); + + // Client sends close_notify + client.close().unwrap(); + assert!(client.is_closing()); + assert!(!client.is_closed()); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "Client should emit close_notify alert" + ); + assert!(!client.is_closing()); + assert!(client.is_closed()); + + // Deliver to server + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + assert!(server.is_closing()); + assert!(!server.is_closed()); + + let server_out = drain_outputs(&mut server); + + // Server should emit CloseNotify event + assert!( + server_out.close_notify, + "Server should emit Output::CloseNotify" + ); + + // Server should emit a reciprocal close_notify packet. + assert!( + !server_out.packets.is_empty(), + "Server should emit a reciprocal close_notify packet" + ); + assert!(!server.is_closing()); + assert!(server.is_closed()); + + // Deliver reciprocal back to client and verify it sees CloseNotify. + deliver_packets(&server_out.packets, &mut client); + client + .handle_timeout(now) + .expect("client timeout after reciprocal"); + assert!(client.is_closing()); + assert!(!client.is_closed()); + + let client_out2 = drain_outputs(&mut client); + assert!( + client_out2.close_notify, + "Client should emit Output::CloseNotify after receiving reciprocal close_notify" + ); + assert!(!client.is_closing()); + assert!(client.is_closed()); + + // No half-close in DTLS 1.2: both sides must reject further sends. + assert!( + server.send_application_data(b"after-close").is_err(), + "send_application_data must fail after close_notify in DTLS 1.2" + ); + assert!( + client.send_application_data(b"after-close").is_err(), + "send_application_data must fail after close() in DTLS 1.2" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_close_state_matrix() { + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + assert!(!client.is_closing()); + assert!(!client.is_closed()); + assert!(!server.is_closing()); + assert!(!server.is_closed()); + + client.close().unwrap(); + assert!(client.is_closing(), "local close pending"); + assert!(!client.is_closed(), "local close not drained"); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "local close_notify packet"); + assert!(!client.is_closing(), "local close drained"); + assert!(client.is_closed(), "local close terminal"); + + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + assert!(server.is_closing(), "remote close pending"); + assert!(!server.is_closed(), "remote close not drained"); + + let server_out = drain_outputs(&mut server); + assert!(server_out.close_notify, "remote CloseNotify event"); + assert!( + !server_out.packets.is_empty(), + "remote reciprocal close_notify packet" + ); + assert!(!server.is_closing(), "remote close drained"); + assert!(server.is_closed(), "remote close terminal"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_discard_pending_writes_on_close_notify() { + //! Send application data from the server, then deliver a close_notify from + //! the client before the server polls. The pending data must be discarded + //! per RFC 5246 §7.2.1 — only the reciprocal close_notify is emitted. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + // Server queues some application data (not yet polled) + server + .send_application_data(b"pending-data") + .expect("server send pending data"); + + // Client sends close_notify + client.close().unwrap(); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + // Deliver the close_notify to the server (before it polls its pending data) + deliver_packets(&client_out.packets, &mut server); + + // Now poll the server — pending data should have been discarded + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + assert!(server_out.close_notify, "Server should see CloseNotify"); + assert!( + !server_out.packets.is_empty(), + "Server should emit reciprocal close_notify" + ); + + // Deliver reciprocal to client — verify no app data leaked + deliver_packets(&server_out.packets, &mut client); + client + .handle_timeout(now) + .expect("client timeout after reciprocal"); + let client_out2 = drain_outputs(&mut client); + + assert!( + client_out2.close_notify, + "Client should emit Output::CloseNotify after receiving reciprocal close_notify" + ); + assert!( + client_out2.app_data.is_empty(), + "Pending data must be discarded when close_notify is received" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_fatal_alert_during_handshake() { + //! During the handshake (peer_encryption_enabled == false), an epoch 0 + //! fatal alert (level=2) should be accepted and return a SecurityError. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut _server = Dtls::new_12(config, server_cert, now); + + // Start the handshake so the client is expecting a response + client.handle_timeout(now).expect("client timeout"); + let _client_out = drain_outputs(&mut client); + + // Craft a fatal alert at epoch 0 (during handshake, this is legitimate) + let fatal_alert = vec![ + 21, // content_type: alert + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // sequence number + 0x00, 0x02, // length: 2 + 0x02, // level: fatal + 0x28, // description: handshake_failure (40) + ]; + + let result = client.handle_packet(&fatal_alert); + assert!( + result.is_err(), + "Fatal alert during handshake should return an error" + ); + let err = result.unwrap_err(); + assert!(matches!( + err, + dimpl::Error::SecurityError(dimpl::SecurityError::FatalAlert { description: 40 }) + )); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_app_data_delivered_before_close_notify() { + //! When app data and close_notify arrive together, the app data must be + //! delivered before CloseNotify. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + // Send app data then immediately close + client + .send_application_data(b"before-close") + .expect("send app data"); + client.close().unwrap(); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + deliver_packets(&client_out.packets, &mut server); + + // Poll server outputs and verify ordering: ApplicationData before CloseNotify + server.handle_timeout(now).expect("server timeout"); + let mut saw_app_data = false; + let mut saw_close_notify = false; + let mut close_after_data = false; + let mut buf = vec![0u8; 2048]; + loop { + match server.poll_output(&mut buf) { + Output::ApplicationData(data) => { + assert!( + !saw_close_notify, + "ApplicationData must not appear after CloseNotify" + ); + if data == b"before-close" { + saw_app_data = true; + } + } + Output::CloseNotify => { + saw_close_notify = true; + if saw_app_data { + close_after_data = true; + } + } + Output::Timeout(_) => break, + _ => {} + } + } + assert!(saw_app_data, "Server should receive the app data"); + assert!(saw_close_notify, "Server should see CloseNotify"); + assert!( + close_after_data, + "CloseNotify must come after ApplicationData" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_close_notify_not_retransmitted() { + //! After sending close_notify, the alert must not be retransmitted. + //! RFC 6347 §4.2.7: "Alert messages are not retransmitted at all, + //! even when they occur in the context of a handshake." + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, _server, now_hs) = setup_connected_12_pair(now); + now = now_hs; + + // Client sends close_notify + client.close().unwrap(); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "Client should emit close_notify alert" + ); + + // Advance time 5 times (5 seconds each) — no retransmissions should occur + for _ in 0..5 { + now += Duration::from_secs(5); + let _ = client.handle_timeout(now); + let out = drain_outputs(&mut client); + assert!( + out.packets.is_empty(), + "close_notify must not be retransmitted (RFC 6347 §4.2.7)" + ); + } +} diff --git a/third_party/dimpl/tests/dtls12/fragmentation.rs b/third_party/dimpl/tests/dtls12/fragmentation.rs new file mode 100644 index 0000000..b7a2de7 --- /dev/null +++ b/third_party/dimpl/tests/dtls12/fragmentation.rs @@ -0,0 +1,443 @@ +//! DTLS 1.2 fragmentation test (MTU-based). + +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Output}; + +use crate::common::*; +use crate::ossl_helper::{DtlsCertOptions, DtlsEvent, OsslDtlsCert}; + +fn run_client_server_with_mtu(mtu: usize) -> (usize, usize) { + // Initialize logger once across test runs + let _ = env_logger::try_init(); + + // Generate certificates for both client and server + let client_cert_options = DtlsCertOptions::default(); + let client_cert = OsslDtlsCert::new(client_cert_options); + + let server_cert_options = DtlsCertOptions::default(); + let server_cert = OsslDtlsCert::new(server_cert_options); + + // Create server (OpenSSL-backed) + let mut server = server_cert + .new_dtls_impl() + .expect("Failed to create DTLS server"); + + // Server is passive + server.set_active(false); + + // Initialize client + let config = Arc::new( + Config::builder() + .mtu(mtu) + .build() + .expect("Failed to build config"), + ); + + // Get client certificate as DER encoded bytes + let client_x509_der = client_cert + .x509 + .to_der() + .expect("Failed to get client cert DER"); + let client_pkey_der = client_cert + .pkey + .private_key_to_der() + .expect("Failed to get client private key DER"); + + let now = Instant::now(); + + let mut client = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: client_x509_der, + private_key: client_pkey_der, + }, + now, + ); + client.set_active(true); + + // Server events queue + let mut server_events = VecDeque::new(); + + // State + let mut client_connected = false; + let mut server_connected = false; + + // Packet counters + let mut client_to_server_packets: usize = 0; + let mut server_to_client_packets: usize = 0; + let mut max_c2s_len: usize = 0; + + // Test data + let client_test_data = b"Hello from client"; + let server_test_data = b"Hello from server"; + + // Buffers for received data + let mut client_received_data = Vec::new(); + let mut server_received_data = Vec::new(); + + // Drive handshake and data exchange + let mut out_buf = vec![0u8; mtu + 512]; + for _ in 0..20 { + client.handle_timeout(Instant::now()).unwrap(); + + let mut continue_polling = true; + while continue_polling { + let output = client.poll_output(&mut out_buf); + match output { + Output::Packet(data) => { + client_to_server_packets += 1; + if data.len() > max_c2s_len { + max_c2s_len = data.len(); + } + if let Err(e) = server.handle_receive(data, &mut server_events) { + panic!("Server failed to handle client packet: {:?}", e); + } + } + Output::Connected => { + client_connected = true; + } + Output::PeerCert(_cert) => { + // ignore for this test + } + Output::KeyingMaterial(_km, _profile) => { + // After handshake is complete, send test data + client + .send_application_data(client_test_data) + .expect("Failed to send client data"); + } + Output::ApplicationData(data) => { + client_received_data.extend_from_slice(data); + } + Output::Timeout(_) => { + continue_polling = false; + } + _ => {} + } + } + + // Process server events + while let Some(event) = server_events.pop_front() { + match event { + DtlsEvent::Connected => { + server_connected = true; + } + DtlsEvent::RemoteFingerprint(_fp) => {} + DtlsEvent::SrtpKeyingMaterial(_km, _profile) => { + // After handshake is complete, send test data from server + server + .handle_input(server_test_data) + .expect("Failed to send server data"); + } + DtlsEvent::Data(data) => { + server_received_data.extend_from_slice(&data); + } + } + } + + // Send server datagrams to client and count them + while let Some(datagram) = server.poll_datagram() { + server_to_client_packets += 1; + client + .handle_packet(&datagram) + .expect("Failed to handle server packet"); + } + + if client_connected + && server_connected + && !client_received_data.is_empty() + && !server_received_data.is_empty() + { + break; + } + } + + // Basic correctness + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + assert_eq!(server_received_data, client_test_data); + assert_eq!(client_received_data, server_test_data); + + // Ensure the client never emits datagrams above its configured MTU + assert!( + max_c2s_len <= mtu, + "client->server datagram length {} exceeds MTU {}", + max_c2s_len, + mtu + ); + + (client_to_server_packets, server_to_client_packets) +} + +#[test] +fn dtls12_fragmentation_increases_packet_count() { + // Larger MTU should pack more and send fewer packets + let (large_c2s, large_s2c) = run_client_server_with_mtu(1400); + // Smaller MTU forces more fragmentation + let (small_c2s, small_s2c) = run_client_server_with_mtu(100); + + println!( + "packet counts: large(c2s={}, s2c={}), small(c2s={}, s2c={})", + large_c2s, large_s2c, small_c2s, small_s2c + ); + + // Tight-ish bounds informed by expected DTLS handshake/message sizes and packing + assert!( + (3..=8).contains(&large_c2s), + "large MTU client->server packets: {}", + large_c2s + ); + assert!( + (4..=20).contains(&small_c2s), + "small MTU client->server packets: {}", + small_c2s + ); + assert!( + small_c2s > large_c2s, + "small MTU should produce more client->server packets" + ); + + // Optional checks for server->client direction with similarly tight bounds + assert!( + (3..=10).contains(&large_s2c), + "large MTU server->client packets: {}", + large_s2c + ); + assert!( + (5..=20).contains(&small_s2c), + "small MTU server->client packets: {}", + small_s2c + ); + assert!( + small_s2c >= large_s2c, + "small MTU should produce at least as many server->client packets" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_fragmentation_dimpl_to_dimpl() { + //! Verify that a dimpl-to-dimpl handshake completes successfully with a + //! small MTU that forces handshake message fragmentation. + + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config_with_mtu(200); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut max_packet_size = 0usize; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Track max packet size to verify MTU compliance + for p in &client_out.packets { + if p.len() > max_packet_size { + max_packet_size = p.len(); + } + } + for p in &server_out.packets { + if p.len() > max_packet_size { + max_packet_size = p.len(); + } + } + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect with small MTU (dimpl-to-dimpl)" + ); + assert!( + server_connected, + "Server should connect with small MTU (dimpl-to-dimpl)" + ); + assert!( + max_packet_size <= 200, + "All packets should respect 200-byte MTU: max was {}", + max_packet_size + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_fragmented_handshake_with_packet_loss() { + //! Use a small MTU so flights are fragmented into multiple packets. + //! Drop the first packet of the first flight, then trigger a retransmit. + //! Verify the handshake still completes. + + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config_with_mtu(200); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // FLIGHT 1: Client sends ClientHello (possibly fragmented). + // Trigger the initial timeout to start the handshake. + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let flight1 = collect_packets(&mut client); + assert!( + !flight1.is_empty(), + "Client should emit at least one packet for flight 1" + ); + + // Drop the first packet of flight 1 and deliver the rest (if any). + deliver_packets(&flight1[1..], &mut server); + + // Trigger retransmit on the client so it resends the full flight. + trigger_timeout(&mut client, &mut now); + let retransmit1 = collect_packets(&mut client); + assert!(!retransmit1.is_empty(), "Client should retransmit flight 1"); + + // Deliver the full retransmitted flight to the server. + deliver_packets(&retransmit1, &mut server); + + // Now continue the handshake normally until completion. + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + if server_out.connected { + server_connected = true; + } + deliver_packets(&server_out.packets, &mut client); + + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + if client_out.connected { + client_connected = true; + } + deliver_packets(&client_out.packets, &mut server); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect after retransmit of dropped fragment" + ); + assert!( + server_connected, + "Server should connect after retransmit of dropped fragment" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_out_of_order_fragments() { + //! Use a small MTU to force fragmentation. Before delivering each flight, + //! reverse the packet order. Verify the handshake still completes, proving + //! fragment reassembly handles out-of-order delivery. + + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config_with_mtu(200); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Reverse packet order before delivery to simulate out-of-order fragments + let mut client_packets = client_out.packets; + let mut server_packets = server_out.packets; + client_packets.reverse(); + server_packets.reverse(); + + deliver_packets(&client_packets, &mut server); + deliver_packets(&server_packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect with out-of-order fragments" + ); + assert!( + server_connected, + "Server should connect with out-of-order fragments" + ); +} diff --git a/third_party/dimpl/tests/dtls12/handshake.rs b/third_party/dimpl/tests/dtls12/handshake.rs new file mode 100644 index 0000000..a6f1990 --- /dev/null +++ b/third_party/dimpl/tests/dtls12/handshake.rs @@ -0,0 +1,872 @@ +//! DTLS 1.2 handshake tests (cookie retry, parallel handshakes, basic handshake). + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, SrtpProfile}; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_cookie_retry_proceeds_to_server_hello() { + //! Verify that after HelloVerifyRequest, the ClientHello with cookie + //! is properly processed and the server sends ServerHello (not another HVR). + + use dimpl::certificate::generate_self_signed_certificate; + + let now = Instant::now(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new(Config::builder().build().expect("Failed to build config")); + + let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); + client.set_active(true); + + let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); + server.set_active(false); + + // FLIGHT 1: Client sends ClientHello (no cookie) + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let f1 = collect_packets(&mut client); + assert!(!f1.is_empty(), "client should emit ClientHello"); + + // Verify it's a ClientHello + let f1_hs_types: Vec = f1.iter().flat_map(|p| parse_handshake_types(p)).collect(); + assert!( + f1_hs_types.contains(&CLIENT_HELLO), + "flight 1 should contain ClientHello, got {:?}", + f1_hs_types + ); + + // Deliver to server + for p in &f1 { + server.handle_packet(p).expect("server recv f1"); + } + + // FLIGHT 2: Server sends HelloVerifyRequest + server.handle_timeout(now).expect("server arm flight 2"); + let f2 = collect_packets(&mut server); + assert!(!f2.is_empty(), "server should emit HelloVerifyRequest"); + + // Verify it's a HelloVerifyRequest + let f2_hs_types: Vec = f2.iter().flat_map(|p| parse_handshake_types(p)).collect(); + assert!( + f2_hs_types.contains(&HELLO_VERIFY_REQUEST), + "flight 2 should contain HelloVerifyRequest, got {:?}", + f2_hs_types + ); + + // Deliver to client + for p in &f2 { + client.handle_packet(p).expect("client recv f2"); + } + + // FLIGHT 3: Client sends ClientHello WITH cookie (message_seq=1 per RFC 6347) + client.handle_timeout(now).expect("client arm flight 3"); + let f3 = collect_packets(&mut client); + assert!(!f3.is_empty(), "client should emit ClientHello with cookie"); + + let f3_hs_types: Vec = f3.iter().flat_map(|p| parse_handshake_types(p)).collect(); + assert!( + f3_hs_types.contains(&CLIENT_HELLO), + "flight 3 should contain ClientHello (with cookie), got {:?}", + f3_hs_types + ); + + // Deliver to server - THIS IS WHERE THE BUG MANIFESTS + for p in &f3 { + server.handle_packet(p).expect("server recv f3"); + } + + // FLIGHT 4: Server should send ServerHello, Certificate, etc. - NOT HelloVerifyRequest + server.handle_timeout(now).expect("server arm flight 4"); + let f4 = collect_packets(&mut server); + assert!( + !f4.is_empty(), + "server should emit flight 4 after ClientHello with cookie" + ); + + let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); + + // THE KEY ASSERTION: Server should NOT send another HelloVerifyRequest + assert!( + !f4_hs_types.contains(&HELLO_VERIFY_REQUEST), + "server should NOT send HelloVerifyRequest after valid cookie - BUG! got {:?}", + f4_hs_types + ); + + // Server should send ServerHello + assert!( + f4_hs_types.contains(&SERVER_HELLO), + "server should send ServerHello after valid cookie, got {:?}", + f4_hs_types + ); + + // Should also contain Certificate and ServerHelloDone + assert!( + f4_hs_types.contains(&CERTIFICATE), + "server should send Certificate, got {:?}", + f4_hs_types + ); + assert!( + f4_hs_types.contains(&SERVER_HELLO_DONE), + "server should send ServerHelloDone, got {:?}", + f4_hs_types + ); + + println!( + "SUCCESS: Server correctly processed ClientHello with cookie and sent ServerHello flight" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_parallel_handshakes_with_cookies() { + //! Test multiple parallel DTLS handshakes to ensure cookie handling + //! works correctly under concurrent load (the original bug scenario). + + use dimpl::certificate::generate_self_signed_certificate; + + let now = Instant::now(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new(Config::builder().build().expect("Failed to build config")); + + // Create 5 parallel client-server pairs + let mut pairs: Vec<(Dtls, Dtls)> = (0..5) + .map(|_| { + let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); + client.set_active(true); + let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); + server.set_active(false); + (client, server) + }) + .collect(); + + // Run all handshakes through the cookie exchange phase + for (i, (client, server)) in pairs.iter_mut().enumerate() { + // Flight 1: ClientHello + client.handle_timeout(now).expect("client timeout"); + client.handle_timeout(now).expect("client arm f1"); + let f1 = collect_packets(client); + for p in &f1 { + server.handle_packet(p).expect("server recv f1"); + } + + // Flight 2: HelloVerifyRequest + server.handle_timeout(now).expect("server arm f2"); + let f2 = collect_packets(server); + for p in &f2 { + client.handle_packet(p).expect("client recv f2"); + } + + // Flight 3: ClientHello with cookie + client.handle_timeout(now).expect("client arm f3"); + let f3 = collect_packets(client); + for p in &f3 { + server.handle_packet(p).expect("server recv f3"); + } + + // Flight 4: Should be ServerHello, not HelloVerifyRequest + server.handle_timeout(now).expect("server arm f4"); + let f4 = collect_packets(server); + let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); + + assert!( + !f4_hs_types.contains(&HELLO_VERIFY_REQUEST), + "pair {}: server sent HelloVerifyRequest instead of ServerHello - BUG!", + i + ); + assert!( + f4_hs_types.contains(&SERVER_HELLO), + "pair {}: server should send ServerHello, got {:?}", + i, + f4_hs_types + ); + } + + println!( + "SUCCESS: All {} parallel handshakes processed cookies correctly", + pairs.len() + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_retransmit_no_cookie_after_cookie_sent() { + //! Simulates the real Firefox bug scenario: + //! 1. Client sends ClientHello (no cookie) + //! 2. Server sends HelloVerifyRequest + //! 3. Client sends ClientHello (with cookie) + //! 4. Client's timer fires and it ALSO retransmits the original no-cookie ClientHello + //! 5. Server should NOT get confused by this out-of-order retransmit + + use dimpl::certificate::generate_self_signed_certificate; + + let now = Instant::now(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new(Config::builder().build().expect("Failed to build config")); + + let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); + client.set_active(true); + + let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); + server.set_active(false); + + // Flight 1: ClientHello (no cookie) + client.handle_timeout(now).expect("client timeout"); + client.handle_timeout(now).expect("client arm f1"); + let f1 = collect_packets(&mut client); + assert!(!f1.is_empty()); + + // Save a copy of the original no-cookie ClientHello for later retransmit + let f1_copy = f1.clone(); + + // Deliver to server + for p in &f1 { + server.handle_packet(p).expect("server recv f1"); + } + + // Flight 2: HelloVerifyRequest + server.handle_timeout(now).expect("server arm f2"); + let f2 = collect_packets(&mut server); + assert!(!f2.is_empty()); + + // Deliver to client + for p in &f2 { + client.handle_packet(p).expect("client recv f2"); + } + + // Flight 3: ClientHello WITH cookie + client.handle_timeout(now).expect("client arm f3"); + let f3 = collect_packets(&mut client); + assert!(!f3.is_empty()); + + // Deliver the cookie version to server + for p in &f3 { + server.handle_packet(p).expect("server recv f3 with cookie"); + } + + // NOW simulate Firefox's retransmit timer firing - send the ORIGINAL + // no-cookie ClientHello again (this is what Firefox does in the real bug) + for p in &f1_copy { + // This should not cause the handshake to fail + server + .handle_packet(p) + .expect("server recv retransmit of no-cookie CH"); + } + + // Server should still send ServerHello flight, not another HelloVerifyRequest + server.handle_timeout(now).expect("server arm f4"); + let f4 = collect_packets(&mut server); + assert!(!f4.is_empty(), "server should emit flight 4"); + + let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); + + // The key test: even after receiving the retransmitted no-cookie ClientHello, + // the server should proceed with ServerHello (having already processed the cookie version) + assert!( + f4_hs_types.contains(&SERVER_HELLO), + "server should send ServerHello even after retransmit of no-cookie CH, got {:?}", + f4_hs_types + ); + + println!("SUCCESS: Server correctly handled out-of-order retransmit scenario"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_retransmit_no_cookie_before_cookie_received() { + //! Tests the specific bug scenario from webrtc deployments: + //! + //! 1. Client sends ClientHello (seq=0, no cookie) + //! 2. Server sends HelloVerifyRequest, clears queue_rx + //! 3. Client retransmits old ClientHello (seq=0, no cookie) - HVR was lost/delayed + //! 4. Server resends HelloVerifyRequest (correct), but OLD ClientHello must NOT + //! be inserted into queue_rx, otherwise it blocks the new ClientHello + //! 5. Client sends ClientHello (seq=1, with cookie) + //! 6. Server should process it and send ServerHello + + use dimpl::certificate::generate_self_signed_certificate; + + let now = Instant::now(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new(Config::builder().build().expect("Failed to build config")); + + let mut client = Dtls::new_12(config.clone(), client_cert.clone(), now); + client.set_active(true); + + let mut server = Dtls::new_12(config.clone(), server_cert.clone(), now); + server.set_active(false); + + // Flight 1: ClientHello (no cookie) + client.handle_timeout(now).expect("client timeout"); + client.handle_timeout(now).expect("client arm f1"); + let f1 = collect_packets(&mut client); + assert!(!f1.is_empty()); + + // Save a copy of the original no-cookie ClientHello for retransmit simulation + let f1_copy = f1.clone(); + + // Deliver to server + for p in &f1 { + server.handle_packet(p).expect("server recv f1"); + } + + // Flight 2: HelloVerifyRequest + server.handle_timeout(now).expect("server arm f2"); + let f2 = collect_packets(&mut server); + assert!(!f2.is_empty()); + + // Simulate: HVR is "lost" - don't deliver to client yet + // Instead, client's retransmit timer fires and sends the old ClientHello again + + // THIS IS THE BUG TRIGGER: old ClientHello (seq=0) arrives at server + // BEFORE the cookie-bearing ClientHello (seq=1) + for p in &f1_copy { + server + .handle_packet(p) + .expect("server recv retransmit of no-cookie CH"); + } + + // Server should resend HelloVerifyRequest (this is correct behavior) + // The bug was that the old ClientHello got inserted into queue_rx + let f2_resend = collect_packets(&mut server); + let f2_resend_types: Vec = f2_resend + .iter() + .flat_map(|p| parse_handshake_types(p)) + .collect(); + assert!( + f2_resend_types.contains(&HELLO_VERIFY_REQUEST), + "server should resend HelloVerifyRequest after duplicate, got {:?}", + f2_resend_types + ); + + // Now deliver the original HVR to client + for p in &f2 { + client.handle_packet(p).expect("client recv f2"); + } + + // Flight 3: ClientHello WITH cookie (seq=1) + client.handle_timeout(now).expect("client arm f3"); + let f3 = collect_packets(&mut client); + assert!(!f3.is_empty()); + + // Deliver to server - THIS IS WHERE THE BUG MANIFESTED + // Before fix: queue_rx had old ClientHello (seq=0), blocking this one + for p in &f3 { + server.handle_packet(p).expect("server recv f3 with cookie"); + } + + // Server should now send ServerHello flight + server.handle_timeout(now).expect("server arm f4"); + let f4 = collect_packets(&mut server); + assert!(!f4.is_empty(), "server should emit flight 4"); + + let f4_hs_types: Vec = f4.iter().flat_map(|p| parse_handshake_types(p)).collect(); + + // THE KEY ASSERTION: Server must NOT be stuck sending HelloVerifyRequest + assert!( + !f4_hs_types.contains(&HELLO_VERIFY_REQUEST), + "server should NOT resend HelloVerifyRequest after valid cookie, got {:?}", + f4_hs_types + ); + + // Server should send ServerHello + assert!( + f4_hs_types.contains(&SERVER_HELLO), + "server should send ServerHello after cookie CH, got {:?}", + f4_hs_types + ); + + println!("SUCCESS: Old duplicate ClientHello did not block new ClientHello with cookie"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_basic_handshake() { + //! Complete a full dimpl-to-dimpl DTLS 1.2 handshake and verify both + //! client and server reach the connected state. + + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_with_keying_material() { + //! Complete a DTLS 1.2 handshake with SRTP profile configured and verify + //! both sides derive identical SRTP keying material. + + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + assert_eq!( + client_km.0, server_km.0, + "Client and server keying material should match" + ); + assert_eq!( + client_km.1, server_km.1, + "Client and server SRTP profile should match" + ); + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_peer_certificate_exchange() { + //! Complete a DTLS 1.2 handshake and verify the client can access the + //! server's certificate and the server can access the client's certificate. + + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let expected_client_cert = client_cert.certificate.clone(); + let expected_server_cert = server_cert.certificate.clone(); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_peer_cert: Option> = None; + let mut server_peer_cert: Option> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(cert) = client_out.peer_cert { + client_peer_cert = Some(cert); + } + if let Some(cert) = server_out.peer_cert { + server_peer_cert = Some(cert); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_peer_cert.is_some() && server_peer_cert.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_peer_cert.is_some(), + "Client should receive server's certificate" + ); + assert!( + server_peer_cert.is_some(), + "Server should receive client's certificate" + ); + + assert_eq!( + client_peer_cert.unwrap(), + expected_server_cert, + "Client should receive server's certificate" + ); + assert_eq!( + server_peer_cert.unwrap(), + expected_client_cert, + "Server should receive client's certificate" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_client_certificate_auth() { + //! Configure the server to require a client certificate, complete the + //! handshake, and verify the server received and validated the client + //! certificate. + + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let expected_client_cert = client_cert.certificate.clone(); + + let config = Arc::new( + Config::builder() + .require_client_certificate(true) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut server_connected = false; + let mut server_peer_cert: Option> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if server_out.connected { + server_connected = true; + } + if let Some(cert) = server_out.peer_cert { + server_peer_cert = Some(cert); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if server_connected && server_peer_cert.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + server_connected, + "Server should be connected after client certificate auth" + ); + assert!( + server_peer_cert.is_some(), + "Server should receive client's certificate" + ); + assert_eq!( + server_peer_cert.unwrap(), + expected_client_cert, + "Server should receive the correct client certificate" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_secp384r1_key_exchange() { + //! Configure to use only P-384 for key exchange, complete the handshake, + //! and verify both sides reach connected. + + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::aws_lc_rs; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Build a crypto provider with only the P-384 key exchange group. + let mut provider = aws_lc_rs::default_provider(); + let p384_vec: Vec<&'static dyn dimpl::crypto::SupportedKxGroup> = provider + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == dimpl::NamedGroup::Secp384r1) + .collect(); + // leak: intentional leak to produce a &'static slice for the provider field + let p384_only: &'static [&'static dyn dimpl::crypto::SupportedKxGroup] = + Box::leak(p384_vec.into_boxed_slice()); + provider.kx_groups = p384_only; + + let config = Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("Failed to build config with P-384 only"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected with P-384"); + assert!(server_connected, "Server should be connected with P-384"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_timeout_expires() { + //! Create client and server but never deliver packets. Trigger timeouts + //! repeatedly and verify the handshake eventually times out/fails. + + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use a short handshake timeout to speed up the test. + let config = Arc::new( + Config::builder() + .handshake_timeout(Duration::from_secs(5)) + .flight_retries(2) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + let mut client_timed_out = false; + let mut server_timed_out = false; + + // Run for many iterations, advancing time each round, but never deliver + // packets between client and server. + for _ in 0..100 { + if !client_timed_out { + match client.handle_timeout(now) { + Ok(()) => { + // Drain outputs but discard packets (never deliver them) + let _ = drain_outputs(&mut client); + } + Err(_) => { + client_timed_out = true; + } + } + } + + if !server_timed_out { + match server.handle_timeout(now) { + Ok(()) => { + let _ = drain_outputs(&mut server); + } + Err(_) => { + server_timed_out = true; + } + } + } + + if client_timed_out && server_timed_out { + break; + } + + now += Duration::from_secs(2); + } + + assert!( + client_timed_out, + "Client handshake should eventually time out when no packets are delivered" + ); +} + +#[test] +fn dtls12_handshake_p384_certificate() { + //! DTLS 1.2 handshake where both sides use P-384 ECDSA certificates. + //! Regression test: the server's ServerKeyExchange must sign with the + //! same hash algorithm it advertises on the wire (SHA-384 for P-384). + + use crate::ossl_helper::{DtlsCertOptions, DtlsPKeyType, OsslDtlsCert}; + + let client_cert = OsslDtlsCert::new(DtlsCertOptions { + common_name: "WebRTC".into(), + pkey_type: DtlsPKeyType::EcDsaP384, + }); + let server_cert = OsslDtlsCert::new(DtlsCertOptions { + common_name: "WebRTC".into(), + pkey_type: DtlsPKeyType::EcDsaP384, + }); + + let config = dtls12_config(); + let mut now = Instant::now(); + + let mut client = Dtls::new_12( + Arc::clone(&config), + dimpl::DtlsCertificate { + certificate: client_cert.x509.to_der().expect("client cert der"), + private_key: client_cert + .pkey + .private_key_to_der() + .expect("client key der"), + }, + now, + ); + client.set_active(true); + + let mut server = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: server_cert.x509.to_der().expect("server cert der"), + private_key: server_cert + .pkey + .private_key_to_der() + .expect("server key der"), + }, + now, + ); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect with P-384 cert"); + assert!(server_connected, "Server should connect with P-384 cert"); +} diff --git a/third_party/dimpl/tests/dtls12/main.rs b/third_party/dimpl/tests/dtls12/main.rs new file mode 100644 index 0000000..c77bc49 --- /dev/null +++ b/third_party/dimpl/tests/dtls12/main.rs @@ -0,0 +1,13 @@ +#[path = "../ossl/mod.rs"] +mod ossl_helper; + +mod common; +mod crypto; +mod data; +mod edge; +mod fragmentation; +mod handshake; +mod ossl; +mod psk; +mod reorder; +mod retransmit; diff --git a/third_party/dimpl/tests/dtls12/ossl.rs b/third_party/dimpl/tests/dtls12/ossl.rs new file mode 100644 index 0000000..e807bba --- /dev/null +++ b/third_party/dimpl/tests/dtls12/ossl.rs @@ -0,0 +1,892 @@ +//! DTLS 1.2 interop tests: dimpl <-> OpenSSL (client + server). + +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::Instant; + +use dimpl::{Config, Dtls, Output}; + +use crate::ossl_helper::{DtlsCertOptions, DtlsEvent, OsslDtlsCert}; + +#[test] +fn dtls12_ossl_client_handshake() { + env_logger::try_init().ok(); + + // Generate certificates for both client and server + let client_cert_options = DtlsCertOptions::default(); + let client_cert = OsslDtlsCert::new(client_cert_options); + + let server_cert_options = DtlsCertOptions::default(); + let server_cert = OsslDtlsCert::new(server_cert_options); + + // Create server + let mut server = server_cert + .new_dtls_impl() + .expect("Failed to create DTLS server"); + + // Set server as passive (accepting connections) + server.set_active(false); + + // Initialize client + let config = Arc::new(Config::default()); + + // Get client certificate as DER encoded bytes + let client_x509_der = client_cert + .x509 + .to_der() + .expect("Failed to get client cert DER"); + let client_pkey_der = client_cert + .pkey + .private_key_to_der() + .expect("Failed to get client private key DER"); + + let now = Instant::now(); + + let mut client = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: client_x509_der, + private_key: client_pkey_der, + }, + now, + ); + client.set_active(true); + + // Collection to store server events + let mut server_events = VecDeque::new(); + + // Stored outputs for verification + let mut client_connected = false; + let mut client_peer_cert = None; + let mut client_keying_material = None; + let mut server_connected = false; + // Fingerprint is only used for logging + let mut server_keying_material = None; + + // Test data to exchange + let client_test_data = b"Hello from client"; + let server_test_data = b"Hello from server"; + + // Buffers for received data + let mut client_received_data = Vec::new(); + let mut server_received_data = Vec::new(); + let mut out_buf = vec![0u8; 2048]; + + // Simulate handshake and data exchange + // This might need several iterations until both sides consider themselves connected + for _ in 0..20 { + client.handle_timeout(Instant::now()).unwrap(); + // Poll client for output + let mut continue_polling = true; + while continue_polling { + // poll_output returns an Output enum (not Option wrapped) + let output = client.poll_output(&mut out_buf); + match output { + Output::Packet(data) => { + // Client data goes to server + if let Err(e) = server.handle_receive(data, &mut server_events) { + panic!("Server failed to handle client packet: {:?}", e); + } + } + Output::Connected => { + client_connected = true; + println!("Client connected"); + } + Output::PeerCert(_cert) => { + client_peer_cert = Some(true); + println!("Client received peer certificate"); + } + Output::KeyingMaterial(km, profile) => { + client_keying_material = Some((km.as_ref().to_vec(), profile)); + println!("Client received keying material for profile: {:?}", profile); + + // After handshake is complete, send test data + client + .send_application_data(client_test_data) + .expect("Failed to send client data"); + } + Output::ApplicationData(data) => { + client_received_data.extend_from_slice(data); + println!( + "Client received {} bytes of application data: {:02x?}", + data.len(), + data + ); + } + Output::Timeout(_) => { + // If we get a timeout, it means there are no more packets ready + // so we stop polling in this iteration + continue_polling = false; + } + _ => {} + } + } + + // Process server events + while let Some(event) = server_events.pop_front() { + match event { + DtlsEvent::Connected => { + server_connected = true; + println!("Server connected"); + } + DtlsEvent::RemoteFingerprint(fp) => { + println!("Server received fingerprint: {}", fp); + // We don't need to store the fingerprint, just log it + } + DtlsEvent::SrtpKeyingMaterial(km, profile) => { + server_keying_material = Some((km, profile)); + println!("Server received keying material for profile: {:?}", profile); + + // After handshake is complete, send test data from server + server + .handle_input(server_test_data) + .expect("Failed to send server data"); + } + DtlsEvent::Data(data) => { + server_received_data.extend_from_slice(&data); + println!( + "Server received {} bytes of application data: {:02x?}", + data.len(), + data + ); + } + } + } + + // Send server datagrams to client + while let Some(datagram) = server.poll_datagram() { + client + .handle_packet(&datagram) + .expect("Failed to handle server packet"); + } + + // If both connected and data exchanged, we can break + if client_connected + && server_connected + && !client_received_data.is_empty() + && !server_received_data.is_empty() + { + break; + } + } + + // Verify both sides connected + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Verify client received server certificate + assert!( + client_peer_cert.is_some(), + "Client should have received peer certificate" + ); + + // Verify client and server negotiated keying material + assert!( + client_keying_material.is_some(), + "Client should have received keying material" + ); + assert!( + server_keying_material.is_some(), + "Server should have received keying material" + ); + + // Verify they negotiated the same SRTP profile + let (client_km, client_profile) = client_keying_material.unwrap(); + let (server_km, server_profile) = server_keying_material.unwrap(); + assert_eq!( + client_profile, server_profile, + "Client and server should negotiate the same SRTP profile" + ); + + // Verify keying material has the right length + assert!( + !client_km.is_empty(), + "Client keying material should not be empty" + ); + assert_eq!( + client_km.len(), + server_km.len(), + "Client and server keying material should have the same length" + ); + + // Verify data exchange + assert_eq!( + server_received_data, client_test_data, + "Server should receive correct data from client" + ); + assert_eq!( + client_received_data, server_test_data, + "Client should receive correct data from server" + ); +} + +#[test] +fn dtls12_ossl_server_handshake() { + let _ = env_logger::try_init(); + + // Generate certificates for both server (dimpl) and client (OpenSSL) + let server_cert_options = DtlsCertOptions::default(); + let server_cert = OsslDtlsCert::new(server_cert_options); + + let client_cert_options = DtlsCertOptions::default(); + let client_cert = OsslDtlsCert::new(client_cert_options); + + // Create OpenSSL DTLS client (active) + let mut client = client_cert + .new_dtls_impl() + .expect("Failed to create DTLS client"); + client.set_active(true); + + // Initialize dimpl server + let config = Arc::new(Config::default()); + + // dimpl Server expects its own certificate/private key (DER) + let server_x509_der = server_cert + .x509 + .to_der() + .expect("Failed to get server cert DER"); + let server_pkey_der = server_cert + .pkey + .private_key_to_der() + .expect("Failed to get server private key DER"); + + let now = Instant::now(); + + let mut server = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: server_x509_der, + private_key: server_pkey_der, + }, + now, + ); + server.set_active(false); + + // Buffers and flags + let mut client_events = VecDeque::new(); + + let mut server_connected = false; + let mut client_connected = false; + + let mut saw_server_peer_cert = false; + let mut server_keying_material = None; + let mut client_keying_material = None; + + // Test data + let client_test_data = b"Hello from client"; + let server_test_data = b"Hello from server"; + + let mut client_received_data = Vec::new(); + let mut server_received_data = Vec::new(); + + // Drive handshake and data exchange + let mut out_buf = vec![0u8; 2048]; + for _ in 0..40 { + server.handle_timeout(Instant::now()).unwrap(); + client.handle_handshake(&mut client_events).unwrap(); + // 1) Drain client (OpenSSL) outgoing datagrams to the server + while let Some(datagram) = client.poll_datagram() { + server + .handle_packet(&datagram) + .expect("Server failed to handle client packet"); + } + + // 2) Poll server outputs and feed to client + loop { + match server.poll_output(&mut out_buf) { + Output::Packet(data) => { + client + .handle_receive(data, &mut client_events) + .expect("Client failed to handle server packet"); + } + Output::Connected => { + server_connected = true; + } + Output::PeerCert(_cert) => { + saw_server_peer_cert = true; + } + Output::KeyingMaterial(km, profile) => { + server_keying_material = Some((km.as_ref().to_vec(), profile)); + // As soon as handshake completes from server side, send server app data + server + .send_application_data(server_test_data) + .expect("Server failed to send app data"); + } + Output::ApplicationData(data) => { + server_received_data.extend_from_slice(data); + } + Output::Timeout(_) => break, + _ => {} + } + } + + // 3) Process client (OpenSSL) events + while let Some(event) = client_events.pop_front() { + match event { + DtlsEvent::Connected => { + client_connected = true; + // Once client is connected, send app data from client to server + client + .handle_input(client_test_data) + .expect("Client failed to send app data"); + } + DtlsEvent::RemoteFingerprint(_fp) => { + // Fingerprint not used in assertions here + } + DtlsEvent::SrtpKeyingMaterial(km, profile) => { + client_keying_material = Some((km, profile)); + } + DtlsEvent::Data(data) => { + client_received_data.extend_from_slice(&data); + } + } + } + + // 4) Deliver any further client datagrams produced after app writes + while let Some(datagram) = client.poll_datagram() { + server + .handle_packet(&datagram) + .expect("Server failed to handle client packet"); + } + + if server_connected + && client_connected + && !client_received_data.is_empty() + && !server_received_data.is_empty() + { + break; + } + } + + // Assertions + assert!(server_connected, "Server should be connected"); + assert!(client_connected, "Client should be connected"); + + assert!( + saw_server_peer_cert, + "Server should have received peer certificate" + ); + + assert!( + server_keying_material.is_some(), + "Server should have SRTP keying material" + ); + assert!( + client_keying_material.is_some(), + "Client should have SRTP keying material" + ); + + let (server_km, server_profile) = server_keying_material.unwrap(); + let (client_km, client_profile) = client_keying_material.unwrap(); + + assert_eq!( + server_profile, client_profile, + "Both sides should negotiate same SRTP profile" + ); + assert!( + !server_km.is_empty(), + "Server keying material should not be empty" + ); + assert_eq!( + server_km.len(), + client_km.len(), + "Keying material length should match" + ); + + assert_eq!( + server_received_data, client_test_data, + "Server should receive correct data" + ); + assert_eq!( + client_received_data, server_test_data, + "Client should receive correct data" + ); +} + +#[test] +fn dtls12_ossl_client_retransmit_on_timeout() { + let _ = env_logger::try_init(); + + // Generate certificates for both client and server + let client_cert_options = DtlsCertOptions::default(); + let client_cert = OsslDtlsCert::new(client_cert_options); + + let server_cert_options = DtlsCertOptions::default(); + let server_cert = OsslDtlsCert::new(server_cert_options); + + // Create OpenSSL server (passive) + let mut server = server_cert + .new_dtls_impl() + .expect("Failed to create DTLS server"); + server.set_active(false); + + // Initialize dimpl client + let config = Arc::new(Config::default()); + let client_x509_der = client_cert + .x509 + .to_der() + .expect("Failed to get client cert DER"); + let client_pkey_der = client_cert + .pkey + .private_key_to_der() + .expect("Failed to get client private key DER"); + + let mut now = Instant::now(); + let mut client = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: client_x509_der, + private_key: client_pkey_der, + }, + now, + ); + client.set_active(true); + + let mut server_events = VecDeque::new(); + let mut out_buf = vec![0u8; 2048]; + + // Trigger the initial client flight + client.handle_timeout(now).unwrap(); + + // Poll client: collect the first flight but DROP it (don't deliver to server) + let mut first_flight_dropped = false; + loop { + match client.poll_output(&mut out_buf) { + Output::Packet(_data) => { + // Intentionally drop the packet -- do not deliver to server + first_flight_dropped = true; + } + Output::Timeout(_) => break, + _ => {} + } + } + assert!( + first_flight_dropped, + "Client should have produced at least one packet in the first flight" + ); + + // The first handle_timeout armed the flight timer, but send_client_hello called + // flight_begin which reset it to Unarmed. We need to call handle_timeout again to + // re-arm the timer, then advance past that armed timeout to trigger the resend. + + // Advance a small amount and call handle_timeout to re-arm the flight timer + now += std::time::Duration::from_millis(50); + client.handle_timeout(now).unwrap(); + + // Poll to get the timeout value (no packets expected here) + let flight_timeout; + loop { + if let Output::Timeout(t) = client.poll_output(&mut out_buf) { + flight_timeout = t; + break; + } + } + + // Advance past the flight timeout to trigger retransmission + now = flight_timeout + std::time::Duration::from_millis(1); + client.handle_timeout(now).unwrap(); + + // Poll client again: this time deliver the retransmitted flight to the server + let mut retransmitted = false; + loop { + match client.poll_output(&mut out_buf) { + Output::Packet(data) => { + retransmitted = true; + if let Err(e) = server.handle_receive(data, &mut server_events) { + panic!( + "Server failed to handle retransmitted client packet: {:?}", + e + ); + } + } + Output::Timeout(_) => break, + _ => {} + } + } + assert!( + retransmitted, + "Client should have retransmitted packets after timeout" + ); + + // Now run the normal handshake loop to completion + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..20 { + // Process server events + while let Some(event) = server_events.pop_front() { + if let DtlsEvent::Connected = event { + server_connected = true; + } + } + + // Send server datagrams to client + while let Some(datagram) = server.poll_datagram() { + client + .handle_packet(&datagram) + .expect("Failed to handle server packet"); + } + + now += std::time::Duration::from_millis(50); + client.handle_timeout(now).unwrap(); + + // Poll client for output + loop { + match client.poll_output(&mut out_buf) { + Output::Packet(data) => { + if let Err(e) = server.handle_receive(data, &mut server_events) { + panic!("Server failed to handle client packet: {:?}", e); + } + } + Output::Connected => { + client_connected = true; + } + Output::Timeout(_) => break, + _ => {} + } + } + + if client_connected && server_connected { + break; + } + } + + assert!( + client_connected, + "Client should be connected after retransmit" + ); + assert!( + server_connected, + "Server should be connected after retransmit" + ); +} + +#[test] +fn dtls12_ossl_client_handles_duplicates() { + let _ = env_logger::try_init(); + + // Generate certificates for both client and server + let client_cert_options = DtlsCertOptions::default(); + let client_cert = OsslDtlsCert::new(client_cert_options); + + let server_cert_options = DtlsCertOptions::default(); + let server_cert = OsslDtlsCert::new(server_cert_options); + + // Create OpenSSL server (passive) + let mut server = server_cert + .new_dtls_impl() + .expect("Failed to create DTLS server"); + server.set_active(false); + + // Initialize dimpl client + let config = Arc::new(Config::default()); + let client_x509_der = client_cert + .x509 + .to_der() + .expect("Failed to get client cert DER"); + let client_pkey_der = client_cert + .pkey + .private_key_to_der() + .expect("Failed to get client private key DER"); + + let mut client = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: client_x509_der, + private_key: client_pkey_der, + }, + Instant::now(), + ); + client.set_active(true); + + let mut server_events = VecDeque::new(); + let mut client_connected = false; + let mut server_connected = false; + let mut client_keying_material = None; + let mut server_keying_material = None; + + let client_test_data = b"Hello from client"; + let server_test_data = b"Hello from server"; + let mut client_received_data = Vec::new(); + let mut server_received_data = Vec::new(); + let mut out_buf = vec![0u8; 2048]; + + for _ in 0..20 { + client.handle_timeout(Instant::now()).unwrap(); + + // Poll client for output + loop { + match client.poll_output(&mut out_buf) { + Output::Packet(data) => { + if let Err(e) = server.handle_receive(data, &mut server_events) { + panic!("Server failed to handle client packet: {:?}", e); + } + } + Output::Connected => { + client_connected = true; + } + Output::KeyingMaterial(km, profile) => { + client_keying_material = Some((km.as_ref().to_vec(), profile)); + client + .send_application_data(client_test_data) + .expect("Failed to send client data"); + } + Output::ApplicationData(data) => { + client_received_data.extend_from_slice(data); + } + Output::Timeout(_) => break, + _ => {} + } + } + + // Process server events + while let Some(event) = server_events.pop_front() { + match event { + DtlsEvent::Connected => { + server_connected = true; + } + DtlsEvent::SrtpKeyingMaterial(km, profile) => { + server_keying_material = Some((km, profile)); + server + .handle_input(server_test_data) + .expect("Failed to send server data"); + } + DtlsEvent::Data(data) => { + server_received_data.extend_from_slice(&data); + } + _ => {} + } + } + + // Collect all server datagrams, then deliver each one TWICE to the client + let mut server_datagrams = Vec::new(); + while let Some(datagram) = server.poll_datagram() { + server_datagrams.push(datagram); + } + for datagram in &server_datagrams { + // First delivery + client + .handle_packet(datagram) + .expect("Failed to handle server packet (first delivery)"); + // Second delivery (duplicate) + let _ = client.handle_packet(datagram); + } + + if client_connected + && server_connected + && !client_received_data.is_empty() + && !server_received_data.is_empty() + { + break; + } + } + + // Verify handshake completed despite duplicates + assert!( + client_connected, + "Client should be connected despite duplicates" + ); + assert!( + server_connected, + "Server should be connected despite duplicates" + ); + + // Verify keying material was negotiated + assert!( + client_keying_material.is_some(), + "Client should have received keying material" + ); + assert!( + server_keying_material.is_some(), + "Server should have received keying material" + ); + + let (_client_km, client_profile) = client_keying_material.unwrap(); + let (_server_km, server_profile) = server_keying_material.unwrap(); + assert_eq!( + client_profile, server_profile, + "Client and server should negotiate the same SRTP profile" + ); + + // Verify data exchange succeeded + assert_eq!( + server_received_data, client_test_data, + "Server should receive correct data from client" + ); + assert_eq!( + client_received_data, server_test_data, + "Client should receive correct data from server" + ); +} + +#[test] +fn dtls12_ossl_server_bidirectional_data() { + let _ = env_logger::try_init(); + + // Generate certificates for both server (dimpl) and client (OpenSSL) + let server_cert_options = DtlsCertOptions::default(); + let server_cert = OsslDtlsCert::new(server_cert_options); + + let client_cert_options = DtlsCertOptions::default(); + let client_cert = OsslDtlsCert::new(client_cert_options); + + // Create OpenSSL DTLS client (active) + let mut client = client_cert + .new_dtls_impl() + .expect("Failed to create DTLS client"); + client.set_active(true); + + // Initialize dimpl server + let config = Arc::new(Config::default()); + let server_x509_der = server_cert + .x509 + .to_der() + .expect("Failed to get server cert DER"); + let server_pkey_der = server_cert + .pkey + .private_key_to_der() + .expect("Failed to get server private key DER"); + + let mut server = Dtls::new_12( + config, + dimpl::DtlsCertificate { + certificate: server_x509_der, + private_key: server_pkey_der, + }, + Instant::now(), + ); + server.set_active(false); + + let mut client_events = VecDeque::new(); + let mut server_connected = false; + let mut client_connected = false; + + // Test data for bidirectional exchange: initial messages + replies + let server_test_data = b"Hello from server"; + let client_test_data = b"Hello from client"; + let server_reply_data = b"Server got your message"; + let client_reply_data = b"Client got your message"; + + let mut client_received_data = Vec::new(); + let mut server_received_data = Vec::new(); + let mut server_first_sent = false; + let mut client_first_sent = false; + let mut server_reply_sent = false; + let mut client_reply_sent = false; + + let mut out_buf = vec![0u8; 2048]; + for _ in 0..40 { + server.handle_timeout(Instant::now()).unwrap(); + client.handle_handshake(&mut client_events).unwrap(); + + // 1) Drain client (OpenSSL) outgoing datagrams to the server + while let Some(datagram) = client.poll_datagram() { + server + .handle_packet(&datagram) + .expect("Server failed to handle client packet"); + } + + // 2) Poll server outputs and feed to client + loop { + match server.poll_output(&mut out_buf) { + Output::Packet(data) => { + client + .handle_receive(data, &mut client_events) + .expect("Client failed to handle server packet"); + } + Output::Connected => { + server_connected = true; + } + Output::KeyingMaterial(_km, _profile) if !server_first_sent => { + // Server handshake complete -- send first message + server + .send_application_data(server_test_data) + .expect("Server failed to send app data"); + server_first_sent = true; + } + Output::ApplicationData(data) => { + server_received_data.extend_from_slice(data); + // After receiving from client, send a reply + if !server_reply_sent && server_received_data.len() >= client_test_data.len() { + server + .send_application_data(server_reply_data) + .expect("Server failed to send reply"); + server_reply_sent = true; + } + } + Output::Timeout(_) => break, + _ => {} + } + } + + // 3) Process client (OpenSSL) events + while let Some(event) = client_events.pop_front() { + match event { + DtlsEvent::Connected => { + client_connected = true; + // Client sends first message on connect + if !client_first_sent { + client + .handle_input(client_test_data) + .expect("Client failed to send app data"); + client_first_sent = true; + } + } + DtlsEvent::Data(data) => { + client_received_data.extend_from_slice(&data); + // After receiving from server, send a reply + if !client_reply_sent && client_received_data.len() >= server_test_data.len() { + client + .handle_input(client_reply_data) + .expect("Client failed to send reply"); + client_reply_sent = true; + } + } + _ => {} + } + } + + // 4) Deliver any further client datagrams produced after app writes + while let Some(datagram) = client.poll_datagram() { + server + .handle_packet(&datagram) + .expect("Server failed to handle client packet"); + } + + // Check if all data has been exchanged in both directions: + // server sent: server_test_data + server_reply_data + // client sent: client_test_data + client_reply_data + let expected_server_len = client_test_data.len() + client_reply_data.len(); + let expected_client_len = server_test_data.len() + server_reply_data.len(); + + if server_connected + && client_connected + && server_received_data.len() >= expected_server_len + && client_received_data.len() >= expected_client_len + { + break; + } + } + + // Verify both sides connected + assert!(server_connected, "Server should be connected"); + assert!(client_connected, "Client should be connected"); + + // Verify bidirectional data exchange: each side sent and received 2 messages + let mut expected_server_recv = Vec::new(); + expected_server_recv.extend_from_slice(client_test_data); + expected_server_recv.extend_from_slice(client_reply_data); + + let mut expected_client_recv = Vec::new(); + expected_client_recv.extend_from_slice(server_test_data); + expected_client_recv.extend_from_slice(server_reply_data); + + assert_eq!( + server_received_data, expected_server_recv, + "Server should receive both client messages" + ); + assert_eq!( + client_received_data, expected_client_recv, + "Client should receive both server messages" + ); +} diff --git a/third_party/dimpl/tests/dtls12/psk.rs b/third_party/dimpl/tests/dtls12/psk.rs new file mode 100644 index 0000000..ad9c11a --- /dev/null +++ b/third_party/dimpl/tests/dtls12/psk.rs @@ -0,0 +1,428 @@ +//! DTLS 1.2 PSK handshake tests. + +use std::sync::Arc; +use std::time::Instant; + +use dimpl::crypto::Dtls12CipherSuite; +use dimpl::{Config, Dtls, Error, PskResolver}; + +use crate::common::{deliver_packets, drain_outputs}; + +/// Simple PSK resolver that returns a fixed key for a known identity. +struct FixedPsk { + identity: Vec, + key: Vec, +} + +impl PskResolver for FixedPsk { + fn resolve(&self, identity: &[u8]) -> Option> { + if identity == self.identity { + Some(self.key.clone()) + } else { + None + } + } +} + +fn psk_provider(suite: Dtls12CipherSuite) -> dimpl::crypto::CryptoProvider { + let mut provider = Config::default().crypto_provider().clone(); + let psk_suite = provider + .cipher_suites + .iter() + .copied() + .find(|cs| cs.suite() == suite) + .unwrap_or_else(|| panic!("{:?} not in provider", suite)); + + let suites = Box::leak(Box::new([psk_suite])); + provider.cipher_suites = suites; + provider +} + +/// Returns (client_config, server_config) for PSK tests. +fn psk_configs_for_suite(suite: Dtls12CipherSuite) -> (Arc, Arc) { + let identity = b"test-device".to_vec(); + let key = b"0123456789abcdef".to_vec(); // 16 bytes + + let resolver = Arc::new(FixedPsk { + identity: identity.clone(), + key, + }); + + let provider = psk_provider(suite); + + let client = Arc::new( + Config::builder() + .with_crypto_provider(provider.clone()) + .with_psk_client(identity, resolver.clone()) + .build() + .expect("build PSK client config"), + ); + + let server = Arc::new( + Config::builder() + .with_crypto_provider(provider) + .with_psk_server(Some(b"hint".to_vec()), resolver) + .build() + .expect("build PSK server config"), + ); + + (client, server) +} + +fn psk_configs() -> (Arc, Arc) { + psk_configs_for_suite(Dtls12CipherSuite::PSK_AES128_CCM_8) +} + +#[test] +fn dtls12_psk_self_handshake() { + let _ = env_logger::try_init(); + + let (client_config, server_config) = psk_configs(); + let now = Instant::now(); + + let mut client = Dtls::new_12_psk(client_config, now); + client.set_active(true); + + let mut server = Dtls::new_12_psk(server_config, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..60 { + client.handle_timeout(Instant::now()).unwrap(); + server.handle_timeout(Instant::now()).unwrap(); + + // Drain client → server + let client_out = drain_outputs(&mut client); + if client_out.connected { + client_connected = true; + } + deliver_packets(&client_out.packets, &mut server); + + // Drain server → client + let server_out = drain_outputs(&mut server); + if server_out.connected { + server_connected = true; + } + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + } + + assert!(client_connected, "PSK client should connect"); + assert!(server_connected, "PSK server should connect"); +} + +#[test] +fn dtls12_psk_application_data_roundtrip() { + let _ = env_logger::try_init(); + + let (client_config, server_config) = psk_configs(); + let now = Instant::now(); + + let mut client = Dtls::new_12_psk(client_config, now); + client.set_active(true); + + let mut server = Dtls::new_12_psk(server_config, now); + server.set_active(false); + + // Complete handshake + for _ in 0..60 { + client.handle_timeout(Instant::now()).unwrap(); + server.handle_timeout(Instant::now()).unwrap(); + + let co = drain_outputs(&mut client); + deliver_packets(&co.packets, &mut server); + + let so = drain_outputs(&mut server); + deliver_packets(&so.packets, &mut client); + + if co.connected || so.connected { + // One more round to let both sides finish + client.handle_timeout(Instant::now()).unwrap(); + server.handle_timeout(Instant::now()).unwrap(); + + let co2 = drain_outputs(&mut client); + deliver_packets(&co2.packets, &mut server); + + let so2 = drain_outputs(&mut server); + deliver_packets(&so2.packets, &mut client); + break; + } + } + + // Send data client → server + let payload = b"Hello from PSK client!"; + client + .send_application_data(payload) + .expect("send app data"); + + let co = drain_outputs(&mut client); + deliver_packets(&co.packets, &mut server); + + let so = drain_outputs(&mut server); + assert!( + so.app_data.iter().any(|d| d == payload), + "Server should receive client's application data" + ); + + // Send data server → client + let reply = b"Hello from PSK server!"; + server.send_application_data(reply).expect("send app data"); + + let so = drain_outputs(&mut server); + deliver_packets(&so.packets, &mut client); + + let co = drain_outputs(&mut client); + assert!( + co.app_data.iter().any(|d| d == reply), + "Client should receive server's application data" + ); +} + +#[test] +fn psk_invalid_identity_fails_at_finished() { + let _ = env_logger::try_init(); + + struct FailingResolver; + impl PskResolver for FailingResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + None + } + } + + struct PassingResolver; + impl PskResolver for PassingResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(vec![0u8; 32]) + } + } + + let server_config = dimpl::Config::builder() + .with_psk_server(None, Arc::new(FailingResolver)) + .build() + .expect("server config should build"); + let mut server = Dtls::new_12_psk(Arc::new(server_config), Instant::now()); + + let client_config = dimpl::Config::builder() + .with_psk_client(b"test_identity".to_vec(), Arc::new(PassingResolver)) + .build() + .expect("client config should build"); + let mut client = Dtls::new_12_psk(Arc::new(client_config), Instant::now()); + client.set_active(true); + + // Drive the handshake; expect a SecurityError from mismatched PSK keys. + let mut error_found = false; + for _ in 0..60 { + if let Err(e) = client.handle_timeout(Instant::now()) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + let co = drain_outputs(&mut client); + for p in &co.packets { + if let Err(e) = server.handle_packet(p) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + } + if error_found { + break; + } + assert!( + !co.connected, + "client should not connect with mismatched PSK" + ); + + if let Err(e) = server.handle_timeout(Instant::now()) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + let so = drain_outputs(&mut server); + for p in &so.packets { + if let Err(e) = client.handle_packet(p) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + } + if error_found { + break; + } + assert!( + !so.connected, + "server should not connect with mismatched PSK" + ); + } + + assert!( + error_found, + "Expected SecurityError from PSK verification failure" + ); +} + +#[test] +fn psk_mismatched_keys_fail_at_finished_via_mac() { + // Both resolvers return Some, so server.psk_valid stays Some(true) and + // the defense-in-depth flag check is bypassed — any failure here must + // come from the Finished MAC mismatch itself. Exercises the primary + // cryptographic guarantee independently of the flag. + let _ = env_logger::try_init(); + + struct ZeroKey; + impl PskResolver for ZeroKey { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(vec![0u8; 32]) + } + } + struct OneKey; + impl PskResolver for OneKey { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(vec![0xAA; 32]) + } + } + + let server_config = dimpl::Config::builder() + .with_psk_server(None, Arc::new(ZeroKey)) + .build() + .expect("server config should build"); + let mut server = Dtls::new_12_psk(Arc::new(server_config), Instant::now()); + + let client_config = dimpl::Config::builder() + .with_psk_client(b"test_identity".to_vec(), Arc::new(OneKey)) + .build() + .expect("client config should build"); + let mut client = Dtls::new_12_psk(Arc::new(client_config), Instant::now()); + client.set_active(true); + + let mut error_found = false; + for _ in 0..60 { + if let Err(e) = client.handle_timeout(Instant::now()) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + let co = drain_outputs(&mut client); + for p in &co.packets { + if let Err(e) = server.handle_packet(p) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + } + if error_found { + break; + } + assert!( + !co.connected, + "client should not connect with mismatched PSK keys" + ); + + if let Err(e) = server.handle_timeout(Instant::now()) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + let so = drain_outputs(&mut server); + for p in &so.packets { + if let Err(e) = client.handle_packet(p) { + assert!( + matches!(e, Error::SecurityError(_) | Error::CryptoError(_)), + "unexpected error: {e:?}" + ); + error_found = true; + break; + } + } + if error_found { + break; + } + assert!( + !so.connected, + "server should not connect with mismatched PSK keys" + ); + } + + assert!( + error_found, + "Expected SecurityError from Finished MAC mismatch" + ); +} + +#[test] +fn psk_valid_identity_succeeds() { + let _ = env_logger::try_init(); + + struct AlwaysPassResolver; + impl PskResolver for AlwaysPassResolver { + fn resolve(&self, _identity: &[u8]) -> Option> { + Some(vec![0u8; 32]) + } + } + + let server_config = dimpl::Config::builder() + .with_psk_server(None, Arc::new(AlwaysPassResolver)) + .build() + .expect("server config should build"); + let mut server = Dtls::new_12_psk(Arc::new(server_config), Instant::now()); + + let client_config = dimpl::Config::builder() + .with_psk_client(b"test_identity".to_vec(), Arc::new(AlwaysPassResolver)) + .build() + .expect("client config should build"); + let mut client = Dtls::new_12_psk(Arc::new(client_config), Instant::now()); + client.set_active(true); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..60 { + client.handle_timeout(Instant::now()).unwrap(); + server.handle_timeout(Instant::now()).unwrap(); + + let co = drain_outputs(&mut client); + if co.connected { + client_connected = true; + } + deliver_packets(&co.packets, &mut server); + + let so = drain_outputs(&mut server); + if so.connected { + server_connected = true; + } + deliver_packets(&so.packets, &mut client); + + if client_connected && server_connected { + break; + } + } + + assert!(client_connected, "PSK client should connect"); + assert!(server_connected, "PSK server should connect"); +} diff --git a/third_party/dimpl/tests/dtls12/reorder.rs b/third_party/dimpl/tests/dtls12/reorder.rs new file mode 100644 index 0000000..5b75a37 --- /dev/null +++ b/third_party/dimpl/tests/dtls12/reorder.rs @@ -0,0 +1,403 @@ +//! DTLS 1.2 packet reordering, replay, and duplicate tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::Dtls; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handles_duplicate_packets() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + // Deliver originals first + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + // Drain any events triggered by the original delivery before + // injecting duplicates, so the state machine has advanced past + // the flight boundary. + let server_mid = drain_outputs(&mut server); + let client_mid = drain_outputs(&mut client); + server_connected |= server_mid.connected; + client_connected |= client_mid.connected; + + // Now deliver duplicates -- these should be tolerated + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(20); + } + + assert!( + client_connected, + "Client should connect despite duplicate packets" + ); + assert!( + server_connected, + "Server should connect despite duplicate packets" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handles_out_of_order_packets() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Deliver packets in reverse order + let mut client_packets = client_out.packets.clone(); + let mut server_packets = server_out.packets.clone(); + client_packets.reverse(); + server_packets.reverse(); + + deliver_packets(&client_packets, &mut server); + deliver_packets(&server_packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect with out-of-order packets" + ); + assert!( + server_connected, + "Server should connect with out-of-order packets" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_replay_window_rejects_old_app_data() { + //! After handshake, send 100 app data messages from client to server. + //! Then replay the very first encrypted packet. The replayed packet + //! should be silently dropped (not delivered as application data again). + + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Send the first message and capture its encrypted packet + client + .send_application_data(b"message 1") + .expect("send message 1"); + let first_out = drain_outputs(&mut client); + assert!( + !first_out.packets.is_empty(), + "Should have packets for message 1" + ); + let early_packet = first_out.packets[0].clone(); + + // Deliver and verify it arrives + deliver_packets(&first_out.packets, &mut server); + let server_out = drain_outputs(&mut server); + assert_eq!( + server_out.app_data.len(), + 1, + "Server should receive message 1" + ); + + // Send 99 more messages to advance the replay window well past the first + for i in 2..=100 { + let msg = format!("message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send message"); + + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + let server_out = drain_outputs(&mut server); + assert!( + !server_out.app_data.is_empty(), + "Server should receive message {}", + i + ); + } + + // Now replay the very first encrypted packet + let _ = server.handle_packet(&early_packet); + let replay_out = drain_outputs(&mut server); + + assert!( + replay_out.app_data.is_empty(), + "Replayed old packet should NOT produce application data (replay protection)" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_replay_window_rejects_duplicate_app_data() { + //! After handshake, send one app data message. Deliver it, then deliver + //! the exact same encrypted packet again. Only one copy should be received. + + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Send a single app data message + client + .send_application_data(b"only once") + .expect("send app data"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "Should have packets for app data" + ); + + // Save the encrypted packet for replay + let encrypted_packet = client_out.packets[0].clone(); + + // First delivery -- should produce app data + let _ = server.handle_packet(&encrypted_packet); + let first_out = drain_outputs(&mut server); + assert_eq!( + first_out.app_data.len(), + 1, + "First delivery should produce exactly one app data" + ); + assert_eq!(first_out.app_data[0], b"only once"); + + // Second delivery of exact same packet -- should be silently dropped + let _ = server.handle_packet(&encrypted_packet); + let dup_out = drain_outputs(&mut server); + assert!( + dup_out.app_data.is_empty(), + "Duplicate packet should NOT produce application data (replay protection)" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handles_delayed_burst_delivery() { + //! During handshake, hold all packets for 3 rounds of timeouts, then + //! deliver them all at once in a burst. Verify handshake still completes. + + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Hold packets for delayed delivery + let mut held_server_packets: Vec> = Vec::new(); + let mut held_client_packets: Vec> = Vec::new(); + let mut hold_rounds = 0; + const HOLD_DURATION: usize = 3; // Hold packets for 3 rounds before delivering + + for _round in 0..200 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Collect packets + held_server_packets.extend(server_out.packets.iter().cloned()); + held_client_packets.extend(client_out.packets.iter().cloned()); + + hold_rounds += 1; + + // Deliver burst every HOLD_DURATION rounds + if hold_rounds >= HOLD_DURATION { + // Deliver all held packets at once + for p in &held_client_packets { + let _ = server.handle_packet(p); + } + for p in &held_server_packets { + let _ = client.handle_packet(p); + } + + held_server_packets.clear(); + held_client_packets.clear(); + hold_rounds = 0; + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + // Deliver any remaining packets + for p in &held_client_packets { + let _ = server.handle_packet(p); + } + for p in &held_server_packets { + let _ = client.handle_packet(p); + } + break; + } + + now += Duration::from_millis(20); + } + + assert!( + client_connected, + "Client should connect despite delayed delivery" + ); + assert!( + server_connected, + "Server should connect despite delayed delivery" + ); +} diff --git a/third_party/dimpl/tests/dtls12/retransmit.rs b/third_party/dimpl/tests/dtls12/retransmit.rs new file mode 100644 index 0000000..b1c9dde --- /dev/null +++ b/third_party/dimpl/tests/dtls12/retransmit.rs @@ -0,0 +1,1272 @@ +//! DTLS 1.2 retransmission and duplicate handling tests. + +#![allow(unused)] + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Output}; + +use crate::common::*; + +#[cfg(feature = "rcgen")] +struct FinalFlightResend { + client: Dtls, + server: Dtls, + f6_init: Vec>, + f6_resend: Vec>, + stale_epoch0_handshake: Vec, +} + +#[cfg(feature = "rcgen")] +fn prepare_server_final_flight_resend(max_queue_rx: usize) -> FinalFlightResend { + use dimpl::certificate::generate_self_signed_certificate; + + let mut now = Instant::now(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config_client = Arc::new( + Config::builder() + .mtu(115) + .max_queue_rx(max_queue_rx) + .build() + .expect("Failed to build config"), + ); + let config_server = Arc::new( + Config::builder() + .mtu(115) + .max_queue_rx(max_queue_rx) + .build() + .expect("Failed to build config"), + ); + + let mut client = Dtls::new_12(config_client, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config_server, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let f1 = collect_packets(&mut client); + for packet in f1 { + server.handle_packet(&packet).expect("server recv f1"); + } + + server.handle_timeout(now).expect("server arm flight 2"); + let f2 = collect_packets(&mut server); + assert!(!f2.is_empty(), "server should emit flight 2 after CH"); + for packet in f2 { + client.handle_packet(&packet).expect("client recv f2"); + } + + client.handle_timeout(now).expect("client arm flight 3"); + let f3 = collect_packets(&mut client); + assert!(!f3.is_empty(), "client should emit flight 3 after HVR"); + let stale_epoch0_handshake = first_record_matching(&f3, 22, 0) + .expect("flight 3 should contain a plaintext ClientHello record"); + for packet in f3 { + server.handle_packet(&packet).expect("server recv f3"); + } + + server.handle_timeout(now).expect("server arm flight 4"); + let f4 = collect_packets(&mut server); + assert!( + !f4.is_empty(), + "server should emit flight 4 after CH+cookie" + ); + for packet in f4 { + client.handle_packet(&packet).expect("client recv f4"); + } + + client.handle_timeout(now).expect("client arm flight 5"); + let f5_init = collect_packets(&mut client); + assert!( + !f5_init.is_empty(), + "client should emit flight 5 after server flight" + ); + for packet in &f5_init { + server.handle_packet(packet).expect("server recv f5"); + } + + server.handle_timeout(now).expect("server arm flight 6"); + let f6_init = collect_packets(&mut server); + assert!(!f6_init.is_empty(), "server should emit initial flight 6"); + let f6_init_hdrs = collect_headers(&f6_init); + assert!( + f6_init_hdrs.iter().any(|h| h.ctype == 20 && h.epoch == 0), + "server flight 6 should include epoch 0 CCS" + ); + assert!( + f6_init_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), + "server flight 6 should include epoch 1 Finished" + ); + + trigger_timeout(&mut client, &mut now); + let f5_resend = collect_packets(&mut client); + assert!(!f5_resend.is_empty(), "client should resend flight 5"); + for packet in &f5_resend { + server.handle_packet(packet).expect("server recv f5 resend"); + } + + let f6_resend = collect_packets(&mut server); + assert!( + !f6_resend.is_empty(), + "server should resend flight 6 upon receiving duplicate Finished" + ); + let f6_resend_hdrs = collect_headers(&f6_resend); + assert!( + f6_resend_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), + "resend flight 6 should include epoch 1 Finished" + ); + assert_epochs_and_seq_increased(&f6_init_hdrs, &f6_resend_hdrs); + + FinalFlightResend { + client, + server, + f6_init, + f6_resend, + stale_epoch0_handshake, + } +} + +#[cfg(feature = "rcgen")] +fn first_record_matching(datagrams: &[Vec], content_type: u8, epoch: u16) -> Option> { + for datagram in datagrams { + let mut offset = 0usize; + while offset + 13 <= datagram.len() { + let len = u16::from_be_bytes([datagram[offset + 11], datagram[offset + 12]]) as usize; + let end = offset + 13 + len; + if end > datagram.len() { + break; + } + + let record_epoch = u16::from_be_bytes([datagram[offset + 3], datagram[offset + 4]]); + if datagram[offset] == content_type && record_epoch == epoch { + return Some(datagram[offset..end].to_vec()); + } + + offset = end; + } + } + + None +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_client_hello_retransmits_using_advertised_deadlines() { + use dimpl::certificate::generate_self_signed_certificate; + + let now = Instant::now(); + let certificate = generate_self_signed_certificate().expect("generate client certificate"); + let mut client = Dtls::new_12(Arc::new(Config::default()), certificate, now); + client.set_active(true); + + client.handle_timeout(now).expect("start client handshake"); + let initial_output = drain_outputs(&mut client); + assert!( + !initial_output.packets.is_empty(), + "client should emit ClientHello" + ); + + // Drop the initial flight and handle the timeout. + let arm_at = initial_output + .timeout + .expect("client should advertise a deadline"); + client + .handle_timeout(arm_at) + .expect("arm ClientHello retransmission"); + let after_timer_arming = drain_outputs(&mut client); + assert!( + after_timer_arming.packets.is_empty(), + "arming should not retransmit early" + ); + + let retransmit_at = after_timer_arming + .timeout + .expect("client should advertise a retransmission deadline"); + client + .handle_timeout(retransmit_at) + .expect("retransmit ClientHello"); + let retransmission_output = drain_outputs(&mut client); + + assert!( + !retransmission_output.packets.is_empty(), + "the dropped ClientHello flight was not retransmitted" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_resends_each_flight_epoch_and_sequence_increase() { + let now0 = Instant::now(); + let mut now = now0; + + use dimpl::certificate::generate_self_signed_certificate; + + // Certificates for client and server + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config_client = Arc::new(Config::default()); + let config_server = Arc::new(Config::default()); + + // Client + let mut client = Dtls::new_12(config_client, client_cert.clone(), now); + client.set_active(true); + + // Server + let mut server = Dtls::new_12(config_server, server_cert.clone(), now); + server.set_active(false); + + // FLIGHT 1 (ClientHello): block initial, deliver resend + client.handle_timeout(now).expect("client timeout start"); + // flight_begin reset the flight timer; arm it again so poll_output yields packets + client.handle_timeout(now).expect("client arm flight 1"); + let init1_pkts = collect_packets(&mut client); + let init1_hdrs = collect_headers(&init1_pkts); + trigger_timeout(&mut client, &mut now); + let resend1_pkts = collect_packets(&mut client); + let resend1_hdrs = collect_headers(&resend1_pkts); + assert_epochs_and_seq_increased(&init1_hdrs, &resend1_hdrs); + for p in resend1_pkts { + server.handle_packet(&p).expect("server recv f1"); + } + + // FLIGHT 2 (HelloVerifyRequest): capture initial from server, block, deliver resend + server.handle_timeout(now).expect("server arm flight 2"); + let init2_pkts = collect_packets(&mut server); + assert!( + !init2_pkts.is_empty(), + "server should emit flight 2 after CH" + ); + let init2_hdrs = collect_headers(&init2_pkts); + trigger_timeout(&mut server, &mut now); + let resend2_pkts = collect_packets(&mut server); + let resend2_hdrs = collect_headers(&resend2_pkts); + assert_epochs_and_seq_increased(&init2_hdrs, &resend2_hdrs); + for p in resend2_pkts { + client.handle_packet(&p).expect("client recv f2"); + } + + // FLIGHT 3 (ClientHello with cookie): block initial, deliver resend + client.handle_timeout(now).expect("client arm flight 3"); + let init3_pkts = collect_packets(&mut client); + assert!( + !init3_pkts.is_empty(), + "client should emit flight 3 after HVR" + ); + let init3_hdrs = collect_headers(&init3_pkts); + trigger_timeout(&mut client, &mut now); + let resend3_pkts = collect_packets(&mut client); + let resend3_hdrs = collect_headers(&resend3_pkts); + assert_epochs_and_seq_increased(&init3_hdrs, &resend3_hdrs); + for p in resend3_pkts { + server.handle_packet(&p).expect("server recv f3"); + } + + // FLIGHT 4 (ServerHello, Certificate, SKE, CR, SHD): block initial, deliver resend + server.handle_timeout(now).expect("server arm flight 4"); + let init4_pkts = collect_packets(&mut server); + assert!( + !init4_pkts.is_empty(), + "server should emit flight 4 after CH+cookie" + ); + let init4_hdrs = collect_headers(&init4_pkts); + trigger_timeout(&mut server, &mut now); + let resend4_pkts = collect_packets(&mut server); + let resend4_hdrs = collect_headers(&resend4_pkts); + assert_epochs_and_seq_increased(&init4_hdrs, &resend4_hdrs); + for p in resend4_pkts { + client.handle_packet(&p).expect("client recv f4"); + } + + // FLIGHT 5 (Client cert?, CKX, CV?, CCS, Finished): block initial, deliver resend + client.handle_timeout(now).expect("client arm flight 5"); + let init5_pkts = collect_packets(&mut client); + assert!( + !init5_pkts.is_empty(), + "client should emit flight 5 after server flight" + ); + let init5_hdrs = collect_headers(&init5_pkts); + trigger_timeout(&mut client, &mut now); + let resend5_pkts = collect_packets(&mut client); + let resend5_hdrs = collect_headers(&resend5_pkts); + assert_epochs_and_seq_increased(&init5_hdrs, &resend5_hdrs); + // Additionally, ensure Finished is epoch 1 is present in the set + assert!( + resend5_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), + "client flight 5 should include epoch 1 Finished" + ); + for p in resend5_pkts { + server.handle_packet(&p).expect("server recv f5"); + } + + // FLIGHT 6 (Server CCS, Finished): no resend timer after final flight + server.handle_timeout(now).expect("server arm flight 6"); + let init6_pkts = collect_packets(&mut server); + assert!( + !init6_pkts.is_empty(), + "server should emit flight 6 after client flight 5" + ); + let init6_hdrs = collect_headers(&init6_pkts); + // Final flight should include epoch 1 Finished in the initial transmission + assert!( + init6_hdrs.iter().any(|h| h.ctype == 22 && h.epoch == 1), + "server flight 6 should include epoch 1 Finished" + ); + // Ensure no timer-driven resend occurs after final flight + trigger_timeout(&mut server, &mut now); + let resend6_pkts = collect_packets(&mut server); + assert!(resend6_pkts.is_empty(), "no resend after final flight"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_duplicate_triggers_server_resend_of_final_flight() { + let result = prepare_server_final_flight_resend(Config::default().max_queue_rx()); + assert!( + !result.f6_init.is_empty(), + "server should emit initial flight 6" + ); + assert!( + !result.f6_resend.is_empty(), + "server should resend flight 6 upon receiving duplicate Finished" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_resend_replaces_pending_handshake_flight_tail() { + let now0 = Instant::now(); + let mut now = now0; + + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config_client = Arc::new( + Config::builder() + .mtu(115) + .build() + .expect("Failed to build config"), + ); + let config_server = Arc::new( + Config::builder() + .mtu(115) + .build() + .expect("Failed to build config"), + ); + + let expected_initial_headers = { + let mut client = Dtls::new_12(Arc::clone(&config_client), client_cert.clone(), now0); + client.set_active(true); + + let mut server = Dtls::new_12(Arc::clone(&config_server), server_cert.clone(), now0); + server.set_active(false); + + client.handle_timeout(now0).expect("client timeout start"); + client.handle_timeout(now0).expect("client arm flight 1"); + for p in collect_packets(&mut client) { + server.handle_packet(&p).expect("control server recv f1"); + } + + server + .handle_timeout(now0) + .expect("control server arm flight 2"); + for p in collect_packets(&mut server) { + client.handle_packet(&p).expect("control client recv f2"); + } + + client + .handle_timeout(now0) + .expect("control client arm flight 3"); + for p in collect_packets(&mut client) { + server.handle_packet(&p).expect("control server recv f3"); + } + + server + .handle_timeout(now0) + .expect("control server arm flight 4"); + collect_headers(&collect_packets(&mut server)) + }; + assert!( + !expected_initial_headers.is_empty(), + "control flight 4 should contain records" + ); + + let mut client = Dtls::new_12(config_client, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config_server, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let f1 = collect_packets(&mut client); + for p in f1 { + server.handle_packet(&p).expect("server recv f1"); + } + + server.handle_timeout(now).expect("server arm flight 2"); + let f2 = collect_packets(&mut server); + for p in f2 { + client.handle_packet(&p).expect("client recv f2"); + } + + client.handle_timeout(now).expect("client arm flight 3"); + let f3 = collect_packets(&mut client); + for p in f3 { + server.handle_packet(&p).expect("server recv f3"); + } + + server.handle_timeout(now).expect("server arm flight 4"); + let first_initial = poll_one_packet(&mut server); + let first_initial_headers = parse_records(&first_initial); + assert!( + !first_initial_headers.is_empty(), + "first initial flight 4 packet should contain records" + ); + + trigger_timeout(&mut server, &mut now); + let pending = collect_packets(&mut server); + assert!( + !pending.is_empty(), + "server should emit flight 4 resend after timeout" + ); + let pending_headers = collect_headers(&pending); + assert_eq!( + pending_headers.len(), + expected_initial_headers.len(), + "resend should replace the undrained original flight tail instead of appending to it; \ + expected initial {expected_initial_headers:?}, pending {pending_headers:?}" + ); + assert!( + pending_headers + .iter() + .zip(expected_initial_headers.iter()) + .all(|(resend, initial)| resend.ctype == initial.ctype + && resend.epoch == initial.epoch + && resend.seq > initial.seq), + "resend should contain only a fresh copy of the flight, got expected initial \ + {expected_initial_headers:?}, first polled {first_initial_headers:?}, pending \ + {pending_headers:?}" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_final_flight_resend_can_share_post_release_appdata_tail() { + let FinalFlightResend { + mut server, + stale_epoch0_handshake, + .. + } = prepare_server_final_flight_resend(Config::default().max_queue_rx()); + + let filler = vec![0x55; 50]; + for i in 0..9 { + server + .send_application_data(&filler) + .unwrap_or_else(|err| panic!("queue filler app data {i}: {err:?}")); + } + server + .send_application_data(b"x") + .expect("queue final small app data"); + + server + .handle_packet(&stale_epoch0_handshake) + .expect("post-release duplicate should trigger final-flight resend"); + + let pending_headers = collect_headers(&collect_packets(&mut server)); + let app_data_records = pending_headers + .iter() + .filter(|header| header.ctype == 23 && header.epoch == 1) + .count(); + assert_eq!( + app_data_records, 10, + "post-release final-flight resend must preserve queued app-data records, got \ + {pending_headers:?}" + ); + assert!( + pending_headers + .iter() + .any(|header| header.ctype == 22 && header.epoch == 1), + "server should retain and resend encrypted final-flight Finished, got \ + {pending_headers:?}" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_late_retransmitted_ccs_does_not_pin_receive_queue() { + //! After the handshake, a peer can still retransmit its final flight. The + //! epoch-0 ChangeCipherSpec in that flight must be ignored; otherwise it + //! remains unhandled and prevents handled app-data records behind it from + //! being purged. + + const RX_QUEUE_LIMIT: usize = 8; + + let FinalFlightResend { + mut client, + mut server, + f6_init, + f6_resend, + stale_epoch0_handshake: _, + } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); + + deliver_packets(&f6_init, &mut client); + let client_connected = drain_outputs(&mut client).connected; + assert!( + client_connected, + "client should connect after initial flight 6" + ); + + for packet in &f6_resend { + client + .handle_packet(packet) + .expect("late final-flight resend should be tolerated"); + } + + for i in 0..=RX_QUEUE_LIMIT { + let msg = format!("post-ccs app data {i}"); + server + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "server should emit app-data packets" + ); + + for packet in &server_out.packets { + client + .handle_packet(packet) + .expect("late CCS must not make receive queue fill"); + } + + let client_out = drain_outputs(&mut client); + assert!( + client_out + .app_data + .iter() + .any(|received| received == msg.as_bytes()), + "client should receive app data after late CCS" + ); + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_late_epoch0_handshake_does_not_pin_receive_queue() { + //! After peer encryption is enabled, plaintext epoch-0 handshake records are + //! unauthenticated and no longer actionable. They must be ignored for the + //! same queue-pinning reason as late CCS records. + + const RX_QUEUE_LIMIT: usize = 8; + + let FinalFlightResend { + mut client, + mut server, + f6_init, + f6_resend: _, + stale_epoch0_handshake: _, + } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); + + deliver_packets(&f6_init, &mut client); + let client_connected = drain_outputs(&mut client).connected; + assert!( + client_connected, + "client should connect after initial flight 6" + ); + + client + .handle_packet(&malformed_epoch0_handshake_packet(0x7fff)) + .expect("late epoch-0 handshake should be tolerated"); + + for i in 0..=RX_QUEUE_LIMIT { + let msg = format!("post-handshake app data {i}"); + server + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "server should emit app-data packets" + ); + + for packet in &server_out.packets { + client + .handle_packet(packet) + .expect("late epoch-0 handshake must not make receive queue fill"); + } + + let client_out = drain_outputs(&mut client); + assert!( + client_out + .app_data + .iter() + .any(|received| received == msg.as_bytes()), + "client should receive app data after late epoch-0 handshake" + ); + } +} + +fn malformed_epoch0_handshake_packet(sequence_number: u64) -> Vec { + let sequence_bytes = sequence_number.to_be_bytes(); + let mut packet = Vec::with_capacity(14); + packet.push(22); + packet.extend_from_slice(&[0xfe, 0xfd]); + packet.extend_from_slice(&0u16.to_be_bytes()); + packet.extend_from_slice(&sequence_bytes[2..]); + packet.extend_from_slice(&1u16.to_be_bytes()); + packet.push(0xff); + packet +} + +fn append_record(mut packet: Vec, record: &[u8]) -> Vec { + packet.extend_from_slice(record); + packet +} + +#[cfg(feature = "rcgen")] +fn poll_one_packet(endpoint: &mut Dtls) -> Vec { + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(packet) => return packet.to_vec(), + Output::Timeout(_) => panic!("expected queued packet"), + _ => {} + } + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_late_epoch0_handshake_trailing_app_data_does_not_pin_receive_queue() { + //! A stale epoch-0 handshake can arrive behind a valid encrypted record in + //! the same datagram. The encrypted app data should still be delivered, and + //! the stale plaintext handshake must not keep that datagram in the queue. + + const RX_QUEUE_LIMIT: usize = 8; + + let FinalFlightResend { + mut client, + mut server, + f6_init, + f6_resend: _, + stale_epoch0_handshake, + } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); + + deliver_packets(&f6_init, &mut client); + let client_connected = drain_outputs(&mut client).connected; + assert!( + client_connected, + "client should connect after initial flight 6" + ); + + for i in 0..=RX_QUEUE_LIMIT { + let msg = format!("post-handshake app data {i}"); + server + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "server should emit app-data packets" + ); + + for packet in server_out.packets { + let packet = if i == 0 { + append_record(packet, &stale_epoch0_handshake) + } else { + packet + }; + client + .handle_packet(&packet) + .expect("trailing late epoch-0 handshake must not make receive queue fill"); + } + + let client_out = drain_outputs(&mut client); + assert!( + client_out + .app_data + .iter() + .any(|received| received == msg.as_bytes()), + "client should receive app data after trailing late epoch-0 handshake" + ); + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_completes_after_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls12_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut drop_next_client_packet = true; // Drop first ClientHello + + for i in 0..60 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Simulate packet loss: drop first client packet batch + if !client_out.packets.is_empty() && drop_next_client_packet { + drop_next_client_packet = false; + // Don't deliver client packets this round + } else { + deliver_packets(&client_out.packets, &mut server); + } + + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + // Advance time to trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite initial packet loss" + ); + assert!( + server_connected, + "Server should connect despite initial packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_completes_with_early_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use a config with more retries to handle packet loss + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + // Drop first 2 client packets and first 2 server packets to test retransmission + let mut client_packets_to_drop = 2; + let mut server_packets_to_drop = 2; + + for i in 0..60 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Deliver client packets, dropping first N + for packet in &client_out.packets { + if client_packets_to_drop > 0 { + client_packets_to_drop -= 1; + } else { + let _ = server.handle_packet(packet); + } + } + + // Deliver server packets, dropping first N + for packet in &server_out.packets { + if server_packets_to_drop > 0 { + server_packets_to_drop -= 1; + } else { + let _ = client.handle_packet(packet); + } + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite early packet loss" + ); + assert!( + server_connected, + "Server should connect despite early packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_survives_random_packet_loss_pattern() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_12(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_12(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut total_dropped = 0; + let mut total_delivered = 0; + + // Deterministic pattern: drop every 3rd packet across both directions + let mut global_packet_index = 0usize; + + for i in 0..100 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + for packet in &client_out.packets { + if global_packet_index % 3 == 2 { + total_dropped += 1; + } else { + let _ = server.handle_packet(packet); + total_delivered += 1; + } + global_packet_index += 1; + } + + for packet in &server_out.packets { + if global_packet_index % 3 == 2 { + total_dropped += 1; + } else { + let _ = client.handle_packet(packet); + total_delivered += 1; + } + global_packet_index += 1; + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite every-3rd-packet loss" + ); + assert!( + server_connected, + "Server should connect despite every-3rd-packet loss" + ); + assert!( + total_dropped > 0, + "Test should have dropped at least one packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_retransmit_exponential_backoff() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + + // Use a known start RTO and enough retries to observe backoff + let config = Arc::new( + Config::builder() + .flight_start_rto(Duration::from_secs(1)) + .flight_retries(4) + .handshake_timeout(Duration::from_secs(120)) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + let mut client = Dtls::new_12(config, client_cert, now); + client.set_active(true); + + // No server -- we never deliver packets. + // Start the handshake. + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let _ = collect_packets(&mut client); + + // Record successive timeout values returned by poll_output. + // Each handle_timeout that fires the flight timer should produce a new, + // larger timeout. + let mut timeouts: Vec = Vec::new(); + + // Collect the first timeout + let mut buf = vec![0u8; 2048]; + loop { + if let Output::Timeout(t) = client.poll_output(&mut buf) { + timeouts.push(t); + break; + } + } + + // Fire successive timeouts, never delivering packets + for _ in 0..3 { + // Advance past the reported timeout + now = *timeouts.last().expect("should have a timeout") + Duration::from_millis(1); + client.handle_timeout(now).expect("client handle_timeout"); + let _ = collect_packets(&mut client); + + // Collect the next timeout + loop { + if let Output::Timeout(t) = client.poll_output(&mut buf) { + timeouts.push(t); + break; + } + } + } + + // Verify we collected multiple timeout values + assert!( + timeouts.len() >= 4, + "Should have at least 4 timeout values, got {}", + timeouts.len() + ); + + // Verify each successive interval is strictly larger (exponential backoff). + // Interval[i] = timeout[i+1] - timeout[i] should be increasing. + let mut intervals: Vec = Vec::new(); + for pair in timeouts.windows(2) { + let interval = pair[1].duration_since(pair[0]); + intervals.push(interval); + } + + for pair in intervals.windows(2) { + assert!( + pair[1] > pair[0], + "Backoff intervals should increase: {:?} should be > {:?}", + pair[1], + pair[0] + ); + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_handshake_timeout_aborts() { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + + // Configure a very short handshake timeout so we hit it quickly + let config = Arc::new( + Config::builder() + .handshake_timeout(Duration::from_secs(5)) + .flight_start_rto(Duration::from_secs(1)) + .flight_retries(10) // Many retries, but the handshake timeout will fire first + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + let mut client = Dtls::new_12(config, client_cert, now); + client.set_active(true); + + // Start the handshake + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let _ = collect_packets(&mut client); + + // Keep triggering timeouts without ever delivering packets. + // The handshake_timeout (5s) should eventually cause handle_timeout to return an error. + let mut got_timeout_error = false; + for _ in 0..100 { + now += Duration::from_secs(1); + match client.handle_timeout(now) { + Ok(()) => { + // Drain any packets to keep the state machine consistent + let _ = collect_packets(&mut client); + } + Err(e) => { + let msg = format!("{}", e); + assert!( + msg.contains("timeout"), + "Expected timeout error, got: {}", + msg + ); + got_timeout_error = true; + break; + } + } + } + + assert!( + got_timeout_error, + "Client should report a timeout error when handshake_timeout is exceeded" + ); +} + +/// Before the peer is confirmed (the legitimate retransmission window), a stale +/// plaintext ClientHello still triggers a flight-6 resend, so a lost flight 6 +/// recovers. This is the contrast case to the post-confirmation suppression +/// below: the gate must not break legitimate retransmission. +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_stale_client_hello_before_peer_confirmed_triggers_resend() { + let _ = env_logger::try_init(); + + const RX_QUEUE_LIMIT: usize = 8; + let FinalFlightResend { + mut server, + stale_epoch0_handshake, + .. + } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); + + // The server has sent flight 6 but has no confirmation the client received + // it (no authenticated application data has arrived). A stale ClientHello + // here means "peer still needs my flight" and must drive a resend. + server + .handle_packet(&stale_epoch0_handshake) + .expect("stale ClientHello must be tolerated"); + let resend = collect_packets(&mut server); + + assert!( + !resend.is_empty(), + "server must resend flight 6 on a stale ClientHello while the peer is unconfirmed" + ); +} + +/// Once the peer is confirmed to have completed the handshake (the server has +/// received authenticated application data from the client), a replayed +/// plaintext ClientHello is unauthenticated noise and must not trigger a flight +/// retransmission. This closes the resend-amplification window that an attacker +/// could otherwise drive with spoofed epoch-0 handshakes. +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_stale_client_hello_after_peer_confirmed_triggers_no_resend() { + let _ = env_logger::try_init(); + + const RX_QUEUE_LIMIT: usize = 8; + let FinalFlightResend { + mut client, + mut server, + f6_resend, + stale_epoch0_handshake, + .. + } = prepare_server_final_flight_resend(RX_QUEUE_LIMIT); + + // Finish the handshake: deliver the server's resent flight 6 to the client. + deliver_packets(&f6_resend, &mut client); + assert!( + drain_outputs(&mut client).connected, + "client should connect once it receives flight 6" + ); + + // Client application data is the server's signal that the client completed + // (it could only send it after receiving flight 6). + client + .send_application_data(b"client-app-data") + .expect("client sends application data"); + let client_app = collect_packets(&mut client); + assert!(!client_app.is_empty(), "client should emit app-data packet"); + deliver_packets(&client_app, &mut server); + let server_out = drain_outputs(&mut server); + assert_eq!( + server_out.app_data, + vec![b"client-app-data".to_vec()], + "server should receive the client's application data" + ); + + // Replay the stale plaintext ClientHello at the now-confirmed server. + server + .handle_packet(&stale_epoch0_handshake) + .expect("stale ClientHello must be tolerated"); + let resend = collect_packets(&mut server); + + assert!( + resend.is_empty(), + "server must not resend its flight after the client is confirmed connected" + ); +} + +#[cfg(feature = "rcgen")] +fn forged_epoch1_app_data() -> Vec { + // A DTLS 1.2 record header advertising epoch-1 ApplicationData with a + // garbage (undecryptable) body. The content type lives in the cleartext + // header, so this looks like app data before anything is decrypted. + let mut rec = Vec::new(); + rec.push(23); // ContentType::ApplicationData + rec.extend_from_slice(&[0xFE, 0xFD]); // DTLS 1.2 + rec.extend_from_slice(&1u16.to_be_bytes()); // epoch 1 + rec.extend_from_slice(&[0, 0, 0, 0, 0, 1]); // 48-bit sequence number + rec.extend_from_slice(&2u16.to_be_bytes()); // fragment length + rec.extend_from_slice(&[0xAA, 0xBB]); // garbage fragment + rec +} + +/// A forged epoch-1 application-data record arriving before peer encryption is +/// enabled must not confirm the peer handshake. The record advertises +/// ApplicationData in its cleartext header and is queued undecrypted, so without +/// the authentication guard it would falsely mark the peer confirmed and suppress +/// the flight-6 resend that a genuinely lost flight needs. +#[test] +#[cfg(feature = "rcgen")] +fn dtls12_forged_epoch1_appdata_before_encryption_does_not_confirm_peer() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let mut now = Instant::now(); + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config_client = Arc::new(Config::builder().mtu(115).build().expect("config")); + let config_server = Arc::new(Config::builder().mtu(115).build().expect("config")); + + let mut client = Dtls::new_12(config_client, client_cert, now); + client.set_active(true); + let mut server = Dtls::new_12(config_server, server_cert, now); + server.set_active(false); + + // Flight 1: ClientHello. + client.handle_timeout(now).expect("client timeout start"); + client.handle_timeout(now).expect("client arm flight 1"); + let f1 = collect_packets(&mut client); + for packet in &f1 { + server.handle_packet(packet).expect("server recv f1"); + } + + // Flight 2: HelloVerifyRequest. + server.handle_timeout(now).expect("server arm flight 2"); + let f2 = collect_packets(&mut server); + assert!(!f2.is_empty(), "server should emit flight 2"); + for packet in &f2 { + client.handle_packet(packet).expect("client recv f2"); + } + + // Flight 3: ClientHello with cookie. + client.handle_timeout(now).expect("client arm flight 3"); + let f3 = collect_packets(&mut client); + assert!(!f3.is_empty(), "client should emit flight 3"); + for packet in &f3 { + server.handle_packet(packet).expect("server recv f3"); + } + + // Flight 4: server hello flight. + server.handle_timeout(now).expect("server arm flight 4"); + let f4 = collect_packets(&mut server); + assert!(!f4.is_empty(), "server should emit flight 4"); + for packet in &f4 { + client.handle_packet(packet).expect("client recv f4"); + } + + // Inject the forged epoch-1 app-data record while the server still has peer + // encryption disabled (it has not seen the client CCS yet). + let _ = server.handle_packet(&forged_epoch1_app_data()); + let _ = drain_outputs(&mut server); + + // Flight 5: CKE, CCS, Finished. Server completes and emits flight 6. + client.handle_timeout(now).expect("client arm flight 5"); + let f5 = collect_packets(&mut client); + assert!(!f5.is_empty(), "client should emit flight 5"); + for packet in &f5 { + server.handle_packet(packet).expect("server recv f5"); + } + server.handle_timeout(now).expect("server arm flight 6"); + let f6_init = collect_packets(&mut server); + assert!(!f6_init.is_empty(), "server should emit flight 6"); + + // Drop flight 6. The client retransmits flight 5 on timeout. + trigger_timeout(&mut client, &mut now); + let f5_resend = collect_packets(&mut client); + assert!(!f5_resend.is_empty(), "client should resend flight 5"); + for packet in &f5_resend { + server.handle_packet(packet).expect("server recv f5 resend"); + } + + // The forged record must not have confirmed the peer, so the duplicate + // flight 5 still drives a flight-6 resend. + let f6_resend = collect_packets(&mut server); + assert!( + !f6_resend.is_empty(), + "forged pre-encryption app data must not confirm the peer; flight 6 must still resend" + ); +} diff --git a/third_party/dimpl/tests/dtls13/common.rs b/third_party/dimpl/tests/dtls13/common.rs new file mode 100644 index 0000000..c452df0 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/common.rs @@ -0,0 +1,146 @@ +//! Shared helpers for DTLS 1.3 integration tests. + +#![allow(unused)] + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Output, SrtpProfile}; + +/// Collected outputs from polling an endpoint to `Timeout`. +#[derive(Default, Debug)] +pub struct DrainedOutputs { + pub packets: Vec>, + pub connected: bool, + pub peer_cert: Option>, + pub keying_material: Option<(Vec, SrtpProfile)>, + pub app_data: Vec>, + pub timeout: Option, + pub close_notify: bool, +} + +/// Poll until `Timeout`, collecting only packets. +pub fn collect_packets(endpoint: &mut Dtls) -> Vec> { + let mut out = Vec::new(); + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => out.push(p.to_vec()), + Output::Timeout(_) => break, + _ => {} + } + } + out +} + +/// Poll until `Timeout`, collecting everything. +pub fn drain_outputs(endpoint: &mut Dtls) -> DrainedOutputs { + let mut result = DrainedOutputs::default(); + let mut buf = vec![0u8; 2048]; + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => result.packets.push(p.to_vec()), + Output::Connected => result.connected = true, + Output::PeerCert(cert) => result.peer_cert = Some(cert.to_vec()), + Output::KeyingMaterial(km, profile) => { + result.keying_material = Some((km.to_vec(), profile)); + } + Output::ApplicationData(data) => result.app_data.push(data.to_vec()), + Output::CloseNotify => result.close_notify = true, + Output::Timeout(t) => { + result.timeout = Some(t); + break; + } + _ => {} + } + } + result +} + +/// Deliver a slice of packets to a destination endpoint. +pub fn deliver_packets(packets: &[Vec], dest: &mut Dtls) { + for p in packets { + // Ignore errors - they may be expected for duplicates/replays + let _ = dest.handle_packet(p); + } +} + +/// Trigger a timeout by advancing time 2 seconds. +pub fn trigger_timeout(ep: &mut Dtls, now: &mut Instant) { + *now += Duration::from_secs(2); + ep.handle_timeout(*now).expect("handle_timeout"); +} + +/// Complete a full DTLS 1.3 handshake between client and server. +/// +/// Returns the final `Instant` (time advanced during the handshake). +/// Panics if the handshake does not complete within the iteration limit. +pub fn complete_dtls13_handshake( + client: &mut Dtls, + server: &mut Dtls, + mut now: Instant, +) -> Instant { + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(client); + let server_out = drain_outputs(server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, server); + deliver_packets(&server_out.packets, client); + + if client_connected && server_connected { + return now; + } + now += Duration::from_millis(10); + } + + panic!("DTLS 1.3 handshake did not complete within iteration limit"); +} + +/// Create a DTLS 1.3 config with default settings. +pub fn dtls13_config() -> Arc { + Arc::new( + Config::builder() + .build() + .expect("Failed to build DTLS 1.3 config"), + ) +} + +/// Create a DTLS 1.3 config with custom MTU. +pub fn dtls13_config_with_mtu(mtu: usize) -> Arc { + Arc::new( + Config::builder() + .mtu(mtu) + .build() + .expect("Failed to build DTLS 1.3 config"), + ) +} + +/// Create a connected DTLS 1.3 client/server pair with self-signed certificates. +/// +/// Returns `(client, server, now)` with the handshake already completed. +#[cfg(feature = "rcgen")] +pub fn setup_connected_13_pair(now: Instant) -> (Dtls, Dtls, Instant) { + use dimpl::certificate::generate_self_signed_certificate; + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls13_config(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let now = complete_dtls13_handshake(&mut client, &mut server, now); + (client, server, now) +} diff --git a/third_party/dimpl/tests/dtls13/conformance.rs b/third_party/dimpl/tests/dtls13/conformance.rs new file mode 100644 index 0000000..3719dc6 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/conformance.rs @@ -0,0 +1,528 @@ +//! DTLS 1.3 RFC 9147 conformance regression tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +#[cfg(feature = "rcgen")] +use dimpl::certificate::generate_self_signed_certificate; +use dimpl::{Config, Dtls}; + +use crate::common::*; + +const RECORD_HEADER_LEN: usize = 13; +const HANDSHAKE_HEADER_LEN: usize = 12; +const HANDSHAKE_OFFSET: usize = RECORD_HEADER_LEN; +const BODY_OFFSET: usize = RECORD_HEADER_LEN + HANDSHAKE_HEADER_LEN; + +fn set_u24(buf: &mut [u8], offset: usize, value: usize) { + let value = value as u32; + buf[offset] = (value >> 16) as u8; + buf[offset + 1] = (value >> 8) as u8; + buf[offset + 2] = value as u8; +} + +fn grow_plaintext_handshake(packet: &mut [u8], added: usize) { + let record_len = u16::from_be_bytes([packet[11], packet[12]]) as usize + added; + packet[11..13].copy_from_slice(&(record_len as u16).to_be_bytes()); + + let body_len = + ((packet[14] as usize) << 16) | ((packet[15] as usize) << 8) | packet[16] as usize; + set_u24(packet, 14, body_len + added); + + let fragment_len = + ((packet[22] as usize) << 16) | ((packet[23] as usize) << 8) | packet[24] as usize; + set_u24(packet, 22, fragment_len + added); +} + +fn insert_legacy_session_id(packet: &[u8], session_id: &[u8]) -> Vec { + assert_eq!(packet[0], 22, "expected plaintext handshake record"); + assert_eq!(packet[HANDSHAKE_OFFSET], 1, "expected ClientHello"); + + let sid_len_offset = BODY_OFFSET + 2 + 32; + assert_eq!( + packet[sid_len_offset], 0, + "dimpl ClientHello starts with empty session id" + ); + + let mut out = packet.to_vec(); + out[sid_len_offset] = session_id.len() as u8; + out.splice( + sid_len_offset + 1..sid_len_offset + 1, + session_id.iter().copied(), + ); + grow_plaintext_handshake(&mut out, session_id.len()); + out +} + +fn insert_legacy_cookie(packet: &[u8], cookie: &[u8]) -> Vec { + assert_eq!(packet[0], 22, "expected plaintext handshake record"); + assert_eq!(packet[HANDSHAKE_OFFSET], 1, "expected ClientHello"); + + let sid_len_offset = BODY_OFFSET + 2 + 32; + let cookie_len_offset = sid_len_offset + 1 + packet[sid_len_offset] as usize; + assert_eq!( + packet[cookie_len_offset], 0, + "dimpl ClientHello starts with empty legacy cookie" + ); + + let mut out = packet.to_vec(); + out[cookie_len_offset] = cookie.len() as u8; + out.splice( + cookie_len_offset + 1..cookie_len_offset + 1, + cookie.iter().copied(), + ); + grow_plaintext_handshake(&mut out, cookie.len()); + out +} + +fn plaintext_server_hello_legacy_session_id_len(packet: &[u8]) -> u8 { + assert_eq!(packet[0], 22, "expected plaintext handshake record"); + assert_eq!(packet[HANDSHAKE_OFFSET], 2, "expected ServerHello/HRR"); + packet[BODY_OFFSET + 2 + 32] +} + +fn ciphertext_record_count(packets: &[Vec]) -> usize { + let mut count = 0; + for packet in packets { + let mut input = packet.as_slice(); + while !input.is_empty() { + assert!( + input[0] & 0b1110_0000 == 0b0010_0000, + "expected ciphertext record, got first byte {:#04x}", + input[0] + ); + assert!( + input[0] & 0b0000_1000 != 0, + "test expects 2-byte sequence numbers" + ); + assert!( + input[0] & 0b0000_0100 != 0, + "test expects explicit ciphertext length" + ); + let len = u16::from_be_bytes([input[3], input[4]]) as usize; + count += 1; + input = &input[5 + len..]; + } + } + count +} + +fn has_ciphertext_record_len(packets: &[Vec], wanted: usize) -> bool { + for packet in packets { + let mut input = packet.as_slice(); + while !input.is_empty() { + let len = u16::from_be_bytes([input[3], input[4]]) as usize; + if len == wanted { + return true; + } + input = &input[5 + len..]; + } + } + false +} + +#[cfg(feature = "rcgen")] +fn connected_pair(config: Arc) -> (Dtls, Dtls, Instant) { + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + return (client, server, now); + } + now += Duration::from_millis(10); + } + + panic!("DTLS 1.3 handshake did not complete"); +} + +fn quiesce_pair(client: &mut Dtls, server: &mut Dtls, now: Instant) { + for _ in 0..8 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(client); + let server_out = drain_outputs(server); + let quiet = client_out.packets.is_empty() && server_out.packets.is_empty(); + + deliver_packets(&client_out.packets, server); + deliver_packets(&server_out.packets, client); + + if quiet { + break; + } + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn server_does_not_echo_client_legacy_session_id() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .use_server_cookie(false) + .build() + .expect("build config"), + ); + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + server.handle_timeout(now).expect("server timeout"); + + client.handle_timeout(now).expect("client timeout"); + let client_hello = drain_outputs(&mut client) + .packets + .into_iter() + .next() + .expect("client should emit ClientHello"); + let client_hello = insert_legacy_session_id(&client_hello, b"non-empty-session"); + + server + .handle_packet(&client_hello) + .expect("server should parse ClientHello"); + server.handle_timeout(now).expect("server timeout"); + let server_hello = drain_outputs(&mut server) + .packets + .into_iter() + .next() + .expect("server should emit ServerHello"); + + assert_eq!( + plaintext_server_hello_legacy_session_id_len(&server_hello), + 0, + "DTLS 1.3 servers MUST NOT echo legacy_session_id" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn server_rejects_non_empty_client_legacy_cookie() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .use_server_cookie(false) + .build() + .expect("build config"), + ); + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + server.handle_timeout(now).expect("server timeout"); + + client.handle_timeout(now).expect("client timeout"); + let client_hello = drain_outputs(&mut client) + .packets + .into_iter() + .next() + .expect("client should emit ClientHello"); + let client_hello = insert_legacy_cookie(&client_hello, b"legacy-cookie"); + + assert!( + server.handle_packet(&client_hello).is_err(), + "server must abort ClientHello messages with non-empty legacy_cookie" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn client_aborts_on_distinct_second_hello_retry_request() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls13_config(); + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout"); + let client_hello = drain_outputs(&mut client).packets; + deliver_packets(&client_hello, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let hrr = drain_outputs(&mut server) + .packets + .into_iter() + .next() + .expect("server should emit HRR"); + + client + .handle_packet(&hrr) + .expect("client accepts first HRR"); + client.handle_timeout(now).expect("client sends CH2"); + let _ = drain_outputs(&mut client); + let mut second_hrr = hrr.clone(); + second_hrr[17..19].copy_from_slice(&1u16.to_be_bytes()); + + assert!( + client.handle_packet(&second_hrr).is_err(), + "client must abort on a second HRR" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn application_data_waits_for_key_update_ack() { + let _ = env_logger::try_init(); + + let config = Arc::new( + Config::builder() + .aead_encryption_limit(3) + .build() + .expect("build config"), + ); + let (mut client, mut server, mut now) = connected_pair(config); + quiesce_pair(&mut client, &mut server, now); + + let mut key_update_out = None; + for i in 0..10 { + let msg = format!("key-update-prime-application-payload-{i}").into_bytes(); + client.send_application_data(&msg).expect("queue app data"); + let out = drain_outputs(&mut client).packets; + assert_eq!(ciphertext_record_count(&out), 1); + deliver_packets(&out, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert_eq!(server_out.app_data, vec![msg]); + now += Duration::from_millis(10); + + client.handle_timeout(now).expect("client timeout"); + let out = drain_outputs(&mut client).packets; + if has_ciphertext_record_len(&out, 30) { + key_update_out = Some(out); + break; + } + } + + let out = key_update_out.expect("client should initiate KeyUpdate"); + assert!(!out.is_empty(), "client should send a KeyUpdate"); + let old_epoch_msg = b"sent-on-old-epoch-before-key-update-ack".to_vec(); + client + .send_application_data(&old_epoch_msg) + .expect("send app data while KeyUpdate is in flight"); + let old_epoch_data = drain_outputs(&mut client).packets; + assert!( + !old_epoch_data.is_empty(), + "application data should continue on the old epoch while KeyUpdate is in flight" + ); + deliver_packets(&old_epoch_data, &mut server); + server + .handle_timeout(now) + .expect("server receives old-epoch data"); + let server_out = drain_outputs(&mut server); + assert_eq!(server_out.app_data, vec![old_epoch_msg]); + + deliver_packets(&out, &mut server); + server + .handle_timeout(now) + .expect("server processes KeyUpdate"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.is_empty(), + "processing the KeyUpdate should not produce duplicate application data" + ); + + deliver_packets(&server_out.packets, &mut client); + now += Duration::from_millis(10); + client + .handle_timeout(now) + .expect("client handles KeyUpdate ACK"); + let _ = drain_outputs(&mut client); +} + +#[test] +#[cfg(feature = "rcgen")] +fn update_requested_is_ignored_while_key_update_in_flight() { + let _ = env_logger::try_init(); + + let config = Arc::new( + Config::builder() + .aead_encryption_limit(3) + .build() + .expect("build config"), + ); + let (mut client, mut server, mut now) = connected_pair(config); + quiesce_pair(&mut client, &mut server, now); + + let mut client_key_update = None; + for i in 0..10 { + let msg = format!("client-prime-application-payload-{i}").into_bytes(); + client.send_application_data(&msg).expect("client send"); + let out = drain_outputs(&mut client).packets; + deliver_packets(&out, &mut server); + server.handle_timeout(now).expect("server timeout"); + let _ = drain_outputs(&mut server); + now += Duration::from_millis(10); + + client.handle_timeout(now).expect("client timeout"); + let out = drain_outputs(&mut client).packets; + if has_ciphertext_record_len(&out, 30) { + client_key_update = Some(out); + break; + } + } + + let mut server_key_update = None; + for i in 0..10 { + let msg = format!("server-prime-application-payload-{i}").into_bytes(); + server.send_application_data(&msg).expect("server send"); + let out = drain_outputs(&mut server).packets; + deliver_packets(&out, &mut client); + let _ = drain_outputs(&mut client); + now += Duration::from_millis(10); + + server.handle_timeout(now).expect("server timeout"); + let out = drain_outputs(&mut server).packets; + if has_ciphertext_record_len(&out, 30) { + server_key_update = Some(out); + break; + } + } + + let client_key_update = client_key_update.expect("client should initiate KeyUpdate"); + assert!( + !client_key_update.is_empty(), + "client should send its own KeyUpdate" + ); + + let server_key_update = server_key_update.expect("server should initiate KeyUpdate"); + assert!( + !server_key_update.is_empty(), + "server should send its own KeyUpdate" + ); + deliver_packets(&server_key_update, &mut client); + + client + .handle_timeout(now) + .expect("client processes peer KeyUpdate"); + let ack_only = drain_outputs(&mut client).packets; + assert_eq!( + ciphertext_record_count(&ack_only), + 1, + "client should ACK peer KeyUpdate" + ); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let response = drain_outputs(&mut client).packets; + + assert!( + response.is_empty(), + "client must not send a second KeyUpdate while the first is unacknowledged" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn server_retransmits_final_ack_for_retransmitted_client_final_flight() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("build config"), + ); + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_final_flight_seen = false; + let mut ack_dropped = false; + for round in 0..100 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + if client_final_flight_seen && !ack_dropped && !server_out.packets.is_empty() { + ack_dropped = true; + } else { + deliver_packets(&server_out.packets, &mut client); + } + + if !client_final_flight_seen && !client_out.packets.is_empty() && round > 2 { + client_final_flight_seen = true; + } + + if ack_dropped { + break; + } + + now += if round % 5 == 4 { + Duration::from_secs(2) + } else { + Duration::from_millis(10) + }; + } + + assert!(ack_dropped, "test should drop the server completion ACK"); + + let mut retransmitted_final_flight = Vec::new(); + for _ in 0..10 { + now += Duration::from_secs(2); + client + .handle_timeout(now) + .expect("client retransmit timeout"); + retransmitted_final_flight = drain_outputs(&mut client).packets; + if !retransmitted_final_flight.is_empty() { + break; + } + } + assert!( + !retransmitted_final_flight.is_empty(), + "client should retransmit its final flight" + ); + + deliver_packets(&retransmitted_final_flight, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_response = drain_outputs(&mut server).packets; + + assert!( + !server_response.is_empty(), + "server must retransmit its final ACK when the client final flight is retransmitted" + ); +} diff --git a/third_party/dimpl/tests/dtls13/data.rs b/third_party/dimpl/tests/dtls13/data.rs new file mode 100644 index 0000000..002ef64 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/data.rs @@ -0,0 +1,997 @@ +//! DTLS 1.3 application data tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Dtls, Output}; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_application_data_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let client_data = b"Hello from DTLS 1.3 client!"; + let server_data = b"Hello from DTLS 1.3 server!"; + + let mut client_connected = false; + let mut server_connected = false; + let mut client_received: Vec = Vec::new(); + let mut server_received: Vec = Vec::new(); + let mut client_sent = false; + let mut server_sent = false; + + for _ in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Collect received app data + for data in client_out.app_data { + client_received.extend_from_slice(&data); + } + for data in server_out.app_data { + server_received.extend_from_slice(&data); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + // Send data once connected + if client_connected && !client_sent { + client + .send_application_data(client_data) + .expect("client send"); + client_sent = true; + } + if server_connected && !server_sent { + server + .send_application_data(server_data) + .expect("server send"); + server_sent = true; + } + + if !client_received.is_empty() && !server_received.is_empty() { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + assert_eq!( + client_received, server_data, + "Client should receive server's data" + ); + assert_eq!( + server_received, client_data, + "Server should receive client's data" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_multiple_application_data_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // First complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Now send multiple messages + let messages = vec![ + b"Message 1".to_vec(), + b"Message 2".to_vec(), + b"Message 3 is a bit longer".to_vec(), + b"Message 4".to_vec(), + b"Message 5 - the final one".to_vec(), + ]; + + for msg in &messages { + client.send_application_data(msg).expect("client send"); + } + + let mut server_received: Vec> = Vec::new(); + + for _ in 0..20 { + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + let server_out = drain_outputs(&mut server); + for data in server_out.app_data { + server_received.push(data); + } + + if server_received.len() >= messages.len() { + break; + } + + now += Duration::from_millis(10); + } + + // Flatten and compare + let expected: Vec = messages.iter().flatten().copied().collect(); + let received: Vec = server_received.iter().flatten().copied().collect(); + + assert_eq!(received, expected, "All messages should be received"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_bidirectional_data_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Exchange data in both directions simultaneously + let rounds = 10; + let mut client_received_count = 0; + let mut server_received_count = 0; + + for i in 0..rounds { + let client_msg = format!("Client message {}", i); + let server_msg = format!("Server message {}", i); + + client + .send_application_data(client_msg.as_bytes()) + .expect("client send"); + server + .send_application_data(server_msg.as_bytes()) + .expect("server send"); + + for _ in 0..10 { + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_received_count += client_out.app_data.len(); + server_received_count += server_out.app_data.len(); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + now += Duration::from_millis(5); + } + } + + assert_eq!( + client_received_count, rounds, + "Client should receive all server messages" + ); + assert_eq!( + server_received_count, rounds, + "Server should receive all client messages" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_many_small_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Send many small messages + let message_count = 100; + for i in 0..message_count { + let msg = format!("M{}", i); + client.send_application_data(msg.as_bytes()).expect("send"); + } + + let mut received_bytes: Vec = Vec::new(); + + for _ in 0..50 { + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + let server_out = drain_outputs(&mut server); + for data in server_out.app_data { + received_bytes.extend_from_slice(&data); + } + + now += Duration::from_millis(10); + } + + // Verify we received something + assert!( + !received_bytes.is_empty(), + "Should receive application data" + ); +} + +/// Test that application data queued before handshake completion is piggybacked +/// with the Finished message in the same packet. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_piggybacks_app_data_with_finished() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + let mut server_received_early_data = false; + let mut packets_after_finished_sent = 0; + let mut finished_sent = false; + + // Queue application data immediately - before handshake starts + // This should be piggybacked with the Finished message + client + .send_application_data(b"Early piggybacked data!") + .expect("queue early data"); + eprintln!("Queued early application data before handshake"); + + // Run handshake + for round in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Track when client becomes connected (Finished was sent) + if client_out.connected && !finished_sent { + finished_sent = true; + eprintln!("Round {}: Client sent Finished (connected event)", round); + } + + // Count packets sent after Finished + if finished_sent && !server_received_early_data { + packets_after_finished_sent += client_out.packets.len(); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + // Check if server received the early data + if !server_out.app_data.is_empty() { + server_received_early_data = true; + let received = String::from_utf8_lossy(&server_out.app_data[0]); + eprintln!( + "Round {}: Server received early data: '{}' (packets since Finished: {})", + round, received, packets_after_finished_sent + ); + assert_eq!( + &server_out.app_data[0][..], + b"Early piggybacked data!", + "Should receive the queued early data" + ); + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected && server_received_early_data { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + assert!( + server_received_early_data, + "Server should receive piggybacked early data" + ); + + // The early data should arrive in the same round as the Finished message + // (piggybacked in the same flight). packets_after_finished_sent counts packets + // sent AFTER connected event, which should be 0 if piggybacked correctly + // (the app data goes out with the Finished, not after) + eprintln!( + "SUCCESS: Early data was piggybacked. Packets after Finished sent: {}", + packets_after_finished_sent + ); +} + +/// Test that server can piggyback application data with its first response (Finished). +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_server_piggybacks_app_data_with_finished() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + let mut client_received_early_data = false; + let mut server_finished_sent = false; + let mut packets_after_server_finished = 0; + + // Queue application data on server immediately - before handshake starts + // This should be piggybacked with the server's Finished message + server + .send_application_data(b"Server early piggybacked data!") + .expect("queue server early data"); + eprintln!("Queued server early application data before handshake"); + + // Run handshake + for round in 0..50 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Server sends Finished before becoming "connected" (it waits for client's Finished) + // We detect this by checking if server sent packets that contain encrypted data + // before client is connected + if !server_finished_sent && !server_out.packets.is_empty() && round > 0 { + // After round 0 (ClientHello), if server sends packets it's likely ServerHello + Finished flight + if round >= 1 { + server_finished_sent = true; + eprintln!("Round {}: Server sent its Finished flight", round); + } + } + + // Count packets sent after server Finished + if server_finished_sent && !client_received_early_data { + packets_after_server_finished += server_out.packets.len(); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + // Check if client received the early data from server + if !client_out.app_data.is_empty() { + client_received_early_data = true; + let received = String::from_utf8_lossy(&client_out.app_data[0]); + eprintln!( + "Round {}: Client received early data from server: '{}' (packets since server Finished: {})", + round, received, packets_after_server_finished + ); + assert_eq!( + &client_out.app_data[0][..], + b"Server early piggybacked data!", + "Should receive the server's queued early data" + ); + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected && client_received_early_data { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + assert!( + client_received_early_data, + "Client should receive piggybacked early data from server" + ); + + eprintln!( + "SUCCESS: Server early data was piggybacked. Packets after server Finished: {}", + packets_after_server_finished + ); +} + +/// Test that application data is cached when a handshake packet is lost, +/// and decrypted once the retransmission arrives. +/// +/// Scenario: +/// 1. Server sends flight: ServerHello + Certificate + Finished + piggybacked app data +/// 2. One packet containing Certificate is dropped +/// 3. Client receives app data (epoch 3) but can't derive keys yet +/// 4. Client should cache/defer the app data +/// 5. Server retransmits the lost Certificate packet +/// 6. Client completes handshake and decrypts the cached app data +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_caches_app_data_when_handshake_packet_lost() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use small MTU to ensure server flight is split into multiple packets + let config = dtls13_config_with_mtu(200); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + let mut client_received_app_data = false; + let mut dropped_packet_round = None; + let mut server_first_flight_sent = false; + + // Queue application data on server before handshake + server + .send_application_data(b"Cached then decrypted!") + .expect("queue server app data"); + eprintln!("Queued server application data before handshake"); + + // Run handshake with packet loss simulation + for round in 0..100 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Deliver client packets to server (no loss) + deliver_packets(&client_out.packets, &mut server); + + // For server's first flight (round 1), drop one of the middle packets + // to simulate losing part of the Certificate + if !server_first_flight_sent && server_out.packets.len() > 2 && round > 0 { + server_first_flight_sent = true; + let num_packets = server_out.packets.len(); + + // Drop a middle packet (likely contains Certificate data) + let drop_idx = num_packets / 2; + dropped_packet_round = Some(round); + eprintln!( + "Round {}: DROPPING packet {} of {} (simulating Certificate loss)", + round, drop_idx, num_packets + ); + + for (i, p) in server_out.packets.iter().enumerate() { + if i != drop_idx { + let _ = client.handle_packet(p); + } + } + } else { + // Normal delivery for subsequent rounds (including retransmissions) + if !server_out.packets.is_empty() && dropped_packet_round.is_some() { + eprintln!( + "Round {}: Server sending {} packets (retransmission)", + round, + server_out.packets.len() + ); + } + deliver_packets(&server_out.packets, &mut client); + } + + // Check if client received the application data + if !client_out.app_data.is_empty() { + client_received_app_data = true; + let received = String::from_utf8_lossy(&client_out.app_data[0]); + eprintln!( + "Round {}: Client received app data: '{}' (dropped packet was in round {:?})", + round, received, dropped_packet_round + ); + assert_eq!( + &client_out.app_data[0][..], + b"Cached then decrypted!", + "Should receive the server's cached app data" + ); + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected && client_received_app_data { + break; + } + + // Advance time to trigger retransmission + now += Duration::from_millis(100); + } + + assert!( + dropped_packet_round.is_some(), + "Test should have dropped a packet" + ); + assert!( + client_connected, + "Client should connect after retransmission" + ); + assert!(server_connected, "Server should connect"); + assert!( + client_received_app_data, + "Client should receive cached app data after handshake completes" + ); + + eprintln!( + "SUCCESS: App data was cached during handshake packet loss and decrypted after retransmission" + ); +} + +/// Test that large application data (exceeding MTU) is sent and received intact. +/// +/// With the default MTU of 1150, a 5000-byte message produces a single record +/// in an oversized datagram. The receiver must decrypt and deliver the full payload. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_large_application_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Build a 5000-byte payload (exceeds 1150 MTU) + let large_data: Vec = (0..5000).map(|i| (i % 256) as u8).collect(); + + client + .send_application_data(&large_data) + .expect("client send large data"); + + // Poll with a buffer large enough for the oversized record + let mut big_buf = vec![0u8; 8192]; + let mut server_received: Vec = Vec::new(); + + for _ in 0..20 { + // Drain client outputs: collect packets with large buffer + let mut client_packets: Vec> = Vec::new(); + loop { + match client.poll_output(&mut big_buf) { + Output::Packet(p) => client_packets.push(p.to_vec()), + Output::Timeout(_) => break, + _ => {} + } + } + + deliver_packets(&client_packets, &mut server); + + // Drain server outputs: collect app data with large buffer + loop { + match server.poll_output(&mut big_buf) { + Output::ApplicationData(data) => { + server_received.extend_from_slice(data); + } + Output::Timeout(_) => break, + _ => {} + } + } + + if !server_received.is_empty() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!( + server_received.len(), + 5000, + "Server should receive all 5000 bytes" + ); + assert_eq!( + server_received, large_data, + "Server should receive the exact large payload" + ); +} + +/// Test that application data continues to work after a KeyUpdate. +/// +/// Sets a very low AEAD encryption limit (5) so that sending 10 messages +/// triggers an automatic KeyUpdate. Then sends 5 more messages and verifies +/// all 15 are received, confirming data flows correctly on the new epoch keys. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_data_after_key_update() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Low AEAD limit triggers KeyUpdate after 5 encryptions (with jitter, ~4-5) + let config = Arc::new( + Config::builder() + .aead_encryption_limit(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + let total_messages = 15; + let mut server_received: Vec> = Vec::new(); + + // Send messages one at a time, polling between each to allow KeyUpdate + // handshake messages to flow and to avoid filling the TX queue + for i in 0..total_messages { + let msg = format!("Message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("client send"); + + // Run several exchange rounds to let KeyUpdate complete + for _ in 0..10 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + for data in server_out.app_data { + server_received.push(data); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + now += Duration::from_millis(10); + } + } + + // Verify all messages received + assert_eq!( + server_received.len(), + total_messages, + "Server should receive all {} messages (got {})", + total_messages, + server_received.len() + ); + + for (i, data) in server_received.iter().enumerate() { + let expected = format!("Message {}", i); + assert_eq!(data, expected.as_bytes(), "Message {} should match", i); + } +} + +/// Test that the transmit queue returns an error (not a panic) when full. +/// +/// After handshake, sends application data without polling outputs until +/// the transmit queue overflows. Verifies `Error::TransmitQueueFull` is returned. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_queue_overflow_tx() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Small TX queue to trigger overflow quickly + let config = Arc::new( + Config::builder() + .max_queue_tx(3) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Send messages WITHOUT polling outputs to fill the TX queue. + // Use messages large enough that each one creates a new datagram + // (exceeding MTU prevents coalescing into the same datagram). + let big_msg = vec![0xAB; 1100]; + let mut overflow_error = false; + + for i in 0..50 { + match client.send_application_data(&big_msg) { + Ok(()) => {} + Err(e) => { + eprintln!("TX queue overflow at message {}: {}", i, e); + assert!( + matches!(e, dimpl::Error::TransmitQueueFull), + "Expected TransmitQueueFull, got: {}", + e + ); + overflow_error = true; + break; + } + } + } + + assert!( + overflow_error, + "Should have received TransmitQueueFull error" + ); +} + +/// Test that the receive queue drops packets gracefully when full. +/// +/// After handshake, delivers more packets than `max_queue_rx` allows without +/// reading application data. Verifies `handle_packet` returns `ReceiveQueueFull` +/// (no panic). +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_queue_overflow_rx() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Small RX queue to trigger overflow quickly + let config = Arc::new( + Config::builder() + .max_queue_rx(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Send many messages from client, collecting the wire packets + let mut all_packets: Vec> = Vec::new(); + + for i in 0..20 { + let msg = format!("Overflow msg {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("client send"); + + let client_out = drain_outputs(&mut client); + all_packets.extend(client_out.packets); + } + + // Deliver all packets to server WITHOUT draining its outputs. + // The server's RX queue (max 5) should eventually reject packets. + let mut overflow_error = false; + + for (i, packet) in all_packets.iter().enumerate() { + match server.handle_packet(packet) { + Ok(()) => {} + Err(e) => { + eprintln!("RX queue overflow at packet {}: {}", i, e); + assert!( + matches!(e, dimpl::Error::ReceiveQueueFull), + "Expected ReceiveQueueFull, got: {}", + e + ); + overflow_error = true; + break; + } + } + } + + assert!( + overflow_error, + "Should have received ReceiveQueueFull error" + ); +} diff --git a/third_party/dimpl/tests/dtls13/edge.rs b/third_party/dimpl/tests/dtls13/edge.rs new file mode 100644 index 0000000..c68ea46 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/edge.rs @@ -0,0 +1,2061 @@ +//! DTLS 1.3 edge case and error recovery tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +#[cfg(feature = "rcgen")] +use dimpl::certificate::generate_self_signed_certificate; +use dimpl::{Config, Dtls, Output}; + +use crate::common::*; + +fn dtls13_alert_record(seq: u64, level: u8, description: u8) -> Vec { + let mut out = Vec::new(); + out.push(21); // Alert + out.extend_from_slice(&[0xFE, 0xFD]); // legacy DTLS record version + out.extend_from_slice(&0u16.to_be_bytes()); // epoch 0 plaintext + out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number + out.extend_from_slice(&2u16.to_be_bytes()); // alert payload length + out.extend_from_slice(&[level, description]); // legacy level, description + out +} + +fn dtls13_ack_record(seq: u64) -> Vec { + let mut out = Vec::new(); + out.push(26); // Ack + out.extend_from_slice(&[0xFE, 0xFD]); // legacy DTLS record version + out.extend_from_slice(&0u16.to_be_bytes()); // epoch 0 plaintext + out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number + out.extend_from_slice(&2u16.to_be_bytes()); // arbitrary payload length + out.extend_from_slice(&[0xAA, 0xBB]); + out +} + +fn dtls13_ack_record_for_records(seq: u64, records: &[(u64, u64)]) -> Vec { + let record_numbers_len = (records.len() * 16) as u16; + let mut fragment = Vec::with_capacity(2 + records.len() * 16); + fragment.extend_from_slice(&record_numbers_len.to_be_bytes()); + for &(epoch, record_seq) in records { + fragment.extend_from_slice(&epoch.to_be_bytes()); + fragment.extend_from_slice(&record_seq.to_be_bytes()); + } + + let mut out = Vec::new(); + out.push(26); // Ack + out.extend_from_slice(&[0xFE, 0xFD]); // legacy DTLS record version + out.extend_from_slice(&0u16.to_be_bytes()); // epoch 0 plaintext + out.extend_from_slice(&seq.to_be_bytes()[2..]); // u48 sequence number + out.extend_from_slice(&(fragment.len() as u16).to_be_bytes()); + out.extend_from_slice(&fragment); + out +} + +#[test] +#[cfg(feature = "rcgen")] +fn oversized_application_data_reports_buffer_too_small() { + let now = Instant::now(); + let (mut client, mut server, _now) = setup_connected_13_pair(now); + let payload = vec![0xa5; 4000]; + + client + .send_application_data(&payload) + .expect("send application data"); + + let mut large_buf = vec![0u8; 8192]; + let mut packets = Vec::new(); + loop { + match client.poll_output(&mut large_buf) { + Output::Packet(packet) => packets.push(packet.to_vec()), + Output::Timeout(_) => break, + _ => {} + } + } + + deliver_packets(&packets, &mut server); + + let mut small_buf = vec![0u8; 2048]; + match server.poll_output(&mut small_buf) { + Output::BufferTooSmall { needed } => assert_eq!(needed, payload.len()), + output => panic!("expected BufferTooSmall, got {output:?}"), + } + + match server.poll_output(&mut large_buf) { + Output::ApplicationData(data) => assert_eq!(data, payload.as_slice()), + output => panic!("expected retained application data, got {output:?}"), + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_malformed_datagram_is_discarded_without_processing_alerts() { + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls13_config(); + let now = Instant::now(); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut packet = dtls13_alert_record(1, 2, 40); + packet.push(0xFF); // trailing truncated record header + + server + .handle_packet(&packet) + .expect("malformed datagram should be discarded"); + + let mut buf = [0; 1500]; + assert!(!matches!(server.poll_output(&mut buf), Output::CloseNotify)); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_too_many_control_records_are_discarded() { + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls13_config(); + let now = Instant::now(); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut packet = Vec::new(); + for seq in 1..=17 { + packet.extend_from_slice(&dtls13_ack_record(seq)); + } + + server + .handle_packet(&packet) + .expect("too many records should be discarded"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_discards_too_short_ciphertext_record() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Every length in [0, AEAD overhead) must be rejected at the record boundary. + // For the default DTLS 1.3 suites the AEAD overhead is the tag length (16). + // Header: fixed bits 001, C=0, S=1 (16-bit seq), L=1 (length), epoch_bits=3 + // => 0b0010_1111 = 0x2F + for len in 0..16u16 { + let mut bogus = Vec::with_capacity(5 + len as usize); + bogus.push(0x2F); + bogus.extend_from_slice(&(0x0100 + len).to_be_bytes()); // encrypted seq bits + bogus.extend_from_slice(&len.to_be_bytes()); + bogus.resize(5 + len as usize, 0); + + client + .handle_packet(&bogus) + .expect("short ciphertext record should be silently discarded"); + } + + // Verify we can still exchange application data. + client.send_application_data(b"ping").expect("send app"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), + "Server should receive application data after bogus packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_discards_cid_bit_records() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Unified header with CID bit set: 001CSLEE with C=1, S=1, L=1, epoch_bits=3 => 0x3F. + // We don't support CID, so this should be silently discarded. + let bogus = vec![0x3F]; + + client + .handle_packet(&bogus) + .expect("CID-bit record should be discarded"); + + // Verify we can still exchange application data. + client.send_application_data(b"ping").expect("send app"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), + "Server should receive application data after CID-bit bogus packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_discards_unauthenticated_ciphertext_without_length_field() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Craft a DTLS 1.3 ciphertext record with L=0 (no explicit length). + // Header: 001CSLEE with C=0, S=1, L=0, epoch_bits=3 => 0x2B. + // Provide 16+ bytes ciphertext so sequence-number mask can be computed. + let mut bogus = Vec::new(); + bogus.push(0x2B); + bogus.extend_from_slice(&0x0001u16.to_be_bytes()); // encrypted seq bits + bogus.extend_from_slice(&[0u8; 16]); // unauthenticated ciphertext/tag bytes + + client + .handle_packet(&bogus) + .expect("Unauthenticated ciphertext should be discarded"); + + // Verify we can still exchange application data. + client.send_application_data(b"ping").expect("send app"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), + "Server should receive application data after unauthenticated bogus packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_recovers_from_corrupted_packet() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut corrupted_once = false; + + for i in 0..60 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Corrupt one packet + for mut p in client_out.packets { + if !corrupted_once && p.len() > 20 { + // Corrupt some bytes in the middle (handshake length field) + p[15] ^= 0xFF; + p[16] ^= 0xFF; + corrupted_once = true; + } + let _ = server.handle_packet(&p); + } + + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(50); + } + } + + assert!( + client_connected, + "Client should connect despite corrupted packet" + ); + assert!( + server_connected, + "Server should connect despite corrupted packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_close_notify_graceful_shutdown() { + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + // Client initiates graceful shutdown. + client.close().expect("client close"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "Client should emit close_notify packet" + ); + + // Deliver the close_notify alert to the server. + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.close_notify, + "Server should observe CloseNotify from client" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_warning_user_canceled_alert_is_ignored() { + let _ = env_logger::try_init(); + + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + let warning_alert = dtls13_alert_record(100, 1, 90); + server + .handle_packet(&warning_alert) + .expect("warning alert should be ignored"); + + let server_out = drain_outputs(&mut server); + assert!( + !server_out.close_notify, + "warning alert must not be reported as close_notify" + ); + + client + .send_application_data(b"still-open") + .expect("connection should remain open after warning alert"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "client should still emit application data after warning alert" + ); + + for packet in &client_out.packets { + server + .handle_packet(packet) + .expect("server should still accept packets after warning alert"); + } + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out + .app_data + .iter() + .any(|data| data.as_slice() == b"still-open"), + "application data should still be delivered after warning alert" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_unknown_warning_level_alert_is_still_fatal() { + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = dtls13_config(); + let now = Instant::now(); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // handshake_failure(40) with level=warning(1): TLS 1.3 ignores the level + // byte, so this must still be treated as fatal. + let packet = dtls13_alert_record(1, 1, 40); + let err = server + .handle_packet(&packet) + .expect_err("non-whitelisted alert must be fatal regardless of level"); + assert!(matches!( + err, + dimpl::Error::SecurityError(dimpl::SecurityError::FatalAlert { description: 40 }) + )); +} + +fn queue_ack_with_peer_key_update(sender: &mut Dtls, receiver: &mut Dtls, now: &mut Instant) { + for i in 0..5 { + sender + .send_application_data(format!("msg{i}").as_bytes()) + .expect("send app data"); + } + + *now += Duration::from_millis(10); + sender.handle_timeout(*now).expect("sender timeout"); + let sender_out = drain_outputs(sender); + assert!( + !sender_out.packets.is_empty(), + "sender should emit app data and KeyUpdate" + ); + + for packet in &sender_out.packets { + receiver + .handle_packet(packet) + .expect("receiver should accept KeyUpdate batch"); + } +} + +fn drain_expected_app_data(endpoint: &mut Dtls, expected: usize) { + let mut buf = vec![0u8; 2048]; + for i in 0..expected { + match endpoint.poll_output(&mut buf) { + Output::ApplicationData(data) => { + assert_eq!( + data, + format!("msg{i}").as_bytes(), + "unexpected queued application data before close()" + ); + } + _ => panic!("expected queued application data"), + } + } +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_client_close_after_queued_ack_sends_close_notify() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = Arc::new( + Config::builder() + .aead_encryption_limit(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + queue_ack_with_peer_key_update(&mut server, &mut client, &mut now); + drain_expected_app_data(&mut client, 5); + + client + .close() + .expect("close should succeed with queued ACK pending"); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let mut buf = vec![0u8; 2048]; + let first_packet = match client.poll_output(&mut buf) { + Output::Packet(packet) => packet.to_vec(), + _ => panic!("expected first close output packet"), + }; + + server + .handle_packet(&first_packet) + .expect("server should accept the first client close packet"); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.close_notify, + "server should observe close_notify from the first client close packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_server_close_after_queued_ack_sends_close_notify() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let config = Arc::new( + Config::builder() + .aead_encryption_limit(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + queue_ack_with_peer_key_update(&mut client, &mut server, &mut now); + drain_expected_app_data(&mut server, 5); + + server + .close() + .expect("close should succeed with queued ACK pending"); + + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let mut buf = vec![0u8; 2048]; + let first_packet = match server.poll_output(&mut buf) { + Output::Packet(packet) => packet.to_vec(), + _ => panic!("expected first close output packet"), + }; + + client + .handle_packet(&first_packet) + .expect("client should accept the first server close packet"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.close_notify, + "client should observe close_notify from the first server close packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_discards_unknown_epoch_record() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // After handshake, application data uses epoch 3 (epoch_bits = 3 & 0x03 = 3). + // Craft a ciphertext record with epoch_bits=1, which would map to epoch 1 if + // no keys exist for it (or to an epoch whose low 2 bits are 01, e.g. epoch 5 + // which has never been negotiated). + // + // Unified header: 001CSLEE with C=0, S=1, L=1, EE=01 => 0b0010_1101 = 0x2D. + // This targets epoch_bits=1 -- no keys installed for any epoch with low bits 01. + let mut bogus = Vec::new(); + bogus.push(0x2D); // flags: S=1, L=1, epoch_bits=01 + bogus.extend_from_slice(&0x0000u16.to_be_bytes()); // encrypted seq bits + bogus.extend_from_slice(&0x0020u16.to_be_bytes()); // length = 32 + bogus.extend_from_slice(&[0xAA; 32]); // fake ciphertext (will fail AEAD) + + // Should be silently discarded (decryption will fail since no keys for this epoch) + client + .handle_packet(&bogus) + .expect("unknown-epoch record should be discarded"); + + // Verify normal data exchange still works. + client.send_application_data(b"ping").expect("send app"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), + "Server should receive application data after unknown-epoch bogus packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_discards_truncated_unified_header() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Deliver a 1-byte packet that looks like a unified header but is truncated. + // 0x2F = 001CSLEE with C=0, S=1, L=1, EE=11 -- expects at least 5 header + // bytes (flags + 2 seq + 2 length) but we only provide the flags byte. + let bogus = vec![0x2F]; + + // The parser requires at least 2 bytes for a ciphertext record. This should + // result in a parse error, but handle_packet may surface it as Err. Either way, + // the endpoint must remain operational. + let _ = client.handle_packet(&bogus); + + // Verify normal operation continues. + client.send_application_data(b"ping").expect("send app"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.iter().any(|d| d.as_slice() == b"ping"), + "Server should receive application data after truncated header packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_discards_plaintext_after_handshake() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Craft a DTLS 1.2-style plaintext record (13-byte header). + // content_type=22 (Handshake), version=0xFEFD (DTLS 1.2), epoch=0, seq=0, + // length=5, then 5 bytes of garbage body. + let bogus = vec![ + 0x16, // content_type: Handshake + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // sequence_number: 0 + 0x00, 0x05, // length: 5 + 0x01, 0x00, 0x00, 0x00, 0x00, // 5 bytes of fake handshake body + ]; + + // Delivering a plaintext handshake record after the handshake is complete should + // be silently discarded per RFC 9147. The connection must remain operational. + client + .handle_packet(&bogus) + .expect("silently discard should not return error"); + + // Verify application data exchange still works. + client + .send_application_data(b"after-plaintext") + .expect("send app"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"after-plaintext"), + "Server should receive application data after plaintext bogus packet" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_post_encryption_plaintext_close_notify_is_ignored() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + server + .handle_packet(&dtls13_alert_record(0x100, 1, 0)) + .expect("post-encryption plaintext close_notify should be ignored"); + + let after_plaintext_alert = drain_outputs(&mut server); + assert!( + !after_plaintext_alert.close_notify, + "plaintext close_notify after encryption must not close the connection" + ); + + client + .send_application_data(b"after-plaintext-close-notify") + .expect("send app data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"after-plaintext-close-notify"), + "server should accept encrypted app data after plaintext close_notify" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_post_encryption_plaintext_fatal_alert_is_ignored() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + server + .handle_packet(&dtls13_alert_record(0x101, 2, 40)) + .expect("post-encryption plaintext fatal alert should be ignored"); + + client + .send_application_data(b"after-plaintext-fatal-alert") + .expect("send app data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"after-plaintext-fatal-alert"), + "server should accept encrypted app data after plaintext fatal alert" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_post_encryption_plaintext_ack_does_not_stop_retransmit() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .flight_start_rto(Duration::from_millis(100)) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout"); + let client_hello = collect_packets(&mut client); + assert!(!client_hello.is_empty(), "client should emit ClientHello"); + + deliver_packets(&client_hello, &mut server); + server.handle_timeout(now).expect("server timeout"); + let first_server_flight = collect_packets(&mut server); + assert!( + !first_server_flight.is_empty(), + "server should emit first flight" + ); + + // If this unauthenticated plaintext ACK reaches process_ack, it can mark + // the saved epoch-2 handshake flight as fully acknowledged and disable + // retransmission. The classify_record guard must discard it first. + let acked_records: Vec<(u64, u64)> = (0..64).map(|seq| (2, seq)).collect(); + server + .handle_packet(&dtls13_ack_record_for_records(0x200, &acked_records)) + .expect("post-encryption plaintext ACK should be ignored"); + + // The flight timer jitter is absolute (+/-250 ms), so wait past the + // maximum possible jitter for a 100 ms start RTO. + now += Duration::from_millis(400); + server.handle_timeout(now).expect("server timeout"); + let retransmit = collect_packets(&mut server); + assert!( + !retransmit.is_empty(), + "forged plaintext ACK must not stop server flight retransmission" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_duplicate_client_hello_still_triggers_retransmit_after_peer_encryption() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout"); + let client_hello = collect_packets(&mut client); + assert!(!client_hello.is_empty(), "client should emit ClientHello"); + + deliver_packets(&client_hello, &mut server); + server.handle_timeout(now).expect("server timeout"); + let first_server_flight = collect_packets(&mut server); + assert!( + !first_server_flight.is_empty(), + "server should emit ServerHello plus encrypted handshake flight" + ); + + deliver_packets(&client_hello, &mut server); + let retransmit = collect_packets(&mut server); + assert!( + !retransmit.is_empty(), + "duplicate plaintext ClientHello should still trigger server flight retransmission" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_alert_bad_certificate() { + // NOTE: dimpl does not perform certificate chain/trust validation. The library + // surfaces the peer's leaf certificate via Output::PeerCert and delegates all + // validation to the application layer. There is no configurable certificate + // verifier or trust store that could cause the handshake to fail due to a + // "bad certificate". + // + // This test documents the gap: dimpl should ideally support a pluggable + // certificate verifier callback (e.g., via Config) so that applications can + // reject untrusted certificates and trigger an appropriate alert. + // + // Since both endpoints use self-signed certificates and dimpl accepts them + // unconditionally, we verify that the handshake completes and the peer + // certificates are surfaced via Output::PeerCert. The application would + // then inspect the certificate and decide whether to continue. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Store the DER bytes so we can verify PeerCert output + let client_cert_der = client_cert.certificate.clone(); + let server_cert_der = server_cert.certificate.clone(); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut client_peer_cert: Option> = None; + let mut server_peer_cert: Option> = None; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_out.peer_cert.is_some() { + client_peer_cert = client_out.peer_cert; + } + if server_out.peer_cert.is_some() { + server_peer_cert = server_out.peer_cert; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); + + // Verify that PeerCert was emitted so the application can inspect it. + // The client should see the server's certificate and vice versa. + let client_saw_cert = client_peer_cert.expect("Client should receive PeerCert"); + assert_eq!( + client_saw_cert, server_cert_der, + "Client's PeerCert should match the server's certificate" + ); + + let server_saw_cert = server_peer_cert.expect("Server should receive PeerCert"); + assert_eq!( + server_saw_cert, client_cert_der, + "Server's PeerCert should match the client's certificate" + ); + + // Gap: no way to reject a certificate and trigger a bad_certificate alert. + // When a certificate verifier callback is added to Config, this test should + // be updated to install a verifier that rejects the peer's self-signed cert + // and assert the handshake fails with an appropriate error. +} + +/// Regression test for bug #1: advertised signature schemes must all be functional. +/// +/// Previously, Ed25519 (0x0807) and RSA_PSS_RSAE_SHA256 (0x0804) were advertised +/// in the ClientHello signature_algorithms extension but could not be verified, +/// causing handshake failures when a peer selected them. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_only_functional_signature_schemes_advertised() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut client = Dtls::new_13(config, client_cert, now); + client.set_active(true); + + // Trigger the first ClientHello + client.handle_timeout(now).expect("client timeout"); + let out = drain_outputs(&mut client); + assert!(!out.packets.is_empty(), "Client should send ClientHello"); + + // The first packet is a plaintext record containing the ClientHello. + // DTLSPlaintext header: content_type(1) + version(2) + epoch(2) + seq(6) + length(2) = 13 bytes. + // Handshake header: msg_type(1) + length(3) + message_seq(2) + // + frag_offset(3) + frag_length(3) = 12 bytes. + // ClientHello body: version(2) + random(32) + session_id_len(1) + session_id + cookie_len(1) + cookie + // + cipher_suites_len(2) + cipher_suites + comp_methods_len(1) + comp_methods + // + extensions_len(2) + extensions... + let ch_packet = &out.packets[0]; + + // Find signature_algorithms extension (type 0x000D) in the packet. + // Scan for the 2-byte extension type. + let sig_alg_type: [u8; 2] = [0x00, 0x0D]; + let pos = ch_packet + .windows(2) + .position(|w| w == sig_alg_type) + .expect("signature_algorithms extension should be present in ClientHello"); + + // Extension format: type(2) + ext_len(2) + list_len(2) + schemes(2 each) + let ext_len_offset = pos + 2; + let list_len_offset = ext_len_offset + 2; + let list_len = + u16::from_be_bytes([ch_packet[list_len_offset], ch_packet[list_len_offset + 1]]) as usize; + let schemes_start = list_len_offset + 2; + + // Extract all advertised scheme codes + let mut advertised: Vec = Vec::new(); + let mut i = schemes_start; + while i < schemes_start + list_len { + let scheme = u16::from_be_bytes([ch_packet[i], ch_packet[i + 1]]); + advertised.push(scheme); + i += 2; + } + + // Only ECDSA P-256 (0x0403) and P-384 (0x0503) should be advertised. + let non_functional: Vec = advertised + .iter() + .copied() + .filter(|s| *s != 0x0403 && *s != 0x0503) + .collect(); + + assert!( + non_functional.is_empty(), + "Non-functional signature schemes advertised: {:04X?}. \ + Only ECDSA_SECP256R1_SHA256 (0x0403) and ECDSA_SECP384R1_SHA384 (0x0503) \ + should be advertised.", + non_functional, + ); + + assert_eq!( + advertised, + vec![0x0403, 0x0503], + "Expected exactly ECDSA P-256 and P-384" + ); +} + +/// Regression test for bug #2: a bad record in a multi-record datagram must not +/// kill subsequent valid records. +/// +/// Previously, certain per-record errors (parse failure, content type recovery) +/// would propagate as Err and abort parsing of the entire datagram, causing valid +/// records after the bad one to be lost. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_bad_record_does_not_kill_datagram() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Send application data from server and capture the ciphertext packet. + server + .send_application_data(b"hello") + .expect("send app data"); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "Server should produce a packet" + ); + let good_record = &server_out.packets[0]; + + // Construct a bogus ciphertext record with unknown epoch (epoch_bits=01). + // Unified header: flags=0x2D (001 C=0 S=1 L=1 EE=01), seq=0x0000, length=32. + let mut bogus_record = Vec::new(); + bogus_record.push(0x2D); // flags: S=1, L=1, epoch_bits=01 + bogus_record.extend_from_slice(&0x0000u16.to_be_bytes()); // encrypted seq + bogus_record.extend_from_slice(&0x0020u16.to_be_bytes()); // length = 32 + bogus_record.extend_from_slice(&[0xAA; 32]); // fake ciphertext + + // Build a multi-record datagram: bogus record FIRST, then the valid record. + // If the bad record aborts the datagram, the good record is lost. + let mut combined = bogus_record; + combined.extend_from_slice(good_record); + + // Deliver the combined datagram. Must not error. + client + .handle_packet(&combined) + .expect("multi-record datagram with bad first record should not error"); + + // The valid record should have been processed despite the bad first record. + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.app_data.iter().any(|d| d.as_slice() == b"hello"), + "Client should receive the valid app data record that followed the bogus record" + ); +} + +/// Regression test for bug #3: single replay window across epochs. +/// +/// Before the fix, a single `ReplayWindow` tracked all epochs. When a +/// new-epoch record arrived (after KeyUpdate), the window advanced and +/// permanently rejected all old-epoch records — even though old receive +/// keys were still retained. This test verifies that a delayed old-epoch +/// packet IS accepted and delivered as application data after a KeyUpdate. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_old_epoch_record_accepted_after_key_update() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Low limit to trigger KeyUpdate quickly. + let config = Arc::new( + Config::builder() + .aead_encryption_limit(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Send one message and capture its packet WITHOUT delivering to server. + // This packet is encrypted on the initial application epoch (epoch 3). + client + .send_application_data(b"old-epoch-data") + .expect("send delayed msg"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + let delayed_packets = client_out.packets.clone(); + + // Process server output (don't deliver delayed to server). + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + // Send enough messages to trigger at least one KeyUpdate (limit=5). + let mut server_received = 0; + for i in 0..12 { + let msg = format!("msg-{}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + server_received += server_out.app_data.len(); + } + } + + assert_eq!( + server_received, 12, + "All regular messages should be received" + ); + + // NOW deliver the old-epoch packet. With per-epoch replay windows, + // the epoch-3 window hasn't seen this sequence number, so it must be + // accepted and decrypted using the retained old-epoch keys. + deliver_packets(&delayed_packets, &mut server); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"old-epoch-data"), + "Server must receive the delayed old-epoch packet (per-epoch replay windows)" + ); +} + +/// Test that the ClientHello is padded to fill the configured MTU. +/// +/// RFC 7685 defines the padding extension (type 0x0015) to increase +/// the ClientHello size, reducing the server-to-client amplification +/// factor in DTLS. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_client_hello_padded_to_mtu() { + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let mtu = 1150; // default MTU + + let config = dtls13_config(); + + let now = Instant::now(); + let mut client = Dtls::new_13(config, client_cert, now); + client.set_active(true); + + client.handle_timeout(now).expect("client timeout"); + let out = drain_outputs(&mut client); + assert!(!out.packets.is_empty(), "Client should send ClientHello"); + + let ch_packet = &out.packets[0]; + + // The ClientHello record should fill the MTU exactly. + assert_eq!( + ch_packet.len(), + mtu, + "ClientHello packet should be padded to MTU ({} bytes), got {} bytes", + mtu, + ch_packet.len() + ); + + // Verify the padding extension (type 0x0015) is present. + let padding_type: [u8; 2] = [0x00, 0x15]; + let has_padding = ch_packet.windows(2).any(|w| w == padding_type); + assert!( + has_padding, + "ClientHello should contain a padding extension (type 0x0015)" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_mixed_datagram_during_handshake_bogus_first() { + //! Test that during handshake, a mixed datagram with bogus plaintext + //! ApplicationData first and valid handshake record second is handled + //! correctly: bogus is discarded, valid handshake proceeds. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Client sends ClientHello. + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "Should have ClientHello"); + let client_hello = &client_out.packets[0]; + + // Craft bogus plaintext ApplicationData. + let bogus = vec![ + 0x17, // content_type: ApplicationData + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (plaintext) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, // sequence_number + 0x00, 0x05, // length: 5 + 0x62, 0x6F, 0x67, 0x75, 0x73, // "bogus" + ]; + + // Build mixed datagram: bogus first, then ClientHello. + let mut mixed = bogus; + mixed.extend_from_slice(client_hello); + + // Deliver mixed datagram to server. + server + .handle_packet(&mixed) + .expect("mixed datagram should not error"); + + // Server should process the ClientHello despite the bogus record. + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "Server should send ServerHello flight despite bogus record" + ); + + // Continue handshake normally. + deliver_packets(&server_out.packets, &mut client); + complete_dtls13_handshake(&mut client, &mut server, now); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_mixed_datagram_plaintext_first_then_valid() { + //! Post-handshake: a UDP datagram with bogus plaintext ApplicationData FIRST + //! followed by a valid encrypted record is handled correctly: the bogus + //! record is silently discarded and the valid one is still processed. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Send valid application data from client and capture the encrypted packet. + client + .send_application_data(b"valid-data") + .expect("send valid data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "Should have valid packet"); + let valid_packet = &client_out.packets[0]; + + // Craft a plaintext ApplicationData record (epoch 0). + let bogus_record = vec![ + 0x17, // content_type: ApplicationData + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (plaintext) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, // sequence_number + 0x00, 0x06, // length: 6 + 0x62, 0x6F, 0x67, 0x75, 0x73, 0x21, // "bogus!" + ]; + + // Construct a mixed datagram: bogus plaintext record FIRST, then valid record. + let mut mixed_datagram = bogus_record; + mixed_datagram.extend_from_slice(valid_packet); + + // Deliver the mixed datagram to server. + server + .handle_packet(&mixed_datagram) + .expect("mixed datagram should not error"); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + // The valid record should still be processed despite the bogus first record. + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"valid-data"), + "Server should receive the valid encrypted ApplicationData even when bogus record comes first" + ); + + // The bogus plaintext record should NOT produce any output. + assert_eq!( + server_out.app_data.len(), + 1, + "Should receive exactly 1 app data (the valid one), not the bogus plaintext" + ); + assert!( + !server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"bogus!"), + "Bogus plaintext ApplicationData must not be delivered" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_mixed_datagram_valid_first_then_bogus() { + //! Post-handshake: a UDP datagram with a valid encrypted record FIRST + //! followed by bogus plaintext ApplicationData is handled correctly: the + //! valid record is processed and the trailing bogus record is discarded. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Send valid application data from client and capture the encrypted packet. + client + .send_application_data(b"valid-data") + .expect("send valid data"); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "Should have valid packet"); + let valid_packet = &client_out.packets[0]; + + // Craft a plaintext ApplicationData record (epoch 0). + let bogus_record = vec![ + 0x17, // content_type: ApplicationData + 0xFE, 0xFD, // version: DTLS 1.2 + 0x00, 0x00, // epoch: 0 (plaintext) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, // sequence_number + 0x00, 0x06, // length: 6 + 0x62, 0x6F, 0x67, 0x75, 0x73, 0x21, // "bogus!" + ]; + + // Construct a mixed datagram: valid record FIRST, then bogus plaintext. + let mut mixed_datagram = valid_packet.clone(); + mixed_datagram.extend_from_slice(&bogus_record); + + // Deliver the mixed datagram to server. + server + .handle_packet(&mixed_datagram) + .expect("mixed datagram should not error"); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + + // The valid record should be processed. + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"valid-data"), + "Server should receive the valid encrypted ApplicationData even when bogus record follows" + ); + + // The bogus trailing record should NOT produce any output. + assert_eq!( + server_out.app_data.len(), + 1, + "Should receive exactly 1 app data (the valid one), not the bogus plaintext" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_half_close_send_then_close() { + //! After receiving close_notify, the write half remains open per RFC 8446 §6.1. + //! The local side can send application data (half-close), and the data must + //! be delivered to the peer. Then close() shuts down the write half. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + // Client sends close_notify + client.close().unwrap(); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!(server_out.close_notify, "Server should emit CloseNotify"); + + // Half-close: server can still send after receiving close_notify + server + .send_application_data(b"half-close-data") + .expect("send after close_notify should work"); + + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + // Client receives the data sent during half-close + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out + .app_data + .iter() + .any(|d| d.as_slice() == b"half-close-data"), + "Client should receive data sent during half-close" + ); + + // Server closes its write half + server.close().unwrap(); + + // After local close(), sends must fail + assert!( + server.send_application_data(b"after-own-close").is_err(), + "Server should not accept sends after its own close()" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_close_during_handshake_emits_no_packets() { + //! Call close() on the client while the handshake is in progress. + //! Per `Dtls::close` API contract, close() during handshake silently + //! discards state without sending any packets. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Start handshake — client sends ClientHello + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + !client_out.packets.is_empty(), + "Client should emit ClientHello" + ); + + // Deliver to server, server responds + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + let _server_out = drain_outputs(&mut server); + + // Now abort the client mid-handshake + client.close().unwrap(); + + // After close(), polling must not emit any more packets (library policy, not RFC mandate). + let client_out = drain_outputs(&mut client); + assert!( + client_out.packets.is_empty(), + "Client should not emit packets after close() during handshake" + ); + + // Even after a timeout, no packets should appear. + let later = now + Duration::from_secs(5); + let _ = client.handle_timeout(later); + let client_out = drain_outputs(&mut client); + assert!( + client_out.packets.is_empty(), + "Client should not emit packets after timeout post-close()" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_app_data_delivered_before_close_notify() { + //! When app data and close_notify arrive in the same batch, the app data + //! must be delivered before CloseNotify. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + // Send app data then immediately close (both queued) + client + .send_application_data(b"before-close") + .expect("send app data"); + client.close().unwrap(); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + deliver_packets(&client_out.packets, &mut server); + + // Poll server outputs and verify ordering: ApplicationData before CloseNotify + server.handle_timeout(now).expect("server timeout"); + let mut saw_app_data = false; + let mut saw_close_notify = false; + let mut close_after_data = false; + let mut buf = vec![0u8; 2048]; + loop { + match server.poll_output(&mut buf) { + Output::ApplicationData(data) => { + assert!( + !saw_close_notify, + "ApplicationData must not appear after CloseNotify" + ); + if data == b"before-close" { + saw_app_data = true; + } + } + Output::CloseNotify => { + saw_close_notify = true; + if saw_app_data { + close_after_data = true; + } + } + Output::Timeout(_) => break, + _ => {} + } + } + assert!(saw_app_data, "Server should receive the app data"); + assert!(saw_close_notify, "Server should see CloseNotify"); + assert!( + close_after_data, + "CloseNotify must come after ApplicationData" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_close_notify_out_of_order_app_data_accepted() { + //! Out-of-order app data packets (sequence < close_notify sequence) that + //! arrive after close_notify must still be accepted and delivered. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + // Server sends app data (seq N), then closes (close_notify at seq N+1) + server + .send_application_data(b"before-close-data") + .expect("send app data"); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let app_data_packets = drain_outputs(&mut server).packets; + + server.close().unwrap(); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let close_packets = drain_outputs(&mut server).packets; + + // Deliver close_notify FIRST (out of order), then app data + deliver_packets(&close_packets, &mut client); + deliver_packets(&app_data_packets, &mut client); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + // Client should still deliver the app data (its sequence < close_notify sequence) + assert!( + client_out + .app_data + .iter() + .any(|d| d.as_slice() == b"before-close-data"), + "Out-of-order app data with earlier sequence should be accepted" + ); + + // Client should also see CloseNotify + assert!(client_out.close_notify, "Client should emit CloseNotify"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_half_closed_local_no_retransmit() { + //! After close(), in-flight retransmissions (e.g. a pending KeyUpdate + //! awaiting ACK) must be cancelled. Advancing time past retransmit + //! timeouts should produce no packets. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Low AEAD limit so we can trigger a KeyUpdate after a few app-data records. + let config = Arc::new( + Config::builder() + .aead_encryption_limit(3) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Send enough app data from client to trigger needs_key_update. + // aead_encryption_limit(3) → threshold is 3 (quarter=0, no jitter). + for i in 0..3 { + client + .send_application_data(format!("msg{}", i).as_bytes()) + .expect("send app data"); + } + + // handle_timeout → make_progress → creates KeyUpdate, arms flight timer. + // This puts KeyUpdate records into flight_saved_records for retransmission. + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + // Deliver app data to server but NOT the KeyUpdate ACK back to client, + // so the client has an in-flight KeyUpdate awaiting acknowledgement. + deliver_packets(&client_out.packets, &mut server); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + // Intentionally do NOT deliver server's ACK/response back to client. + let _ = drain_outputs(&mut server); + + // Now close() — should cancel the in-flight KeyUpdate retransmission. + client.close().unwrap(); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + // Drain the close_notify packet + let _ = drain_outputs(&mut client); + + // Advance time well past flight retransmit timeouts — should emit no packets. + for _ in 0..5 { + now += Duration::from_secs(5); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.packets.is_empty(), + "No retransmission packets should be emitted after close()" + ); + } + + // send_application_data must fail + let result = client.send_application_data(b"should-fail"); + assert!( + result.is_err(), + "send_application_data should fail in HalfClosedLocal" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_half_closed_local_transitions_to_closed() { + //! After client calls close() (HalfClosedLocal), receiving the peer's + //! close_notify should transition to Closed and emit CloseNotify. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + assert!(!client.is_closing()); + assert!(!client.is_closed()); + assert!(!server.is_closing()); + assert!(!server.is_closed()); + + // Client calls close() → HalfClosedLocal + client.close().unwrap(); + assert!(client.is_closing()); + assert!(!client.is_closed()); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(client.is_closing()); + assert!(!client.is_closed()); + + // Deliver client's close_notify to server + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + assert!(server.is_closing()); + assert!(!server.is_closed()); + + let server_out = drain_outputs(&mut server); + assert!(server_out.close_notify, "Server should see CloseNotify"); + assert!(!server.is_closing()); + assert!(!server.is_closed()); + + // Server calls close() → sends its own close_notify + server.close().unwrap(); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + assert!(server.is_closing()); + assert!(!server.is_closed()); + + let server_out = drain_outputs(&mut server); + assert!(!server.is_closing()); + assert!(server.is_closed()); + + // Deliver server's close_notify to client + deliver_packets(&server_out.packets, &mut client); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + assert!(client.is_closing()); + assert!(!client.is_closed()); + + let client_out = drain_outputs(&mut client); + + // Client should emit CloseNotify (peer's close_notify received) + assert!( + client_out.close_notify, + "Client should emit CloseNotify after receiving peer's close_notify" + ); + assert!(!client.is_closing()); + assert!(client.is_closed()); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_close_state_matrix() { + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + assert!(!client.is_closing()); + assert!(!client.is_closed()); + assert!(!server.is_closing()); + assert!(!server.is_closed()); + + client.close().unwrap(); + assert!(client.is_closing(), "local close pending"); + assert!(!client.is_closed(), "local close not terminal"); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "local close_notify packet"); + assert!( + client.is_closing(), + "local close remains pending until peer close_notify" + ); + assert!(!client.is_closed(), "local half-close is not terminal"); + + deliver_packets(&client_out.packets, &mut server); + server.handle_timeout(now).expect("server timeout"); + assert!(server.is_closing(), "remote close pending"); + assert!(!server.is_closed(), "remote close not drained"); + + let server_out = drain_outputs(&mut server); + assert!(server_out.close_notify, "remote CloseNotify event"); + assert!(!server.is_closing(), "remote close event drained"); + assert!( + !server.is_closed(), + "remote half-close leaves write side open" + ); + + server.close().unwrap(); + now += Duration::from_millis(10); + server + .handle_timeout(now) + .expect("server timeout after close"); + assert!(server.is_closing(), "remote reciprocal close pending"); + assert!(!server.is_closed(), "remote reciprocal close not drained"); + + let server_out = drain_outputs(&mut server); + assert!( + !server_out.packets.is_empty(), + "remote reciprocal close_notify packet" + ); + assert!(!server.is_closing(), "remote reciprocal close drained"); + assert!(server.is_closed(), "remote close terminal"); + + deliver_packets(&server_out.packets, &mut client); + now += Duration::from_millis(10); + client + .handle_timeout(now) + .expect("client timeout after reciprocal"); + assert!(client.is_closing(), "local close peer response pending"); + assert!(!client.is_closed(), "local close peer response not drained"); + + let client_out = drain_outputs(&mut client); + assert!(client_out.close_notify, "local CloseNotify event"); + assert!(!client.is_closing(), "local close drained"); + assert!(client.is_closed(), "local close terminal"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_close_prohibits_further_sends() { + //! After close(), the sender enters HalfClosedLocal and + //! send_application_data() must return an error. + //! + //! Note: the receiver-side sequence-threshold discard (RFC 9147 §5.10) is + //! exercised by `dtls13_close_notify_out_of_order_app_data_accepted` (accept + //! path). The discard path (seq > close_notify seq) cannot be tested at the + //! integration level because DTLS 1.3 records are AEAD-encrypted and + //! close_notify is always the highest-sequence record from a given sender. + + let _ = env_logger::try_init(); + let mut now = Instant::now(); + let (mut client, mut server, now_hs) = setup_connected_13_pair(now); + now = now_hs; + + // Server sends close_notify + server.close().unwrap(); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let close_packets = drain_outputs(&mut server).packets; + + // Deliver close_notify to client + deliver_packets(&close_packets, &mut client); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(client_out.close_notify, "Client should see CloseNotify"); + + // Now try to send application data from server (after close_notify) + // This should fail because server is in HalfClosedLocal + let result = server.send_application_data(b"after-close"); + assert!( + result.is_err(), + "send_application_data should fail after close()" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_half_closed_local_no_ack() { + //! Per RFC 9147 §5.10 / RFC 8446 §6.1, after sending close_notify, no + //! further messages (including ACKs) should be sent. This test verifies + //! that in HalfClosedLocal state, the implementation does not send ACKs. + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use low AEAD limit to trigger automatic KeyUpdate + let config = Arc::new( + Config::builder() + .aead_encryption_limit(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + now = complete_dtls13_handshake(&mut client, &mut server, now); + + // Client calls close() → HalfClosedLocal + client.close().unwrap(); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let close_packets = drain_outputs(&mut client).packets; + + // Send 5 messages to trigger needs_key_update (limit=5, threshold 4..=5). + for i in 0..5 { + server + .send_application_data(format!("msg{}", i).as_bytes()) + .expect("send app data"); + } + + // handle_timeout → make_progress → creates KeyUpdate, rotates send keys + // to a new epoch. The KeyUpdate handshake record is saved for retransmission. + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + + // Batch 1: 5 app-data records + KeyUpdate (all on old epoch). + let batch1 = drain_outputs(&mut server).packets; + + // Send one more message on the NEW epoch (post-KeyUpdate). + // The client must process the KeyUpdate to install recv keys for this epoch; + // otherwise decryption fails and app_data count will be < 6. + server + .send_application_data(b"msg5") + .expect("send app data on new epoch"); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + + // Batch 2: 1 app-data record on new epoch. + let batch2 = drain_outputs(&mut server).packets; + + // Deliver close_notify to server + deliver_packets(&close_packets, &mut server); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let _ = drain_outputs(&mut server); + + // Deliver batch 1 (includes KeyUpdate) to client. + // Client is in HalfClosedLocal — it should process the KeyUpdate + // (install recv keys for the new epoch) but NOT send ACK. + deliver_packets(&batch1, &mut client); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out1 = drain_outputs(&mut client); + + assert!( + client_out1.packets.is_empty(), + "Client in HalfClosedLocal should not send ACK for KeyUpdate" + ); + + // Deliver batch 2 (new-epoch app data) to client. + // This will only succeed if KeyUpdate was actually processed above. + deliver_packets(&batch2, &mut client); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out2 = drain_outputs(&mut client); + + let total = client_out1.app_data.len() + client_out2.app_data.len(); + assert_eq!( + total, 6, + "Client must receive all 6 messages (6th on new epoch proves KeyUpdate was processed)" + ); + assert!( + client_out2.packets.is_empty(), + "Client in HalfClosedLocal should not send any packets" + ); +} diff --git a/third_party/dimpl/tests/dtls13/fragmentation.rs b/third_party/dimpl/tests/dtls13/fragmentation.rs new file mode 100644 index 0000000..a83868d --- /dev/null +++ b/third_party/dimpl/tests/dtls13/fragmentation.rs @@ -0,0 +1,515 @@ +//! DTLS 1.3 fragmentation tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls}; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_with_small_mtu() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use small MTU to force fragmentation + let config = dtls13_config_with_mtu(200); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut max_packet_size = 0usize; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Track max packet size + for p in &client_out.packets { + if p.len() > max_packet_size { + max_packet_size = p.len(); + } + } + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect with small MTU"); + assert!(server_connected, "Server should connect with small MTU"); + assert!( + max_packet_size <= 200, + "Packets should respect MTU: max was {}", + max_packet_size + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_large_application_data_fragmented() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Small MTU + let config = dtls13_config_with_mtu(300); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // First complete handshake + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_out.connected && server_out.connected { + break; + } + + now += Duration::from_millis(10); + } + + // Send large data (larger than MTU) + let large_data = vec![0xABu8; 1000]; + client + .send_application_data(&large_data) + .expect("client send large data"); + + let mut server_received: Vec = Vec::new(); + let mut _packet_count = 0; + + for _ in 0..20 { + let client_out = drain_outputs(&mut client); + _packet_count += client_out.packets.len(); + deliver_packets(&client_out.packets, &mut server); + + let server_out = drain_outputs(&mut server); + for data in server_out.app_data { + server_received.extend_from_slice(&data); + } + + if server_received.len() >= large_data.len() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!( + server_received, large_data, + "Large data should be received correctly" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_fragmentation_during_hrr() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Small MTU to force fragmentation during HRR handshake + let config = dtls13_config_with_mtu(200); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut max_packet_size = 0usize; + let mut saw_hrr = false; + let mut flight_count = 0; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if !client_out.packets.is_empty() { + flight_count += 1; + } + + // Track if we see what looks like HRR response (server sends before full handshake) + if !server_out.packets.is_empty() && !client_connected && flight_count <= 2 { + saw_hrr = true; + } + + // Track max packet size + for p in &client_out.packets { + if p.len() > max_packet_size { + max_packet_size = p.len(); + } + } + for p in &server_out.packets { + if p.len() > max_packet_size { + max_packet_size = p.len(); + } + } + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect with HRR and small MTU" + ); + assert!( + server_connected, + "Server should connect with HRR and small MTU" + ); + assert!( + max_packet_size <= 200, + "Packets should respect MTU: max was {}", + max_packet_size + ); + assert!( + saw_hrr || flight_count >= 2, + "Should have seen HRR or multiple client flights" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_fragmented_handshake_with_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Small MTU to force fragmentation, extra retries and longer handshake timeout + // to survive loss and retransmission delays + let config = Arc::new( + Config::builder() + .mtu(200) + .flight_retries(8) + .handshake_timeout(Duration::from_secs(120)) + .build() + .expect("Failed to build DTLS 1.3 config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut dropped_client = 0; + let mut dropped_server = 0; + + // Track the packet count of the last flight from each side. + // When the count changes, it's a new flight (different protocol step). + // We drop the first packet only on the first transmission of each new flight; + // retransmissions (same packet count) are delivered in full. + let mut prev_client_count = 0usize; + let mut client_drop_armed = false; + let mut prev_server_count = 0usize; + let mut server_drop_armed = false; + + for i in 0..120 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Detect new flight from client: packet count changed from previous + if !client_out.packets.is_empty() && client_out.packets.len() != prev_client_count { + client_drop_armed = true; + prev_client_count = client_out.packets.len(); + } + + // Deliver client packets, dropping the first of each new flight + if !client_out.packets.is_empty() && client_drop_armed && client_out.packets.len() > 1 { + client_drop_armed = false; + dropped_client += 1; + for p in &client_out.packets[1..] { + let _ = server.handle_packet(p); + } + } else { + deliver_packets(&client_out.packets, &mut server); + } + + // Detect new flight from server: packet count changed from previous + if !server_out.packets.is_empty() && server_out.packets.len() != prev_server_count { + server_drop_armed = true; + prev_server_count = server_out.packets.len(); + } + + // Deliver server packets, dropping the first of each new flight + if !server_out.packets.is_empty() && server_drop_armed && server_out.packets.len() > 1 { + server_drop_armed = false; + dropped_server += 1; + for p in &server_out.packets[1..] { + let _ = client.handle_packet(p); + } + } else { + deliver_packets(&server_out.packets, &mut client); + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite fragmented packet loss" + ); + assert!( + server_connected, + "Server should connect despite fragmented packet loss" + ); + assert!( + dropped_client > 0, + "Should have dropped at least one client packet" + ); + assert!( + dropped_server > 0, + "Should have dropped at least one server packet" + ); +} + +/// Issue 1: Overlapping handshake fragments must be reassembled successfully. +/// +/// RFC 9147 allows overlapping handshake fragments. The reassembly logic must +/// tolerate overlaps (e.g., [0..100] then [50..200]) and still consider the +/// message complete once all bytes are covered. +/// +/// This test captures a fragmented ClientHello, modifies the second fragment +/// to create a 10-byte overlap, and verifies the server completes the handshake. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_overlapping_fragments_reassembled_successfully() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Small MTU forces ClientHello into multiple fragments while keeping + // the server's response flight within the flight_saved_records capacity. + let config = dtls13_config_with_mtu(150); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Get the client's first flight (fragmented ClientHello) + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + // Find handshake fragments: DTLSPlaintext records with content_type 0x16 + // and epoch 0 (bytes 3-4 == 0x00 0x00). + let handshake_packets: Vec = client_out + .packets + .iter() + .enumerate() + .filter(|(_, p)| p.len() > 25 && p[0] == 0x16 && p[3] == 0x00 && p[4] == 0x00) + .map(|(i, _)| i) + .collect(); + + assert!( + handshake_packets.len() >= 2, + "ClientHello should be fragmented into at least 2 packets, got {}", + handshake_packets.len() + ); + + // Create modified packets with overlapping second fragment. + // + // DTLSPlaintext layout: + // Bytes 0: content_type (0x16 = handshake) + // Bytes 1-2: version + // Bytes 3-4: epoch + // Bytes 5-10: sequence_number (6 bytes) + // Bytes 11-12: record length + // Bytes 13: msg_type (handshake header) + // Bytes 14-16: total message length (3 bytes) + // Bytes 17-18: message_seq (2 bytes) + // Bytes 19-21: fragment_offset (3 bytes, big-endian u24) + // Bytes 22-24: fragment_length (3 bytes, big-endian u24) + // Bytes 25+: body + let mut modified_packets = client_out.packets.clone(); + let first_idx = handshake_packets[0]; + let second_idx = handshake_packets[1]; + + // Get overlap data from the end of the first fragment's body + let first_frag_len = { + let p = &modified_packets[first_idx]; + ((p[22] as usize) << 16) | ((p[23] as usize) << 8) | (p[24] as usize) + }; + let overlap_data: Vec = { + let p = &modified_packets[first_idx]; + let body_end = 25 + first_frag_len; + p[body_end - 10..body_end].to_vec() + }; + + // Build a new second packet with the overlap data prepended to its body. + // This shifts fragment_offset back by 10, increases fragment_length by 10, + // and updates the record length accordingly. + let new_packet = { + let packet = &modified_packets[second_idx]; + let orig_offset = + ((packet[19] as u32) << 16) | ((packet[20] as u32) << 8) | (packet[21] as u32); + assert!( + orig_offset >= 10, + "Second fragment offset should be >= 10 for overlap test, got {}", + orig_offset + ); + let orig_frag_len = + ((packet[22] as u32) << 16) | ((packet[23] as u32) << 8) | (packet[24] as u32); + let orig_record_len = u16::from_be_bytes([packet[11], packet[12]]); + + let new_offset = orig_offset - 10; + let new_frag_len = orig_frag_len + 10; + let new_record_len = orig_record_len + 10; + + let mut p = Vec::with_capacity(packet.len() + 10); + // Record header through message_seq (bytes 0-18) + p.extend_from_slice(&packet[..19]); + // fragment_offset (3 bytes) + p.push((new_offset >> 16) as u8); + p.push((new_offset >> 8) as u8); + p.push(new_offset as u8); + // fragment_length (3 bytes) + p.push((new_frag_len >> 16) as u8); + p.push((new_frag_len >> 8) as u8); + p.push(new_frag_len as u8); + // Overlap bytes + original body + p.extend_from_slice(&overlap_data); + p.extend_from_slice(&packet[25..]); + // Fix record length (bytes 11-12) + p[11] = (new_record_len >> 8) as u8; + p[12] = new_record_len as u8; + p + }; + modified_packets[second_idx] = new_packet; + + // Deliver overlapping fragments to server + deliver_packets(&modified_packets, &mut server); + + // Drive the handshake to completion. The server must reassemble the + // overlapping fragments and complete the handshake with the client. + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..40 { + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + match server.handle_timeout(now) { + Ok(()) => {} + Err(e) => panic!("Server should not error with overlapping fragments: {}", e), + } + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + } + + assert!( + server_connected, + "Server should reassemble overlapping fragments and complete the handshake" + ); +} diff --git a/third_party/dimpl/tests/dtls13/handshake.rs b/third_party/dimpl/tests/dtls13/handshake.rs new file mode 100644 index 0000000..1799bf7 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/handshake.rs @@ -0,0 +1,1399 @@ +//! DTLS 1.3 handshake tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Dtls, SrtpProfile}; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_basic_handshake() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Run handshake + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected"); + assert!(server_connected, "Server should be connected"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_with_keying_material() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + let mut server_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + if let Some(km) = server_out.keying_material { + server_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() && server_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let client_km = client_km.expect("Client should have keying material"); + let server_km = server_km.expect("Server should have keying material"); + + // Both sides should derive the same keying material + assert_eq!( + client_km.0, server_km.0, + "Client and server keying material should match" + ); + assert_eq!( + client_km.1, server_km.1, + "Client and server SRTP profile should match" + ); + + // Keying material should be non-empty and properly sized + // SRTP keying material is typically 2*(key_len + salt_len) for both directions + assert!( + !client_km.0.is_empty(), + "Keying material should not be empty" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_peer_certificate_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Store expected certificates + let expected_client_cert = client_cert.certificate.clone(); + let expected_server_cert = server_cert.certificate.clone(); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_peer_cert: Option> = None; + let mut server_peer_cert: Option> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(cert) = client_out.peer_cert { + client_peer_cert = Some(cert); + } + if let Some(cert) = server_out.peer_cert { + server_peer_cert = Some(cert); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_peer_cert.is_some() && server_peer_cert.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_peer_cert.is_some(), + "Client should receive server's certificate" + ); + assert!( + server_peer_cert.is_some(), + "Server should receive client's certificate" + ); + + // Verify the certificates match what was configured + assert_eq!( + client_peer_cert.unwrap(), + expected_server_cert, + "Client should receive server's certificate" + ); + assert_eq!( + server_peer_cert.unwrap(), + expected_client_cert, + "Server should receive client's certificate" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_srtp_keying_material_correct_size() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_km: Option<(Vec, SrtpProfile)> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if let Some(km) = client_out.keying_material { + client_km = Some(km); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_km.is_some() { + break; + } + + now += Duration::from_millis(10); + } + + let (km, profile) = client_km.expect("Should have keying material"); + + // Verify keying material size based on profile + let expected_size = match profile { + SrtpProfile::AEAD_AES_128_GCM => 2 * (16 + 12), // 2 * (key + salt) for AES-128-GCM + SrtpProfile::AEAD_AES_256_GCM => 2 * (32 + 12), // 2 * (key + salt) for AES-256-GCM + SrtpProfile::AES128_CM_SHA1_80 => 2 * (16 + 14), // 2 * (key + salt) for AES-128-CM + _ => unreachable!(), + }; + + assert_eq!( + km.len(), + expected_size, + "Keying material should be {} bytes for {:?}, got {}", + expected_size, + profile, + km.len() + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_hello_retry_request_flow() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Server config that will trigger HRR (by requiring cookie) + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut saw_hrr = false; + let mut flight_count = 0; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if !client_out.packets.is_empty() { + flight_count += 1; + } + + // Track if we see what looks like HRR response (server sends before full handshake) + if !server_out.packets.is_empty() && !client_connected && flight_count <= 2 { + saw_hrr = true; + } + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should be connected after HRR"); + assert!(server_connected, "Server should be connected after HRR"); + // In DTLS 1.3 with cookies, we expect HelloRetryRequest + assert!( + saw_hrr || flight_count >= 2, + "Should have seen HRR or multiple client flights" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_aes_256_gcm() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::Dtls13CipherSuite; + use dimpl::crypto::aws_lc_rs; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Build a custom provider that only offers AES_256_GCM_SHA384 + let default = aws_lc_rs::default_provider(); + let aes256_only: Vec<_> = default + .dtls13_cipher_suites + .iter() + .copied() + .filter(|cs| cs.suite() == Dtls13CipherSuite::AES_256_GCM_SHA384) + .collect(); + assert!(!aes256_only.is_empty(), "Provider must have AES-256-GCM"); + + // Leak the filtered vec to get a &'static slice + let aes256_static: &'static [_] = Box::leak(aes256_only.into_boxed_slice()); + + let provider = dimpl::crypto::CryptoProvider { + dtls13_cipher_suites: aes256_static, + ..default + }; + + let config = Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with AES-256-GCM" + ); + assert!( + server_connected, + "Server should be connected with AES-256-GCM" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_chacha20_poly1305() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::Dtls13CipherSuite; + use dimpl::crypto::aws_lc_rs; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let default = aws_lc_rs::default_provider(); + let chacha_only: Vec<_> = default + .dtls13_cipher_suites + .iter() + .copied() + .filter(|cs| cs.suite() == Dtls13CipherSuite::CHACHA20_POLY1305_SHA256) + .collect(); + assert!( + !chacha_only.is_empty(), + "Provider must have CHACHA20_POLY1305" + ); + + let chacha_static: &'static [_] = Box::leak(chacha_only.into_boxed_slice()); + + let provider = dimpl::crypto::CryptoProvider { + dtls13_cipher_suites: chacha_static, + ..default + }; + + let config = Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with CHACHA20-POLY1305" + ); + assert!( + server_connected, + "Server should be connected with CHACHA20-POLY1305" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_secp256r1_key_exchange() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::NamedGroup; + use dimpl::crypto::aws_lc_rs; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Build a custom provider where the client only offers P-256 + let default = aws_lc_rs::default_provider(); + let p256_only: Vec<_> = default + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == NamedGroup::Secp256r1) + .collect(); + assert!(!p256_only.is_empty(), "Provider must have P-256"); + + let p256_static: &'static [_] = Box::leak(p256_only.into_boxed_slice()); + + let client_provider = dimpl::crypto::CryptoProvider { + kx_groups: p256_static, + ..default.clone() + }; + + let client_config = Arc::new( + Config::builder() + .with_crypto_provider(client_provider) + .build() + .expect("build client config"), + ); + + // Server uses default provider (supports both P-256 and P-384) + let server_config = Arc::new( + Config::builder() + .with_crypto_provider(default) + .build() + .expect("build server config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(server_config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with P-256 key exchange" + ); + assert!( + server_connected, + "Server should be connected with P-256 key exchange" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_x25519_key_exchange() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::NamedGroup; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use config filter to select only X25519 and disable DTLS 1.2 + // to keep this test focused on DTLS 1.3 behavior. + let config = Arc::new( + Config::builder() + .kx_groups(&[NamedGroup::X25519]) + .dtls12_cipher_suites(&[]) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with X25519 key exchange" + ); + assert!( + server_connected, + "Server should be connected with X25519 key exchange" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_client_certificate_auth() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let expected_client_cert = client_cert.certificate.clone(); + + // Explicitly require client certificate + let config = Arc::new( + Config::builder() + .require_client_certificate(true) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + let mut server_peer_cert: Option> = None; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + if let Some(cert) = server_out.peer_cert { + server_peer_cert = Some(cert); + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with client cert auth" + ); + assert!( + server_connected, + "Server should be connected with client cert auth" + ); + assert!( + server_peer_cert.is_some(), + "Server should have received client's certificate" + ); + assert_eq!( + server_peer_cert.unwrap(), + expected_client_cert, + "Server should receive the correct client certificate" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_timeout_expires() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Short handshake timeout so the test runs quickly + let config = Arc::new( + Config::builder() + .handshake_timeout(Duration::from_secs(5)) + .flight_start_rto(Duration::from_millis(500)) + .flight_retries(2) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut _server = Dtls::new_13(config, server_cert, now); + _server.set_active(false); + + let mut timed_out = false; + + // Never deliver any packets between client and server. + // Keep triggering timeouts until the handshake times out. + for _ in 0..100 { + match client.handle_timeout(now) { + Ok(()) => { + // Drain outputs to keep the state machine consistent + drain_outputs(&mut client); + } + Err(_) => { + timed_out = true; + break; + } + } + + now += Duration::from_secs(1); + } + + assert!( + timed_out, + "Client should eventually report a timeout error when no packets are delivered" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_hrr_with_p256_then_x25519() { + // Client offers P-256 key_share but server prefers X25519. Since the + // client's key_share does not match the server's preferred group, the + // server sends HelloRetryRequest asking the client to retry with X25519. + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::NamedGroup; + use dimpl::crypto::aws_lc_rs; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let default = aws_lc_rs::default_provider(); + + // Client: offers both groups but P-256 is first (sends P-256 key_share) + let client_groups: Vec<_> = default + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == NamedGroup::Secp256r1 || g.name() == NamedGroup::X25519) + .collect(); + // Ensure P-256 is first + let mut client_groups_sorted: Vec<_> = client_groups; + client_groups_sorted.sort_by_key(|g| { + if g.name() == NamedGroup::Secp256r1 { + 0 + } else { + 1 + } + }); + let client_groups_static: &'static [_] = Box::leak(client_groups_sorted.into_boxed_slice()); + + let client_provider = dimpl::crypto::CryptoProvider { + kx_groups: client_groups_static, + ..default.clone() + }; + + // Server: prefers X25519 (X25519 is first in kx_groups) + let server_groups: Vec<_> = default + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == NamedGroup::Secp256r1 || g.name() == NamedGroup::X25519) + .collect(); + let mut server_groups_sorted: Vec<_> = server_groups; + server_groups_sorted.sort_by_key(|g| if g.name() == NamedGroup::X25519 { 0 } else { 1 }); + let server_groups_static: &'static [_] = Box::leak(server_groups_sorted.into_boxed_slice()); + + let server_provider = dimpl::crypto::CryptoProvider { + kx_groups: server_groups_static, + ..default + }; + + let client_config = Arc::new( + Config::builder() + .with_crypto_provider(client_provider) + .build() + .expect("build client config"), + ); + + let server_config = Arc::new( + Config::builder() + .with_crypto_provider(server_provider) + .build() + .expect("build server config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(server_config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + let mut saw_hrr = false; + let mut flight_count = 0; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if !client_out.packets.is_empty() { + flight_count += 1; + } + + // HRR: server sends packets before full handshake completes, during + // the initial exchange (flight_count <= 2) + if !server_out.packets.is_empty() && !client_connected && flight_count <= 2 { + saw_hrr = true; + } + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected after HRR with group mismatch" + ); + assert!( + server_connected, + "Server should be connected after HRR with group mismatch" + ); + // The client sent P-256 key_share but server prefers X25519, so HRR should occur + assert!( + saw_hrr || flight_count >= 2, + "Should have seen HRR (server prefers X25519 but client offered P-256)" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_hrr_handshake_completes_after_packet_loss() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::NamedGroup; + use dimpl::crypto::aws_lc_rs; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let default = aws_lc_rs::default_provider(); + + // Client: P-256 first (sends P-256 key_share) + let client_groups: Vec<_> = default + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == NamedGroup::Secp256r1 || g.name() == NamedGroup::Secp384r1) + .collect(); + let mut client_groups_sorted: Vec<_> = client_groups; + client_groups_sorted.sort_by_key(|g| { + if g.name() == NamedGroup::Secp256r1 { + 0 + } else { + 1 + } + }); + let client_groups_static: &'static [_] = Box::leak(client_groups_sorted.into_boxed_slice()); + + let client_provider = dimpl::crypto::CryptoProvider { + kx_groups: client_groups_static, + ..default.clone() + }; + + // Server: P-384 first (triggers HRR when client offers P-256 key_share) + let server_groups: Vec<_> = default + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == NamedGroup::Secp256r1 || g.name() == NamedGroup::Secp384r1) + .collect(); + let mut server_groups_sorted: Vec<_> = server_groups; + server_groups_sorted.sort_by_key(|g| { + if g.name() == NamedGroup::Secp384r1 { + 0 + } else { + 1 + } + }); + let server_groups_static: &'static [_] = Box::leak(server_groups_sorted.into_boxed_slice()); + + let server_provider = dimpl::crypto::CryptoProvider { + kx_groups: server_groups_static, + ..default + }; + + let client_config = Arc::new( + Config::builder() + .with_crypto_provider(client_provider) + .flight_retries(8) + .build() + .expect("build client config"), + ); + + let server_config = Arc::new( + Config::builder() + .with_crypto_provider(server_provider) + .flight_retries(8) + .build() + .expect("build server config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(client_config, client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(server_config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Track flights to drop the first packet of each new flight + let mut last_client_flight_dropped = false; + let mut last_server_flight_dropped = false; + let mut prev_client_had_packets = false; + let mut prev_server_had_packets = false; + + for i in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Detect new flight from client: packets appear after a gap + let client_has_packets = !client_out.packets.is_empty(); + let is_new_client_flight = client_has_packets && !prev_client_had_packets; + prev_client_had_packets = client_has_packets; + + if is_new_client_flight && !last_client_flight_dropped { + // Drop the first packet of this flight, deliver the rest + last_client_flight_dropped = true; + for p in client_out.packets.iter().skip(1) { + let _ = server.handle_packet(p); + } + } else { + if client_has_packets { + // Reset for next flight detection + last_client_flight_dropped = false; + } + deliver_packets(&client_out.packets, &mut server); + } + + // Detect new flight from server + let server_has_packets = !server_out.packets.is_empty(); + let is_new_server_flight = server_has_packets && !prev_server_had_packets; + prev_server_had_packets = server_has_packets; + + if is_new_server_flight && !last_server_flight_dropped { + // Drop the first packet of this flight, deliver the rest + last_server_flight_dropped = true; + for p in server_out.packets.iter().skip(1) { + let _ = client.handle_packet(p); + } + } else { + if server_has_packets { + last_server_flight_dropped = false; + } + deliver_packets(&server_out.packets, &mut client); + } + + if client_connected && server_connected { + break; + } + + // Advance time to trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect after HRR despite packet loss" + ); + assert!( + server_connected, + "Server should connect after HRR despite packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_no_client_auth() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .require_client_certificate(false) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + + assert!( + client_connected, + "Client should connect without client auth" + ); + assert!( + server_connected, + "Server should connect without client auth" + ); + + // Verify data exchange works after handshake + client + .send_application_data(b"no-auth-ping") + .expect("send app data"); + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + assert!( + server_out + .app_data + .iter() + .any(|d| d.as_slice() == b"no-auth-ping"), + "Server should receive app data after no-client-auth handshake" + ); +} + +/// Verify the Finished flight is retransmitted on packet loss when client +/// auth is NOT requested (regression test for flight_begin fix). +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_no_client_auth_retransmit_finished() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .require_client_certificate(false) + .flight_retries(6) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut dropped_client_finished = false; + + for i in 0..80 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + // Drop the first client flight after the client reports Connected. + // This simulates loss of the client's Finished message. + if client_connected && !dropped_client_finished && !client_out.packets.is_empty() { + dropped_client_finished = true; + // Don't deliver — the Finished flight is lost. + } else { + deliver_packets(&client_out.packets, &mut server); + } + + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(50); + } + } + + assert!( + client_connected, + "Client should connect despite Finished loss" + ); + assert!( + server_connected, + "Server should connect via retransmitted Finished" + ); +} + +#[test] +#[cfg(all(feature = "rcgen", feature = "rust-crypto"))] +fn dtls13_handshake_chacha20_poly1305_rust_crypto() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::Dtls13CipherSuite; + use dimpl::crypto::rust_crypto; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let default = rust_crypto::default_provider(); + let chacha_only: Vec<_> = default + .dtls13_cipher_suites + .iter() + .copied() + .filter(|cs| cs.suite() == Dtls13CipherSuite::CHACHA20_POLY1305_SHA256) + .collect(); + assert!( + !chacha_only.is_empty(), + "rust_crypto provider must have CHACHA20_POLY1305" + ); + + let chacha_static: &'static [_] = Box::leak(chacha_only.into_boxed_slice()); + + let provider = dimpl::crypto::CryptoProvider { + dtls13_cipher_suites: chacha_static, + ..default + }; + + let config = Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with rust_crypto CHACHA20-POLY1305" + ); + assert!( + server_connected, + "Server should be connected with rust_crypto CHACHA20-POLY1305" + ); +} + +#[test] +#[cfg(all(feature = "rcgen", feature = "rust-crypto"))] +fn dtls13_handshake_x25519_rust_crypto() { + use dimpl::Config; + use dimpl::certificate::generate_self_signed_certificate; + use dimpl::crypto::NamedGroup; + use dimpl::crypto::rust_crypto; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let default = rust_crypto::default_provider(); + let x25519_only: Vec<_> = default + .kx_groups + .iter() + .copied() + .filter(|g| g.name() == NamedGroup::X25519) + .collect(); + assert!( + !x25519_only.is_empty(), + "rust_crypto provider must have X25519" + ); + + let x25519_static: &'static [_] = Box::leak(x25519_only.into_boxed_slice()); + + let provider = dimpl::crypto::CryptoProvider { + kx_groups: x25519_static, + ..default + }; + + let config = Arc::new( + Config::builder() + .with_crypto_provider(provider) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should be connected with rust_crypto X25519" + ); + assert!( + server_connected, + "Server should be connected with rust_crypto X25519" + ); +} diff --git a/third_party/dimpl/tests/dtls13/key_update.rs b/third_party/dimpl/tests/dtls13/key_update.rs new file mode 100644 index 0000000..d619f0f --- /dev/null +++ b/third_party/dimpl/tests/dtls13/key_update.rs @@ -0,0 +1,642 @@ +//! DTLS 1.3 key update tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls}; + +use crate::common::*; + +/// Test that KeyUpdate is triggered automatically when AEAD encryption limit is reached. +/// Uses a low limit so the test can observe multiple transparent KeyUpdates. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_key_update_on_aead_limit() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .aead_encryption_limit(10) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send 100 messages client→server. With limit=10, KeyUpdates must happen + // transparently for all messages to arrive. + let mut server_received = 0; + for i in 0..100 { + let msg = format!("Message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + server_received += server_out.app_data.len(); + } + } + + assert_eq!( + server_received, 100, + "All messages should be received (proves KeyUpdate worked transparently)" + ); +} + +/// Test that bidirectional traffic works with auto-KeyUpdate on both sides. +/// Sends 100 messages in each direction (client first, then server) to avoid +/// simultaneous KeyUpdate contention. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_key_update_bidirectional_after_limit() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .aead_encryption_limit(10) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + let mut server_received = 0; + let mut client_received = 0; + + // Phase 1: Send 100 messages client→server (triggers KeyUpdates on client) + for i in 0..100 { + let msg = format!("Client msg {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("client send"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + server_received += server_out.app_data.len(); + } + } + + // Phase 2: Send 100 messages server→client (triggers KeyUpdates on server) + for i in 0..100 { + let msg = format!("Server msg {}", i); + server + .send_application_data(msg.as_bytes()) + .expect("server send"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + client_received += client_out.app_data.len(); + } + } + + assert_eq!( + server_received, 100, + "Server should receive all messages (proves KeyUpdate worked for client→server)" + ); + assert_eq!( + client_received, 100, + "Client should receive all messages (proves KeyUpdate worked for server→client)" + ); +} + +/// Test that a reordered packet captured before a KeyUpdate is accepted when +/// delivered alongside other packets during the transition. The packet is from +/// the same epoch and arrives before any new-epoch records, so the replay +/// window accepts it and the retained old epoch keys decrypt it. +/// +/// This verifies that auto-KeyUpdate is transparent to application data, even +/// when packets arrive out of order during the key transition. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_key_update_old_epoch_packet_still_decrypted() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .aead_encryption_limit(10) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send the first message and capture its raw packets WITHOUT delivering. + // This packet is encrypted on epoch 3 (the initial application epoch). + client + .send_application_data(b"delayed-old-epoch") + .expect("send delayed msg"); + + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + let delayed_packets = client_out.packets.clone(); + + // Process server output (don't deliver delayed to server). + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + // Send enough messages to trigger at least one KeyUpdate (limit=10). + // The KeyUpdate fires transparently as part of the normal exchange. + // With the delayed packet withheld, the AEAD count starts from the + // delayed message (count=1) plus each additional message. + let mut server_received = 0; + for i in 0..15 { + let msg = format!("Message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + server_received += server_out.app_data.len(); + } + } + + assert_eq!( + server_received, 15, + "All regular messages should be received" + ); + + // Now deliver the delayed packet that was captured before the KeyUpdate. + // The server has completed one or more KeyUpdates by now. The old epoch + // keys (epoch 3) are retained in the app_recv_keys array (up to 4 entries). + // Each epoch has its own replay window, so the old-epoch packet is accepted + // and decrypted (the per-epoch window for epoch 3 hasn't seen this seqno). + // + // We verify the connection is still healthy after delivering the late + // packet by sending additional data. + deliver_packets(&delayed_packets, &mut server); + now += Duration::from_millis(10); + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + // Verify post-KeyUpdate data exchange still works. The stale old-epoch + // packet should not have disrupted the connection. + let mut post_received = 0; + for i in 0..10 { + let msg = format!("Post msg {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send post msg"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + post_received += server_out.app_data.len(); + } + } + + assert_eq!( + post_received, 10, + "All post-KeyUpdate messages should be received (stale packet didn't break connection)" + ); +} + +/// Test that multiple sequential KeyUpdates work correctly. With a very low +/// AEAD limit, sending many messages should trigger 3+ KeyUpdates in sequence, +/// and all messages must still be received. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_key_update_multiple_sequential() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // With limit=3, quarter=0, so threshold=3 exactly (no jitter). + // Each KeyUpdate cycle: ~3 app records before the next KeyUpdate triggers. + let config = Arc::new( + Config::builder() + .aead_encryption_limit(3) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send 30 messages. With limit=3, this should trigger at least 3 KeyUpdates + // (likely more, since ACKs and KeyUpdate records themselves also count as + // AEAD encryptions on the current epoch). + let mut server_received = 0; + for i in 0..30 { + let msg = format!("Message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + now += Duration::from_millis(10); + + for _ in 0..5 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + server_received += server_out.app_data.len(); + } + } + + assert_eq!( + server_received, 30, + "All 30 messages should be received across 3+ KeyUpdates" + ); +} + +/// Test that KeyUpdate completes correctly even when the KeyUpdate message +/// itself is lost and must be retransmitted via timeout. After recovery, +/// subsequent data exchange must work normally. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_key_update_with_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .aead_encryption_limit(5) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send enough messages to trigger KeyUpdate, but drop all packets from the + // round where the KeyUpdate fires, simulating network loss of the KeyUpdate. + let mut _server_received = 0; + let mut dropped_round = false; + for i in 0..10 { + let msg = format!("Message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + now += Duration::from_millis(10); + + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + + // Drop one round of client packets (simulating KeyUpdate loss). + // We drop round i==5 which should be around the time a KeyUpdate fires. + if i == 5 && !dropped_round { + dropped_round = true; + // Don't deliver client_out.packets to server — they are lost. + } else { + deliver_packets(&client_out.packets, &mut server); + } + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + _server_received += server_out.app_data.len(); + } + + // The dropped round means at least one message was lost. Now trigger a + // retransmission timeout so the KeyUpdate (and any lost data) is resent. + for _ in 0..10 { + trigger_timeout(&mut client, &mut now); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + _server_received += server_out.app_data.len(); + } + + // Continue sending more messages to prove the connection is healthy. + let mut post_recovery_received = 0; + for i in 0..10 { + let msg = format!("Post-recovery {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send post-recovery"); + + now += Duration::from_millis(10); + + for _ in 0..3 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + post_recovery_received += server_out.app_data.len(); + } + } + + assert_eq!( + post_recovery_received, 10, + "All post-recovery messages should be received" + ); +} + +/// Test that high-frequency KeyUpdates work correctly. With the minimum +/// AEAD limit of 2, nearly every message triggers a KeyUpdate. This stress- +/// tests the key rotation machinery and epoch tracking under extreme churn, +/// exercising many more KeyUpdate cycles than the limit=10 tests above. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_key_update_high_frequency() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // With limit=2, quarter=0 so threshold=2 exactly. Every 2 AEAD + // encryptions on an epoch triggers a KeyUpdate. This means nearly + // every application message triggers a key rotation. + let config = Arc::new( + Config::builder() + .aead_encryption_limit(2) + .build() + .expect("build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Complete handshake + let mut client_connected = false; + let mut server_connected = false; + for _ in 0..30 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + now += Duration::from_millis(50); + } + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send 50 messages with limit=2. This triggers ~25 KeyUpdates, + // exercising epoch cycling through many values (3, 4, 5, ... ~28). + let mut server_received = 0; + for i in 0..50 { + let msg = format!("High-freq msg {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("send app data"); + + now += Duration::from_millis(10); + + for _ in 0..5 { + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + deliver_packets(&server_out.packets, &mut client); + + server_received += server_out.app_data.len(); + } + } + + assert_eq!( + server_received, 50, + "All 50 messages should be received despite high-frequency KeyUpdates" + ); +} diff --git a/third_party/dimpl/tests/dtls13/main.rs b/third_party/dimpl/tests/dtls13/main.rs new file mode 100644 index 0000000..162e821 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/main.rs @@ -0,0 +1,16 @@ +#[cfg(not(windows))] +#[path = "../wolfssl/mod.rs"] +mod wolfssl_helper; + +mod common; +mod conformance; +mod data; +mod edge; +mod fragmentation; +mod handshake; +mod key_update; +mod reorder; +mod retransmit; + +#[cfg(not(windows))] +mod wolfssl; diff --git a/third_party/dimpl/tests/dtls13/reorder.rs b/third_party/dimpl/tests/dtls13/reorder.rs new file mode 100644 index 0000000..445e6d3 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/reorder.rs @@ -0,0 +1,722 @@ +//! DTLS 1.3 packet reordering and duplicate tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::Dtls; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handles_duplicate_packets() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Deliver packets twice (simulating duplicates) + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&client_out.packets, &mut server); // Duplicate! + + deliver_packets(&server_out.packets, &mut client); + deliver_packets(&server_out.packets, &mut client); // Duplicate! + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect despite duplicate packets" + ); + assert!( + server_connected, + "Server should connect despite duplicate packets" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handles_out_of_order_packets() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Deliver packets in reverse order + let mut client_packets = client_out.packets.clone(); + let mut server_packets = server_out.packets.clone(); + client_packets.reverse(); + server_packets.reverse(); + + deliver_packets(&client_packets, &mut server); + deliver_packets(&server_packets, &mut client); + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + client_connected, + "Client should connect with out-of-order packets" + ); + assert!( + server_connected, + "Server should connect with out-of-order packets" + ); +} + +/// Test severely reordered packets - deliver packets in reverse order +/// Uses deterministic reordering pattern with sufficient rounds for retransmissions. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handles_severely_reordered_packets() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + // Use default MTU - we'll accumulate packets for reordering + let config = dtls13_config(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Buffer to hold packets for reordering + let mut server_buffer: Vec> = Vec::new(); + let mut packets_reordered = 0; + + // Use many rounds with very small time steps for reliability + for round in 0..500 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Deliver client packets normally + deliver_packets(&client_out.packets, &mut server); + + // Accumulate server packets + server_buffer.extend(server_out.packets); + + // Every 5 rounds or when we have accumulated enough, deliver in reverse order + if (round % 5 == 4 || server_buffer.len() >= 3) && !server_buffer.is_empty() { + packets_reordered += server_buffer.len(); + for p in server_buffer.iter().rev() { + let _ = client.handle_packet(p); + } + server_buffer.clear(); + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + // Deliver any remaining buffered packets + for p in server_buffer.iter().rev() { + let _ = client.handle_packet(p); + } + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect despite reordering"); + assert!(server_connected, "Server should connect despite reordering"); + assert!(packets_reordered > 0, "Should have reordered some packets"); + + eprintln!( + "SUCCESS: Handshake completed with {} packets delivered in reordered batches", + packets_reordered + ); +} + +/// Test delayed packets - hold packets for several rounds then deliver all at once +/// Uses deterministic hold pattern with sufficient rounds for retransmissions. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handles_delayed_burst_delivery() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let config = dtls13_config_with_mtu(220); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Hold packets for delayed delivery + let mut held_server_packets: Vec> = Vec::new(); + let mut held_client_packets: Vec> = Vec::new(); + let mut hold_rounds = 0; + const HOLD_DURATION: usize = 3; // Hold packets for 3 rounds before delivering + + // Use more rounds with shorter time steps for reliability + for _round in 0..200 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Collect packets + held_server_packets.extend(server_out.packets.iter().cloned()); + held_client_packets.extend(client_out.packets.iter().cloned()); + + hold_rounds += 1; + + // Deliver burst every HOLD_DURATION rounds + if hold_rounds >= HOLD_DURATION { + // Deliver all held packets at once + for p in &held_client_packets { + let _ = server.handle_packet(p); + } + for p in &held_server_packets { + let _ = client.handle_packet(p); + } + + held_server_packets.clear(); + held_client_packets.clear(); + hold_rounds = 0; + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + // Deliver any remaining packets + for p in &held_client_packets { + let _ = server.handle_packet(p); + } + for p in &held_server_packets { + let _ = client.handle_packet(p); + } + break; + } + + now += Duration::from_millis(20); + } + + assert!( + client_connected, + "Client should connect despite delayed delivery" + ); + assert!( + server_connected, + "Server should connect despite delayed delivery" + ); + + eprintln!("SUCCESS: Handshake completed with delayed burst delivery"); +} + +/// Test interleaved old and new packets (simulating network path changes) +/// Uses deterministic replay pattern with sufficient rounds for retransmissions. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handles_interleaved_old_and_new_packets() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let config = dtls13_config_with_mtu(220); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Store some packets to replay later (simulating delayed path) + let mut old_server_packets: Vec> = Vec::new(); + let mut captured_old = false; + + // Use more rounds with shorter time steps for reliability + for round in 0..200 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + + // Capture some early packets + if !captured_old && !server_out.packets.is_empty() && round < 5 { + old_server_packets = server_out.packets.clone(); + captured_old = true; + } + + // Normal delivery + deliver_packets(&server_out.packets, &mut client); + + // Interleave old packets with new ones (replay old packets periodically) + // Use deterministic pattern: replay at rounds 7, 14, 21, ... + if captured_old && round % 7 == 0 && round > 0 && !old_server_packets.is_empty() { + for p in &old_server_packets { + // These should be safely ignored (duplicates/old epoch) + let _ = client.handle_packet(p); + } + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(20); + } + + assert!( + client_connected, + "Client should connect despite interleaved old packets" + ); + assert!( + server_connected, + "Server should connect despite interleaved old packets" + ); + + eprintln!("SUCCESS: Handshake completed with interleaved old/new packets"); +} + +/// After handshake, send 100 app data messages from client to server, delivering +/// each one. Then replay the very first packet. The replayed packet should be +/// silently dropped because it falls outside the 64-packet replay window. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_replay_window_rejects_old_record() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Complete handshake + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send 100 app data messages from client to server, delivering each one. + // Capture the very first packet for replay later. + let mut first_packet: Option> = None; + + for i in 0..100 { + let msg = format!("Message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("client send"); + + let client_out = drain_outputs(&mut client); + deliver_packets(&client_out.packets, &mut server); + + if i == 0 { + // unwrap: first message always produces at least one packet + first_packet = Some(client_out.packets[0].clone()); + } + + let server_out = drain_outputs(&mut server); + assert!( + !server_out.app_data.is_empty(), + "Server should receive message {}", + i + ); + + now += Duration::from_millis(1); + } + + // Now replay the very first packet — it is well outside the 64-packet window + let replayed = first_packet.expect("should have captured first packet"); + let _ = server.handle_packet(&replayed); + + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.is_empty(), + "Replayed old packet should be silently dropped" + ); +} + +/// After handshake, send one app data message and deliver the packet. Then +/// deliver the exact same packet again. Only one copy of the data should be +/// received by the server — the duplicate is rejected by the replay window. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_replay_window_rejects_duplicate_app_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Complete handshake + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send one app data message + client + .send_application_data(b"Hello once") + .expect("client send"); + + let client_out = drain_outputs(&mut client); + let packets = client_out.packets.clone(); + + // Deliver the packet — server should receive the data + deliver_packets(&packets, &mut server); + let server_out = drain_outputs(&mut server); + assert_eq!( + server_out.app_data.len(), + 1, + "Server should receive exactly one message" + ); + assert_eq!(&server_out.app_data[0][..], b"Hello once"); + + // Deliver the exact same packet again — duplicate should be rejected + deliver_packets(&packets, &mut server); + let server_out = drain_outputs(&mut server); + assert!( + server_out.app_data.is_empty(), + "Duplicate packet should be silently dropped" + ); +} + +/// After handshake, send several app data messages. Deliver them out of order +/// (e.g., deliver message 3 before message 2, but both within the 64-packet +/// window). Both should be accepted and the data received. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_replay_window_accepts_within_range() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Complete handshake + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send 5 app data messages, collecting all packets without delivering + let mut all_packets: Vec> = Vec::new(); + let messages = vec![ + b"Message 1".to_vec(), + b"Message 2".to_vec(), + b"Message 3".to_vec(), + b"Message 4".to_vec(), + b"Message 5".to_vec(), + ]; + + for msg in &messages { + client.send_application_data(msg).expect("client send"); + let client_out = drain_outputs(&mut client); + all_packets.extend(client_out.packets); + } + + // Deliver out of order: swap packets so that later ones arrive first. + // Reverse the packet order — all are within the 64-packet window. + let mut reordered = all_packets.clone(); + reordered.reverse(); + + let mut server_received: Vec> = Vec::new(); + deliver_packets(&reordered, &mut server); + let server_out = drain_outputs(&mut server); + server_received.extend(server_out.app_data); + + assert_eq!( + server_received.len(), + messages.len(), + "All out-of-order messages within window should be accepted" + ); + + // Verify all expected message contents were received (order may differ) + let mut received_sorted: Vec> = server_received.clone(); + received_sorted.sort(); + let mut expected_sorted = messages.clone(); + expected_sorted.sort(); + assert_eq!( + received_sorted, expected_sorted, + "All message contents should be received" + ); +} + +/// After handshake, send 10 app data messages from client. Collect all packets. +/// Deliver them in reverse order. All 10 messages should be received by the +/// server since they are all within the 64-packet replay window. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_reorder_app_data_after_handshake() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + let mut client_connected = false; + let mut server_connected = false; + + // Complete handshake + for _ in 0..40 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + deliver_packets(&client_out.packets, &mut server); + deliver_packets(&server_out.packets, &mut client); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect"); + assert!(server_connected, "Server should connect"); + + // Send 10 app data messages, collecting all packets without delivering + let mut all_packets: Vec> = Vec::new(); + let message_count = 10; + + for i in 0..message_count { + let msg = format!("Reverse message {}", i); + client + .send_application_data(msg.as_bytes()) + .expect("client send"); + let client_out = drain_outputs(&mut client); + all_packets.extend(client_out.packets); + } + + // Deliver all packets in reverse order + let mut reversed = all_packets.clone(); + reversed.reverse(); + + deliver_packets(&reversed, &mut server); + let server_out = drain_outputs(&mut server); + + assert_eq!( + server_out.app_data.len(), + message_count, + "All {} messages should be received when delivered in reverse order", + message_count + ); + + // Verify all expected message contents were received (order may differ) + let mut received_sorted: Vec = server_out + .app_data + .iter() + .map(|d| String::from_utf8_lossy(d).to_string()) + .collect(); + received_sorted.sort(); + + let mut expected_sorted: Vec = (0..message_count) + .map(|i| format!("Reverse message {}", i)) + .collect(); + expected_sorted.sort(); + + assert_eq!( + received_sorted, expected_sorted, + "All message contents should be received" + ); +} diff --git a/third_party/dimpl/tests/dtls13/retransmit.rs b/third_party/dimpl/tests/dtls13/retransmit.rs new file mode 100644 index 0000000..ad0226b --- /dev/null +++ b/third_party/dimpl/tests/dtls13/retransmit.rs @@ -0,0 +1,956 @@ +//! DTLS 1.3 retransmission tests. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls}; + +use crate::common::*; + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_client_retransmits_on_timeout() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + // Get initial ClientHello + client.handle_timeout(now).expect("client start"); + client.handle_timeout(now).expect("client arm"); + let initial_packets = collect_packets(&mut client); + assert!( + !initial_packets.is_empty(), + "Client should send ClientHello" + ); + + // Don't deliver to server, trigger timeout + trigger_timeout(&mut client, &mut now); + + // Should get retransmitted packets + let retransmit_packets = collect_packets(&mut client); + assert!( + !retransmit_packets.is_empty(), + "Client should retransmit on timeout" + ); + + // Retransmit should have same number of packets (same flight) + assert_eq!( + initial_packets.len(), + retransmit_packets.len(), + "Retransmit should have same packet count" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_completes_after_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = dtls13_config(); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut drop_next_client_packet = true; // Drop first ClientHello + + for i in 0..60 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Simulate packet loss: drop first client packet + if !client_out.packets.is_empty() && drop_next_client_packet { + drop_next_client_packet = false; + // Don't deliver client packets this round + } else { + deliver_packets(&client_out.packets, &mut server); + } + + deliver_packets(&server_out.packets, &mut client); + + if client_connected && server_connected { + break; + } + + // Advance time to trigger retransmissions + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite initial packet loss" + ); + assert!( + server_connected, + "Server should connect despite initial packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_completes_with_early_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use a config with more retries to handle packet loss + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build DTLS 1.3 config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + + // Drop first 2 client packets and first 2 server packets to test retransmission + let mut client_packets_to_drop = 2; + let mut server_packets_to_drop = 2; + + for i in 0..60 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + if client_out.connected { + client_connected = true; + } + if server_out.connected { + server_connected = true; + } + + // Deliver client packets, dropping first N + for packet in &client_out.packets { + if client_packets_to_drop > 0 { + client_packets_to_drop -= 1; + } else { + let _ = server.handle_packet(packet); + } + } + + // Deliver server packets, dropping first N + for packet in &server_out.packets { + if server_packets_to_drop > 0 { + server_packets_to_drop -= 1; + } else { + let _ = client.handle_packet(packet); + } + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite early packet loss" + ); + assert!( + server_connected, + "Server should connect despite early packet loss" + ); +} + +/// Test packet loss on both directions simultaneously (moderate loss rate) +/// Uses a deterministic drop pattern: drop packets only in specific rounds, +/// ensuring retransmissions in later rounds get through. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handles_bidirectional_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let config = dtls13_config_with_mtu(220); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut dropped_client = 0; + let mut dropped_server = 0; + let mut total_client_packets = 0; + let mut total_server_packets = 0; + + // Run for plenty of rounds to allow retransmissions + for round in 0..300 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Drop pattern: drop every other packet, but only in rounds 0-4 and 8-12 + // This simulates burst loss with recovery windows + let is_loss_window = round < 5 || (8..13).contains(&round); + + for (i, p) in client_out.packets.iter().enumerate() { + total_client_packets += 1; + // Drop odd-indexed packets during loss windows + if is_loss_window && i % 2 == 1 { + dropped_client += 1; + } else { + let _ = server.handle_packet(p); + } + } + + for (i, p) in server_out.packets.iter().enumerate() { + total_server_packets += 1; + // Drop even-indexed packets during loss windows (different pattern) + if is_loss_window && i % 2 == 0 && server_out.packets.len() > 1 { + dropped_server += 1; + } else { + let _ = client.handle_packet(p); + } + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(20); + } + + assert!( + client_connected, + "Client should connect despite bidirectional loss" + ); + assert!( + server_connected, + "Server should connect despite bidirectional loss" + ); + + // Verify we actually dropped some packets + assert!( + dropped_client > 0 || dropped_server > 0, + "Test should have dropped some packets" + ); + + eprintln!( + concat!( + "SUCCESS: Handshake completed with bidirectional loss. Dropped: ", + "client→server={}/{}, server→client={}/{}" + ), + dropped_client, total_client_packets, dropped_server, total_server_packets + ); +} + +/// Test random packet loss pattern (chaos test) +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_survives_random_packet_loss_pattern() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let config = dtls13_config_with_mtu(220); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut total_dropped = 0; + let mut total_delivered = 0; + + // Deterministic "random-like" loss pattern + // Drop only specific packets that won't kill the handshake + let should_drop = |round: usize, packet_idx: usize| -> bool { + // Only drop on certain rounds, and only if there are multiple packets + // This ensures we don't drop critical single-packet flights + round > 2 && round % 7 == 0 && packet_idx == 0 + }; + + for round in 0..100 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + // Deliver with controlled drops + for (i, p) in client_out.packets.iter().enumerate() { + if !should_drop(round, i) || client_out.packets.len() == 1 { + let _ = server.handle_packet(p); + total_delivered += 1; + } else { + total_dropped += 1; + } + } + + for (i, p) in server_out.packets.iter().enumerate() { + if !should_drop(round, i) || server_out.packets.len() == 1 { + let _ = client.handle_packet(p); + total_delivered += 1; + } else { + total_dropped += 1; + } + } + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(30); + } + + assert!(client_connected, "Client should eventually connect"); + assert!(server_connected, "Server should eventually connect"); + + let drop_rate = if total_dropped + total_delivered > 0 { + total_dropped as f64 / (total_dropped + total_delivered) as f64 * 100.0 + } else { + 0.0 + }; + eprintln!( + "SUCCESS: Handshake completed with controlled loss. Dropped: {}, Delivered: {}, Drop rate: {:.1}%", + total_dropped, total_delivered, drop_rate + ); +} + +/// Test selective retransmit: verify that only unACKed records are retransmitted. +/// This test carefully controls packet delivery to verify the actual retransmit behavior. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_selective_retransmit_only_missing_records() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + fn count_epoch2_records(packet: &[u8]) -> usize { + let mut i = 0usize; + let mut count = 0usize; + while i < packet.len() { + let b0 = packet[i]; + if (b0 & 0b1110_0000) == 0b0010_0000 { + let c = (b0 & 0b0001_0000) != 0; + let s16 = (b0 & 0b0000_1000) != 0; + let l = (b0 & 0b0000_0100) != 0; + let epoch_bits = b0 & 0b0000_0011; + if c { + break; + } + let mut header_len = 1 + if s16 { 2 } else { 1 }; + if l { + header_len += 2; + } + if i + header_len > packet.len() { + break; + } + let ciphertext_len = if l { + let off = i + 1 + if s16 { 2 } else { 1 }; + u16::from_be_bytes([packet[off], packet[off + 1]]) as usize + } else { + packet.len() - (i + header_len) + }; + if epoch_bits == 2 { + count += 1; + } + i += header_len.saturating_add(ciphertext_len); + continue; + } + if i + 13 > packet.len() { + break; + } + let len = u16::from_be_bytes([packet[i + 11], packet[i + 12]]) as usize; + i += 13 + len; + } + count + } + + const ATTEMPTS: usize = 12; + + let mut success = None; + let mut attempts_with_drop = 0usize; + let mut attempts_with_retransmit = 0usize; + let mut attempts_with_client_epoch2 = 0usize; + let mut attempts_connected = 0usize; + + for attempt in 0..ATTEMPTS { + // Small MTU to force multi-packet flights. + // Vary deterministic seeds and dropped epoch-2 index across attempts so + // we exercise different fragmentation layouts without relying on runtime RNG. + let client_config = Arc::new( + Config::builder() + .mtu(220) + .dangerously_set_rng_seed(0xC1A0_C1A0u64.wrapping_add(attempt as u64 * 17)) + .build() + .expect("Failed to build DTLS 1.3 client config"), + ); + let server_config = Arc::new( + Config::builder() + .mtu(220) + .dangerously_set_rng_seed(0x5E8E_5E8Eu64.wrapping_add(attempt as u64 * 29)) + .build() + .expect("Failed to build DTLS 1.3 server config"), + ); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&client_config), client_cert, now); + client.set_active(true); + let mut server = Dtls::new_13(server_config, server_cert, now); + server.set_active(false); + + let mut dropped_packet: Option> = None; + let mut original_flight_size = 0usize; + let mut saw_any_retransmit = false; + let mut selective_retransmit_flight_size = None; + let mut delivered_client_epoch2_after_drop = 0usize; + let mut client_connected = false; + let mut server_connected = false; + + for round in 0..220 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + for p in &client_out.packets { + if dropped_packet.is_some() && count_epoch2_records(p) > 0 { + delivered_client_epoch2_after_drop += 1; + } + let _ = server.handle_packet(p); + } + + // Phase 1: Find a multi-packet epoch-2 flight and drop one packet. + if dropped_packet.is_none() { + let epoch2_indices: Vec = server_out + .packets + .iter() + .enumerate() + .filter(|(_, p)| count_epoch2_records(p) > 0) + .map(|(i, _)| i) + .collect(); + + if epoch2_indices.len() >= 3 { + original_flight_size = epoch2_indices.len(); + + let drop_epoch2_idx = attempt % epoch2_indices.len(); + let drop_packet_idx = epoch2_indices[drop_epoch2_idx]; + dropped_packet = Some(server_out.packets[drop_packet_idx].clone()); + + for (i, p) in server_out.packets.iter().enumerate() { + if i != drop_packet_idx { + let _ = client.handle_packet(p); + } + } + + eprintln!( + "Attempt {} Round {}: Dropped packet {} of {}", + attempt, round, drop_epoch2_idx, original_flight_size + ); + } else { + deliver_packets(&server_out.packets, &mut client); + } + } + // Phase 2: After dropping, wait for retransmit and count packets. + // The first resend can be full-flight (dupe-triggered), so keep waiting. + else if selective_retransmit_flight_size.is_none() { + let epoch2_packets: Vec<&Vec> = server_out + .packets + .iter() + .filter(|p| count_epoch2_records(p) > 0) + .collect(); + + if !epoch2_packets.is_empty() { + let retransmit_flight_size = epoch2_packets.len(); + saw_any_retransmit = true; + + eprintln!( + "Attempt {} Round {}: Retransmit flight has {} packets (original had {})", + attempt, round, retransmit_flight_size, original_flight_size + ); + + if retransmit_flight_size < original_flight_size { + selective_retransmit_flight_size = Some(retransmit_flight_size); + } else { + eprintln!( + "Attempt {} Round {}: Full-flight resend observed before selective resend", + attempt, round + ); + } + } + + deliver_packets(&server_out.packets, &mut client); + } else { + deliver_packets(&server_out.packets, &mut client); + } + + if selective_retransmit_flight_size.is_some() && client_connected && server_connected { + break; + } + + now += Duration::from_millis(150); + } + + if dropped_packet.is_some() { + attempts_with_drop += 1; + } + if saw_any_retransmit { + attempts_with_retransmit += 1; + } + if delivered_client_epoch2_after_drop > 0 { + attempts_with_client_epoch2 += 1; + } + if client_connected && server_connected { + attempts_connected += 1; + } + + if let Some(retransmit_flight_size) = selective_retransmit_flight_size { + if client_connected && server_connected { + success = Some((attempt, original_flight_size, retransmit_flight_size)); + break; + } + } + } + + let Some((attempt, original_flight_size, retransmit_flight_size)) = success else { + panic!( + "Did not observe selective retransmit across {} attempts \ + (drop={}, retransmit={}, client_epoch2_after_drop={}, connected={})", + ATTEMPTS, + attempts_with_drop, + attempts_with_retransmit, + attempts_with_client_epoch2, + attempts_connected + ); + }; + + eprintln!( + "SUCCESS: Selective retransmit verified on attempt {}. \ + Original flight: {} packets, Retransmit: {} packets", + attempt, original_flight_size, retransmit_flight_size + ); +} + +/// Test that retransmission timeouts increase exponentially. +/// Start a handshake but never deliver packets to the server. +/// Record each timeout value and verify they increase monotonically. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_retransmit_exponential_backoff() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + // Use enough retries to observe several backoff steps + let config = Arc::new( + Config::builder() + .flight_retries(6) + .handshake_timeout(Duration::from_secs(300)) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let _server = Dtls::new_13(config, server_cert, now); + + // Kick off the handshake + client.handle_timeout(now).expect("client start"); + client.handle_timeout(now).expect("client arm"); + + // Collect initial packets (ClientHello) without delivering them + let _initial_packets = collect_packets(&mut client); + + // Record successive timeout values by triggering retransmissions + let mut timeouts: Vec = Vec::new(); + + for _ in 0..6 { + // Drain to get the current timeout instant + let out = drain_outputs(&mut client); + let timeout_instant = out.timeout.expect("Should have a timeout scheduled"); + + let wait = timeout_instant.duration_since(now); + timeouts.push(wait); + + // Advance past the timeout to trigger retransmission + now = timeout_instant; + client.handle_timeout(now).expect("client timeout"); + + // Consume retransmitted packets without delivering + let _retransmit = collect_packets(&mut client); + } + + // Verify we collected multiple timeout values + assert!( + timeouts.len() >= 4, + "Should have at least 4 timeout values, got {}", + timeouts.len() + ); + + // Verify each timeout is larger than the previous (exponential backoff) + for i in 1..timeouts.len() { + assert!( + timeouts[i] > timeouts[i - 1], + "Timeout {} ({:?}) should be larger than timeout {} ({:?})", + i, + timeouts[i], + i - 1, + timeouts[i - 1] + ); + } + + // Verify rough doubling: each timeout should be at least 1.5x the previous + // (accounting for jitter of +/- 0.25s) + for i in 1..timeouts.len() { + let ratio = timeouts[i].as_secs_f64() / timeouts[i - 1].as_secs_f64(); + assert!( + ratio > 1.4, + "Timeout ratio {}/{} = {:.2} should be > 1.4 (exponential backoff)", + i, + i - 1, + ratio + ); + } + + eprintln!( + "SUCCESS: Exponential backoff verified. Timeouts: {:?}", + timeouts + ); +} + +/// Test that when the server's ACK is lost, the client falls back to its +/// retransmission timer and the handshake still completes. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_ack_loss_falls_back_to_timer() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut client_final_flight_seen = false; + let mut ack_dropped = false; + + for round in 0..100 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + // Always deliver client packets to server + deliver_packets(&client_out.packets, &mut server); + + // Track the handshake phases: + // Once the client has sent packets after receiving the server's flight, + // the next server response is likely an ACK — drop it once. + if client_final_flight_seen && !ack_dropped && !server_out.packets.is_empty() { + // Drop this server response (the ACK) + ack_dropped = true; + eprintln!("Round {}: Dropped server ACK", round); + } else { + deliver_packets(&server_out.packets, &mut client); + } + + // Detect client's final flight (client sends after having received server's flight) + if !client_final_flight_seen && !client_out.packets.is_empty() && round > 2 { + client_final_flight_seen = true; + } + + if client_connected && server_connected { + eprintln!( + "Round {}: Both connected (ack_dropped={})", + round, ack_dropped + ); + break; + } + + // Advance time: use larger steps periodically to trigger retransmissions + if round % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!(client_connected, "Client should connect despite ACK loss"); + assert!(server_connected, "Server should connect despite ACK loss"); + assert!(ack_dropped, "Test should have dropped an ACK packet"); +} + +/// Test retransmission during a HelloRetryRequest flow. +/// The default DTLS 1.3 config triggers HRR (via cookie). Drop packets during +/// the HRR exchange and verify the handshake still completes via retransmission. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_retransmit_during_hrr_flow() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + let mut client_connected = false; + let mut server_connected = false; + let mut client_flight_count = 0; + let mut dropped_server_hrr = false; + + for round in 0..100 { + client.handle_timeout(now).expect("client timeout"); + server.handle_timeout(now).expect("server timeout"); + + let client_out = drain_outputs(&mut client); + let server_out = drain_outputs(&mut server); + + client_connected |= client_out.connected; + server_connected |= server_out.connected; + + if !client_out.packets.is_empty() { + client_flight_count += 1; + } + + // Deliver client packets to server + deliver_packets(&client_out.packets, &mut server); + + // Drop the first server response (the HRR) to force retransmission + if !dropped_server_hrr && !server_out.packets.is_empty() && client_flight_count <= 1 { + dropped_server_hrr = true; + eprintln!("Round {}: Dropped server HRR response", round); + // Don't deliver — force client to retransmit and server to re-send HRR + } else { + deliver_packets(&server_out.packets, &mut client); + } + + if client_connected && server_connected { + break; + } + + // Advance time: larger steps periodically to trigger retransmissions + if round % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite HRR packet loss" + ); + assert!( + server_connected, + "Server should connect despite HRR packet loss" + ); + assert!( + dropped_server_hrr, + "Test should have dropped the HRR response" + ); +} + +/// Test that a short handshake timeout causes the client to abort. +/// Configure a 5-second handshake timeout, never deliver any packets, +/// and verify the client eventually returns a timeout error. +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_handshake_timeout_aborts() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + + let config = Arc::new( + Config::builder() + .handshake_timeout(Duration::from_secs(5)) + .flight_retries(10) // plenty of retries so we hit connect timeout, not flight exhaustion + .flight_start_rto(Duration::from_millis(200)) + .build() + .expect("Failed to build config"), + ); + + let mut now = Instant::now(); + let start = now; + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let _server = Dtls::new_13(config, server_cert, now); + + // Kick off the handshake + client.handle_timeout(now).expect("client start"); + client.handle_timeout(now).expect("client arm"); + let _ = collect_packets(&mut client); + + let mut got_timeout_error = false; + + for _ in 0..200 { + // Drain to find the next timeout + let out = drain_outputs(&mut client); + let Some(timeout_instant) = out.timeout else { + break; + }; + + // Advance to the timeout + now = timeout_instant; + + match client.handle_timeout(now) { + Ok(()) => { + // Consume retransmitted packets without delivering + let _ = collect_packets(&mut client); + } + Err(e) => { + let msg = format!("{}", e); + assert!( + msg.contains("timeout"), + "Expected timeout error, got: {}", + msg + ); + got_timeout_error = true; + break; + } + } + } + + assert!( + got_timeout_error, + "Client should have aborted with a timeout error" + ); + + let elapsed = now.duration_since(start); + assert!( + elapsed <= Duration::from_secs(10), + "Timeout should have fired within a reasonable time, took {:?}", + elapsed + ); + + eprintln!( + "SUCCESS: Handshake aborted after {:?} with timeout error", + elapsed + ); +} diff --git a/third_party/dimpl/tests/dtls13/wolfssl.rs b/third_party/dimpl/tests/dtls13/wolfssl.rs new file mode 100644 index 0000000..f068346 --- /dev/null +++ b/third_party/dimpl/tests/dtls13/wolfssl.rs @@ -0,0 +1,2232 @@ +//! DTLS 1.3 interop tests: dimpl <-> WolfSSL +//! +//! Tests verify DTLS 1.3 interoperability between dimpl and WolfSSL, +//! with dimpl as both client and server. + +#![allow(unused, dead_code)] + +use std::collections::VecDeque; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use dimpl::{Config, Dtls, Output, SrtpProfile}; + +use crate::wolfssl_helper::{DtlsEvent, WolfDtlsCert}; + +// ============================================================================= +// Shared helpers +// ============================================================================= + +/// Collected outputs from polling a dimpl endpoint. +#[derive(Default, Debug)] +struct DrainedOutputs { + packets: Vec>, + connected: bool, + peer_cert: Option>, + keying_material: Option<(Vec, SrtpProfile)>, + app_data: Vec>, + timeout: Option, +} + +/// Drain all outputs from a dimpl endpoint. +fn drain_dimpl_outputs(endpoint: &mut Dtls) -> DrainedOutputs { + let mut result = DrainedOutputs::default(); + let mut buf = vec![0u8; 2048]; + + loop { + match endpoint.poll_output(&mut buf) { + Output::Packet(p) => result.packets.push(p.to_vec()), + Output::Connected => result.connected = true, + Output::PeerCert(cert) => result.peer_cert = Some(cert.to_vec()), + Output::KeyingMaterial(km, profile) => { + result.keying_material = Some((km.to_vec(), profile)); + } + Output::ApplicationData(data) => result.app_data.push(data.to_vec()), + Output::Timeout(t) => { + result.timeout = Some(t); + break; + } + _ => {} + } + } + + result +} + +/// Create a DTLS 1.3 config. +fn dtls13_config() -> Arc { + Arc::new( + Config::builder() + .build() + .expect("Failed to build DTLS 1.3 config"), + ) +} + +/// Create a DTLS 1.3 config with custom MTU. +fn dtls13_config_with_mtu(mtu: usize) -> Arc { + Arc::new( + Config::builder() + .mtu(mtu) + .build() + .expect("Failed to build DTLS 1.3 config"), + ) +} + +// ============================================================================= +// Client tests: dimpl client <-> WolfSSL server +// ============================================================================= + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_handshake() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + if client_out.connected { + client_connected = true; + } + + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .expect("wolf server handle receive"); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + server_connected = true; + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "dimpl client should be connected"); + assert!(server_connected, "WolfSSL server should be connected"); +} + +// NOTE: Keying material test skipped for WolfSSL interop. +// WolfSSL DTLS 1.3 server doesn't appear to support SRTP extension by default, +// so keying material export won't work without additional WolfSSL configuration. + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_data_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake first + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .expect("wolf server handle receive"); + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if client_out.connected && wolf_server.is_connected() { + break; + } + + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send data from client to server + let test_data = b"Hello from dimpl client!"; + dimpl_client + .send_application_data(test_data) + .expect("write app data"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + + let mut received_data = Vec::new(); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .expect("wolf server handle receive"); + } + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + received_data.extend_from_slice(&data); + } + } + + assert_eq!( + received_data, test_data, + "WolfSSL server should receive the data from dimpl client" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_bidirectional_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + if client_out.connected && wolf_server.is_connected() { + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send data both directions + let client_data = b"Hello from dimpl client!"; + let server_data = b"Hello from WolfSSL server!"; + + dimpl_client + .send_application_data(client_data) + .expect("client send"); + wolf_server.write(server_data).expect("server send"); + + let mut client_received = Vec::new(); + let mut server_received = Vec::new(); + + for _ in 0..20 { + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for data in client_out.app_data { + client_received.extend_from_slice(&data); + } + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + server_received.extend_from_slice(&data); + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if !client_received.is_empty() && !server_received.is_empty() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!( + client_received, server_data, + "Client should receive server data" + ); + assert_eq!( + server_received, client_data, + "Server should receive client data" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_multiple_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + if client_out.connected && wolf_server.is_connected() { + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send multiple messages - send each one and let it be processed + let messages = vec![ + b"Message 1".to_vec(), + b"Message 2".to_vec(), + b"Message 3 is a bit longer".to_vec(), + b"Message 4".to_vec(), + b"Message 5 - the final one".to_vec(), + ]; + + let mut server_received: Vec> = Vec::new(); + + for msg in &messages { + dimpl_client + .send_application_data(msg) + .expect("client send"); + + // Drain and deliver each message immediately + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + server_received.push(data); + } + } + } + + let expected: Vec = messages.iter().flatten().copied().collect(); + let total_received: Vec = server_received.iter().flatten().copied().collect(); + assert_eq!(total_received, expected, "All messages should be received"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_many_small_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + if client_out.connected && wolf_server.is_connected() { + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send many small messages + let message_count = 100; + for i in 0..message_count { + let msg = format!("M{}", i); + dimpl_client + .send_application_data(msg.as_bytes()) + .expect("send"); + } + + let mut received_bytes: Vec = Vec::new(); + + for _ in 0..50 { + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + received_bytes.extend_from_slice(&data); + } + } + + now += Duration::from_millis(10); + } + + assert!( + !received_bytes.is_empty(), + "Should receive application data" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_retransmit_on_timeout() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + + // Get initial ClientHello + dimpl_client.handle_timeout(now).expect("client start"); + dimpl_client.handle_timeout(now).expect("client arm"); + let initial_out = drain_dimpl_outputs(&mut dimpl_client); + assert!( + !initial_out.packets.is_empty(), + "Client should send ClientHello" + ); + + // Don't deliver to server, trigger timeout + now += Duration::from_secs(2); + dimpl_client.handle_timeout(now).expect("client timeout"); + + // Should get retransmitted packets + let retransmit_out = drain_dimpl_outputs(&mut dimpl_client); + assert!( + !retransmit_out.packets.is_empty(), + "Client should retransmit on timeout" + ); + + assert_eq!( + initial_out.packets.len(), + retransmit_out.packets.len(), + "Retransmit should have same packet count" + ); + + // Now actually complete the handshake to verify everything works + let wolf_events = &mut VecDeque::new(); + + // First, deliver the retransmitted packets we already have + for packet in &retransmit_out.packets { + wolf_server.handle_receive(packet, wolf_events).unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + wolf_events.clear(); + + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server.handle_receive(packet, wolf_events).unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + if client_out.connected && wolf_server.is_connected() { + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + assert!(wolf_server.is_connected(), "Should eventually connect"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_handshake_after_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + let mut drop_next_packet = true; + + for i in 0..60 { + dimpl_client.handle_timeout(now).expect("client timeout"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + if client_out.connected { + client_connected = true; + } + + // Drop first packet + if !client_out.packets.is_empty() && drop_next_packet { + drop_next_packet = false; + } else { + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + server_connected = true; + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite packet loss" + ); + assert!( + server_connected, + "Server should connect despite packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_handles_duplicates() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + if client_out.connected { + client_connected = true; + } + + // Send packets twice (duplicates) + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + server_connected = true; + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + let _ = dimpl_client.handle_packet(&packet); // Duplicate + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect despite duplicates"); + assert!(server_connected, "Server should connect despite duplicates"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_handles_out_of_order() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // First complete handshake normally + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + if client_out.connected && wolf_server.is_connected() { + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + assert!(wolf_server.is_connected(), "Handshake should complete"); + + // Now test out-of-order application data delivery + // Send multiple messages from client, deliver to server in reverse order + dimpl_client + .send_application_data(b"First") + .expect("send 1"); + dimpl_client + .send_application_data(b"Second") + .expect("send 2"); + dimpl_client + .send_application_data(b"Third") + .expect("send 3"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + + // Deliver packets in reverse order (if there are multiple) + let mut packets = client_out.packets.clone(); + packets.reverse(); + for packet in &packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + let mut server_received: Vec = Vec::new(); + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + server_received.extend_from_slice(&data); + } + } + + // DTLS should handle reordering - all data should arrive + assert!( + !server_received.is_empty(), + "Server should receive data despite reordering" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_small_mtu() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + // Use 600 MTU - large enough for handshake but smaller than default + let config = dtls13_config_with_mtu(600); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + let mut max_client_packet_size = 0usize; + + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + if client_out.connected { + client_connected = true; + } + + for p in &client_out.packets { + if p.len() > max_client_packet_size { + max_client_packet_size = p.len(); + } + } + + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + server_connected = true; + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(client_connected, "Client should connect with small MTU"); + assert!(server_connected, "Server should connect with small MTU"); + // Only check that dimpl client respects MTU (WolfSSL may not) + assert!( + max_client_packet_size <= 600, + "Client packets should respect MTU: max was {}", + max_client_packet_size + ); +} + +// NOTE: This test is skipped because dimpl does not fragment application data +// by MTU. Neither DTLS 1.2 nor DTLS 1.3 splits app data into multiple records. +// Handshake fragmentation is supported, but app data is sent as a single record. +#[ignore = "dimpl does not fragment application data by MTU"] +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_large_data_fragmented() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config_with_mtu(300); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_client.handle_timeout(now).expect("client timeout"); + let client_out = drain_dimpl_outputs(&mut dimpl_client); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + if client_out.connected && wolf_server.is_connected() { + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send large data + let large_data = vec![0xABu8; 1000]; + dimpl_client + .send_application_data(&large_data) + .expect("send large data"); + + let mut server_received: Vec = Vec::new(); + let mut packet_count = 0; + + for _ in 0..20 { + let client_out = drain_dimpl_outputs(&mut dimpl_client); + packet_count += client_out.packets.len(); + for packet in &client_out.packets { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + server_received.extend_from_slice(&data); + } + } + + if server_received.len() >= large_data.len() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!( + server_received, large_data, + "Large data should be received correctly" + ); + assert!( + packet_count >= 2, + "Large data should be split into multiple packets: {}", + packet_count + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_recovers_from_corruption() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + let config = dtls13_config(); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + let mut corrupted_once = false; + + for i in 0..60 { + dimpl_client.handle_timeout(now).expect("client timeout"); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + if client_out.connected { + client_connected = true; + } + + // Corrupt one packet + for mut p in client_out.packets { + if !corrupted_once && p.len() > 20 { + p[15] ^= 0xFF; + p[16] ^= 0xFF; + corrupted_once = true; + } + let _ = wolf_server.handle_receive(&p, &mut wolf_events); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + server_connected = true; + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(50); + } + } + + assert!(client_connected, "Client should connect despite corruption"); + assert!(server_connected, "Server should connect despite corruption"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_handshake_with_early_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let client_cert = generate_self_signed_certificate().expect("gen client cert"); + let server_dimpl_cert = generate_self_signed_certificate().expect("gen server cert"); + + let wolf_server_cert = WolfDtlsCert::new( + server_dimpl_cert.certificate.clone(), + server_dimpl_cert.private_key.clone(), + ); + + let mut wolf_server = wolf_server_cert + .new_dtls13_impl(true) + .expect("Failed to create WolfSSL server"); + + // Use more retries for lossy conditions + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build DTLS 1.3 config"), + ); + + let now = Instant::now(); + let mut dimpl_client = Dtls::new_13(config, client_cert, now); + dimpl_client.set_active(true); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + // Drop first 3 packets to test retransmission recovery + let mut packets_to_drop = 3; + + for i in 0..60 { + let _ = dimpl_client.handle_timeout(now); + + let client_out = drain_dimpl_outputs(&mut dimpl_client); + if client_out.connected { + client_connected = true; + } + + // Drop first N packets, then deliver all + for packet in &client_out.packets { + if packets_to_drop > 0 { + packets_to_drop -= 1; + } else { + wolf_server + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + server_connected = true; + } + } + + while let Some(packet) = wolf_server.poll_datagram() { + let _ = dimpl_client.handle_packet(&packet); + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + client_connected, + "Client should connect despite early packet loss" + ); + assert!( + server_connected, + "Server should connect despite early packet loss" + ); +} + +// ============================================================================= +// Server tests: WolfSSL client <-> dimpl server +// ============================================================================= + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_handshake() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + dimpl_server.handle_timeout(now).expect("server timeout"); + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .expect("wolf client handle receive"); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(server_connected, "dimpl server should be connected"); + assert!(client_connected, "WolfSSL client should be connected"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_data_exchange() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + if server_out.connected && wolf_client.is_connected() { + wolf_events.clear(); + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send data from WolfSSL client to dimpl server + let test_data = b"Hello from WolfSSL client!"; + wolf_client + .write(test_data) + .expect("write from wolf client"); + + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + let received: Vec = server_out.app_data.into_iter().flatten().collect(); + + assert_eq!( + received, test_data, + "dimpl server should receive the data from WolfSSL client" + ); +} + +// NOTE: This test is commented out due to WolfSSL state machine quirks +// WolfSSL returns error -441 "Application data is available for reading" +// when trying to receive new data after a bidirectional exchange. +// The data_exchange test verifies one-way data transfer works. +/* +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_bidirectional_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for packet in &server_out.packets { + wolf_client.handle_receive(packet, &mut wolf_events).unwrap(); + } + if server_out.connected && wolf_client.is_connected() { + wolf_events.clear(); + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send data from client to server + let client_data = b"Hello from WolfSSL!"; + wolf_client.write(client_data).expect("client write"); + + // Send data from server to client + let server_data = b"Hello from dimpl!"; + dimpl_server.send_application_data(server_data).expect("server send"); + + // Drain any pending data in WolfSSL before sending new packets + wolf_client.drain_pending_data(&mut wolf_events); + while let Some(event) = wolf_events.pop_front() { + eprintln!("Drained pending event: {:?}", std::mem::discriminant(&event)); + } + + // Immediately drain and deliver server packets + let initial_out = drain_dimpl_outputs(&mut dimpl_server); + for packet in &initial_out.packets { + // Drain before each receive + wolf_client.drain_pending_data(&mut wolf_events); + match wolf_client.handle_receive(packet, &mut wolf_events) { + Ok(()) => (), + Err(e) => eprintln!("handle_receive error: {:?}", e), + } + } + + let mut client_received: Vec = Vec::new(); + let mut server_received: Vec = Vec::new(); + + // Collect events from initial delivery + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + client_received.extend_from_slice(&data); + } + } + + for _ in 0..100 { + // Client -> Server: drain WolfSSL output first + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + // Process server and get outputs + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for data in server_out.app_data { + server_received.extend_from_slice(&data); + } + + // Drain any pending events from previous iteration + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + client_received.extend_from_slice(&data); + } + } + + // Server -> Client + for packet in &server_out.packets { + let _ = wolf_client.handle_receive(packet, &mut wolf_events); + } + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + client_received.extend_from_slice(&data); + } + } + + if !client_received.is_empty() && !server_received.is_empty() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!(client_received, server_data, "Client should receive server data"); + assert_eq!(server_received, client_data, "Server should receive client data"); +} +*/ + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_multiple_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + if server_out.connected && wolf_client.is_connected() { + wolf_events.clear(); + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send multiple messages from WolfSSL client + let messages = vec![ + b"Message 1".to_vec(), + b"Message 2".to_vec(), + b"Message 3 is a bit longer".to_vec(), + b"Message 4".to_vec(), + b"Message 5 - the final one".to_vec(), + ]; + + let mut server_received: Vec> = Vec::new(); + + for msg in &messages { + wolf_client.write(msg).expect("client write"); + + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for data in server_out.app_data { + server_received.push(data); + } + } + + let expected: Vec = messages.iter().flatten().copied().collect(); + let total_received: Vec = server_received.iter().flatten().copied().collect(); + assert_eq!(total_received, expected, "All messages should be received"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_handshake_after_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + let mut drop_next_server_packet = true; + + for i in 0..60 { + dimpl_server.handle_timeout(now).expect("server timeout"); + + // Always deliver client packets to server + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + dimpl_server.handle_timeout(now).expect("server timeout"); + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + // Drop first server packet (drop server->client) + for packet in &server_out.packets { + if drop_next_server_packet && !server_out.packets.is_empty() { + drop_next_server_packet = false; + continue; + } + let _ = wolf_client.handle_receive(packet, &mut wolf_events); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + // Trigger server retransmissions + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + server_connected, + "Server should connect despite packet loss" + ); + assert!( + client_connected, + "Client should connect despite packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_handshake_with_early_packet_loss() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + // Use more retries for lossy conditions + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build DTLS 1.3 config"), + ); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + // Drop first 3 server packets to test retransmission recovery + let mut packets_to_drop = 3; + + for i in 0..60 { + let _ = dimpl_server.handle_timeout(now); + + // Always deliver client packets to server + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + // Drain fresh server output before processing another timeout tick; + // otherwise a retransmit can race the newly processed WolfSSL client flight. + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + // Drop first N server packets, then deliver all + for packet in &server_out.packets { + if packets_to_drop > 0 { + packets_to_drop -= 1; + } else { + let _ = wolf_client.handle_receive(packet, &mut wolf_events); + } + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(10); + } + } + + assert!( + server_connected, + "Server should connect despite early packet loss" + ); + assert!( + client_connected, + "Client should connect despite early packet loss" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_handles_duplicates() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + + // Send client packets twice (duplicates) + let mut client_packets = Vec::new(); + while let Some(packet) = wolf_client.poll_datagram() { + client_packets.push(packet); + } + for packet in &client_packets { + let _ = dimpl_server.handle_packet(packet); + let _ = dimpl_server.handle_packet(packet); // Duplicate + } + + dimpl_server.handle_timeout(now).expect("server timeout"); + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + // Send server packets twice too + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .unwrap(); + wolf_client + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(server_connected, "Server should connect despite duplicates"); + assert!(client_connected, "Client should connect despite duplicates"); +} + +// NOTE: This test is skipped because WolfSSL doesn't recover well from corruption +// during handshake - the corrupted server packet causes the handshake to stall +// without proper retransmission from the WolfSSL client side. +// The client-wolfssl tests verify corruption recovery from dimpl's perspective. +/* +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_recovers_from_corruption() { + // ... test body omitted - see original server-wolfssl.rs ... +} +*/ + +// NOTE: This test is skipped because WolfSSL's wrapper has issues with +// receiving large fragmented data - error -441 "Application data is available" +// occurs after receiving partial data. The client-wolfssl tests verify +// large data handling from dimpl's perspective. +/* +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_large_data_fragmented() { + // ... test body omitted - see original server-wolfssl.rs ... +} +*/ + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_many_small_messages() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + if server_out.connected && wolf_client.is_connected() { + wolf_events.clear(); + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + // Send many small messages from WolfSSL client + let message_count = 100; + for i in 0..message_count { + let msg = format!("M{}", i); + wolf_client.write(msg.as_bytes()).expect("send"); + } + + let mut received_bytes: Vec = Vec::new(); + + for _ in 0..100 { + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for data in server_out.app_data { + received_bytes.extend_from_slice(&data); + } + + now += Duration::from_millis(10); + } + + assert!( + !received_bytes.is_empty(), + "Should receive application data" + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_bidirectional_data() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + // Complete handshake + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .unwrap(); + } + if server_out.connected && wolf_client.is_connected() { + wolf_events.clear(); + break; + } + wolf_events.clear(); + now += Duration::from_millis(10); + } + + assert!( + wolf_client.is_connected(), + "WolfSSL client should be connected" + ); + + // Send data in both directions. WolfSSL client has a quirk (error -441 + // "Application data is available for reading") that can cause handle_receive + // to fail, so we tolerate errors and use drain_pending_data to flush state. + let server_data = b"Hello from dimpl server!"; + let client_data = b"Hello from WolfSSL client!"; + + dimpl_server + .send_application_data(server_data) + .expect("server send"); + wolf_client.write(client_data).expect("client write"); + + let mut client_received: Vec = Vec::new(); + let mut server_received: Vec = Vec::new(); + + for _ in 0..50 { + // WolfSSL client -> dimpl server + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + dimpl_server.handle_timeout(now).expect("server timeout"); + let server_out = drain_dimpl_outputs(&mut dimpl_server); + for data in server_out.app_data { + server_received.extend_from_slice(&data); + } + + // dimpl server -> WolfSSL client + // Drain pending data first to avoid -441 error + wolf_client.drain_pending_data(&mut wolf_events); + for packet in &server_out.packets { + let _ = wolf_client.handle_receive(packet, &mut wolf_events); + } + wolf_client.drain_pending_data(&mut wolf_events); + + while let Some(event) = wolf_events.pop_front() { + if let DtlsEvent::Data(data) = event { + client_received.extend_from_slice(&data); + } + } + + if !client_received.is_empty() && !server_received.is_empty() { + break; + } + + now += Duration::from_millis(10); + } + + assert_eq!( + server_received, client_data, + "dimpl server should receive data from WolfSSL client" + ); + assert_eq!( + client_received, server_data, + "WolfSSL client should receive data from dimpl server" + ); +} + +// NOTE: HRR (HelloRetryRequest) test is skipped because in the current WolfSSL interop +// setup, WolfSSL accepts all key-share groups dimpl offers. There is no way to configure +// the dimpl client to offer an initial key share that WolfSSL rejects (to trigger HRR) +// while still being able to complete the handshake. HRR is tested separately in the +// dimpl-only tests. +#[test] +#[ignore = "cannot trigger HRR: WolfSSL accepts all groups dimpl offers"] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_client_hrr_flow() { + // Cannot trigger HRR with the current WolfSSL + dimpl configuration: + // WolfSSL accepts the groups dimpl offers in this test setup. +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_small_mtu() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + // Use 600 MTU - large enough for handshake but smaller than default + let config = dtls13_config_with_mtu(600); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + let mut max_server_packet_size = 0usize; + + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + dimpl_server.handle_timeout(now).expect("server timeout"); + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + for p in &server_out.packets { + if p.len() > max_server_packet_size { + max_server_packet_size = p.len(); + } + } + + for packet in &server_out.packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .expect("wolf client handle receive"); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!(server_connected, "Server should connect with small MTU"); + assert!(client_connected, "Client should connect with small MTU"); + // Only check that dimpl server respects MTU (WolfSSL may not) + assert!( + max_server_packet_size <= 600, + "Server packets should respect MTU: max was {}", + max_server_packet_size + ); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_recovers_from_corruption() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = Arc::new( + Config::builder() + .flight_retries(8) + .build() + .expect("Failed to build DTLS 1.3 config"), + ); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + let mut corrupted_once = false; + + for i in 0..60 { + let _ = dimpl_server.handle_timeout(now); + + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + let _ = dimpl_server.handle_timeout(now); + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + // Corrupt one packet from dimpl server before delivering to WolfSSL client + for mut p in server_out.packets { + if !corrupted_once && p.len() > 20 { + p[15] ^= 0xFF; + p[16] ^= 0xFF; + corrupted_once = true; + } + let _ = wolf_client.handle_receive(&p, &mut wolf_events); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + // Trigger retransmissions periodically + if i % 5 == 4 { + now += Duration::from_secs(2); + } else { + now += Duration::from_millis(50); + } + } + + assert!(server_connected, "Server should connect despite corruption"); + assert!(client_connected, "Client should connect despite corruption"); +} + +#[test] +#[cfg(feature = "rcgen")] +fn dtls13_wolfssl_server_handles_out_of_order() { + use dimpl::certificate::generate_self_signed_certificate; + + let _ = env_logger::try_init(); + + let server_cert = generate_self_signed_certificate().expect("gen server cert"); + let client_dimpl_cert = generate_self_signed_certificate().expect("gen client cert"); + + let wolf_client_cert = WolfDtlsCert::new( + client_dimpl_cert.certificate.clone(), + client_dimpl_cert.private_key.clone(), + ); + + let mut wolf_client = wolf_client_cert + .new_dtls13_impl(false) + .expect("Failed to create WolfSSL client"); + + wolf_client.initiate().expect("initiate wolf client"); + + let config = dtls13_config(); + let now = Instant::now(); + let mut dimpl_server = Dtls::new_13(config, server_cert, now); + dimpl_server.set_active(false); + + let mut now = Instant::now(); + let mut wolf_events = VecDeque::new(); + + let mut client_connected = false; + let mut server_connected = false; + + for _ in 0..50 { + dimpl_server.handle_timeout(now).expect("server timeout"); + + while let Some(packet) = wolf_client.poll_datagram() { + let _ = dimpl_server.handle_packet(&packet); + } + + dimpl_server.handle_timeout(now).expect("server timeout"); + + let server_out = drain_dimpl_outputs(&mut dimpl_server); + if server_out.connected { + server_connected = true; + } + + // Reverse order of dimpl server's packets before delivering to WolfSSL client + let mut packets = server_out.packets; + packets.reverse(); + for packet in &packets { + wolf_client + .handle_receive(packet, &mut wolf_events) + .expect("wolf client handle receive"); + } + + while let Some(event) = wolf_events.pop_front() { + if matches!(event, DtlsEvent::Connected) { + client_connected = true; + } + } + + if client_connected && server_connected { + break; + } + + now += Duration::from_millis(10); + } + + assert!( + server_connected, + "Server should connect despite out-of-order delivery" + ); + assert!( + client_connected, + "Client should connect despite out-of-order delivery" + ); +} diff --git a/third_party/dimpl/tests/dtls13_cookie.rs b/third_party/dimpl/tests/dtls13_cookie.rs new file mode 100644 index 0000000..27421d2 --- /dev/null +++ b/third_party/dimpl/tests/dtls13_cookie.rs @@ -0,0 +1,357 @@ +#![cfg(any(feature = "aws-lc-rs", feature = "rust-crypto"))] + +#[path = "dtls13/common.rs"] +mod common; + +#[path = "ossl/mod.rs"] +mod ossl_helper; + +#[cfg(not(windows))] +#[path = "wolfssl/mod.rs"] +mod wolfssl_helper; + +use std::sync::Arc; +use std::time::Instant; + +use dimpl::{Dtls, DtlsCertificate}; + +use crate::common::{drain_outputs, dtls13_config}; +use crate::ossl_helper::{DtlsCertOptions, OsslDtlsCert}; + +fn certificate() -> DtlsCertificate { + let cert = OsslDtlsCert::new(DtlsCertOptions::default()); + DtlsCertificate { + certificate: cert.x509.to_der().expect("certificate DER"), + private_key: cert.pkey.private_key_to_pkcs8().expect("private key DER"), + } +} + +fn cookie_extensions_start(body: &[u8], msg_type: u8) -> Option { + let mut pos = 0; + match msg_type { + 0x01 => { + pos += 2 + 32; + let sid_len = *body.get(pos)? as usize; + pos += 1 + sid_len; + let cookie_len = *body.get(pos)? as usize; + pos += 1 + cookie_len; + let suites_len = u16::from_be_bytes([*body.get(pos)?, *body.get(pos + 1)?]) as usize; + pos += 2 + suites_len; + let compression_len = *body.get(pos)? as usize; + pos += 1 + compression_len; + } + 0x02 => { + pos += 2 + 32; + let sid_len = *body.get(pos)? as usize; + pos += 1 + sid_len + 2 + 1; + } + _ => return None, + } + + Some(pos) +} + +fn shrink_dtls13_cookie_extension_inner_len(packet: &mut [u8]) -> bool { + const RECORD_HEADER_LEN: usize = 13; + const HANDSHAKE_HEADER_LEN: usize = 12; + const COOKIE_EXTENSION: u16 = 0x002C; + + if packet.len() < RECORD_HEADER_LEN + HANDSHAKE_HEADER_LEN || packet[0] != 22 { + return false; + } + + let handshake = &mut packet[RECORD_HEADER_LEN..]; + let msg_type = handshake[0]; + let body_len = + ((handshake[1] as usize) << 16) | ((handshake[2] as usize) << 8) | handshake[3] as usize; + if handshake.len() < HANDSHAKE_HEADER_LEN + body_len { + return false; + } + + let body = &mut handshake[HANDSHAKE_HEADER_LEN..HANDSHAKE_HEADER_LEN + body_len]; + let mut pos = match cookie_extensions_start(body, msg_type) { + Some(pos) => pos, + None => return false, + }; + if body.len() < pos + 2 { + return false; + } + + let extensions_len = u16::from_be_bytes([body[pos], body[pos + 1]]) as usize; + pos += 2; + let extensions_end = pos + extensions_len; + if body.len() < extensions_end { + return false; + } + + while pos + 4 <= extensions_end { + let extension_type = u16::from_be_bytes([body[pos], body[pos + 1]]); + let extension_len = u16::from_be_bytes([body[pos + 2], body[pos + 3]]) as usize; + let extension_body = pos + 4; + let next = extension_body + extension_len; + if next > extensions_end { + return false; + } + + if extension_type == COOKIE_EXTENSION && extension_len > 2 { + let cookie_len = u16::from_be_bytes([body[extension_body], body[extension_body + 1]]); + if cookie_len == 0 { + return false; + } + body[extension_body..extension_body + 2] + .copy_from_slice(&(cookie_len - 1).to_be_bytes()); + return true; + } + + pos = next; + } + + false +} + +#[test] +fn dtls13_client_rejects_hrr_cookie_extension_trailing_bytes() { + let _ = env_logger::try_init(); + + let client_cert = certificate(); + let server_cert = certificate(); + let config = dtls13_config(); + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + assert!(!client_out.packets.is_empty(), "client should send CH1"); + for packet in &client_out.packets { + server.handle_packet(packet).expect("server receives CH1"); + } + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + let mut hrr = server_out + .packets + .into_iter() + .next() + .expect("server should emit HRR"); + assert!( + shrink_dtls13_cookie_extension_inner_len(&mut hrr), + "fixture should contain a Cookie extension" + ); + + client + .handle_packet(&hrr) + .expect("malformed HRR Cookie extension should be discarded"); + + client + .handle_timeout(now) + .expect("client timeout after error"); + let client_out = drain_outputs(&mut client); + assert!( + client_out.packets.is_empty(), + "client must not send CH2 after malformed HRR Cookie" + ); +} + +#[test] +fn dtls13_server_rejects_clienthello_cookie_extension_trailing_bytes() { + let _ = env_logger::try_init(); + + let client_cert = certificate(); + let server_cert = certificate(); + let config = dtls13_config(); + let now = Instant::now(); + + let mut client = Dtls::new_13(Arc::clone(&config), client_cert, now); + client.set_active(true); + + let mut server = Dtls::new_13(config, server_cert, now); + server.set_active(false); + + client.handle_timeout(now).expect("client timeout"); + let client_out = drain_outputs(&mut client); + for packet in &client_out.packets { + server.handle_packet(packet).expect("server receives CH1"); + } + + server.handle_timeout(now).expect("server timeout"); + let server_out = drain_outputs(&mut server); + let hrr = server_out + .packets + .first() + .expect("server should emit HRR") + .clone(); + client + .handle_packet(&hrr) + .expect("client receives valid HRR"); + + client + .handle_timeout(now) + .expect("client timeout after HRR"); + let client_out = drain_outputs(&mut client); + let mut ch2 = client_out + .packets + .into_iter() + .next() + .expect("client should emit CH2 with cookie"); + assert!( + shrink_dtls13_cookie_extension_inner_len(&mut ch2), + "fixture should contain a Cookie extension" + ); + + server + .handle_packet(&ch2) + .expect("malformed ClientHello Cookie extension should be discarded"); +} + +#[test] +fn dtls13_cookie_only_retry_preserves_key_share() { + const COOKIE: u16 = 44; + const KEY_SHARE: u16 = 51; + + let config = dtls13_config(); + let now = Instant::now(); + let mut client = Dtls::new_13(Arc::clone(&config), certificate(), now); + client.set_active(true); + let mut server = Dtls::new_13(config, certificate(), now); + server.set_active(false); + server.handle_timeout(now).expect("start server"); + assert!(drain_outputs(&mut server).packets.is_empty()); + + client.handle_timeout(now).expect("send CH1"); + let ch1 = drain_outputs(&mut client).packets; + assert_eq!(ch1.len(), 1); + let key_share = hello_extension(&ch1[0], 1, KEY_SHARE).expect("CH1 key_share"); + + server.handle_packet(&ch1[0]).expect("receive CH1"); + let hrr = drain_outputs(&mut server).packets; + assert_eq!(hrr.len(), 1); + let cookie = hello_extension(&hrr[0], 2, COOKIE).expect("HRR cookie"); + assert!( + hello_extension(&hrr[0], 2, KEY_SHARE).is_none(), + "cookie-only HRR" + ); + + client.handle_packet(&hrr[0]).expect("receive HRR"); + let ch2 = drain_outputs(&mut client).packets; + assert_eq!(ch2.len(), 1); + assert_eq!(hello_extension(&ch2[0], 1, COOKIE), Some(cookie)); + assert_eq!(hello_extension(&ch2[0], 1, KEY_SHARE), Some(key_share)); +} + +fn hello_extension(packet: &[u8], message_type: u8, extension_type: u16) -> Option<&[u8]> { + assert_eq!(packet[0], 22); + assert_eq!(&packet[3..5], &[0, 0]); + assert_eq!(packet[13], message_type); + assert_eq!(&packet[19..22], &[0, 0, 0]); + assert_eq!(&packet[14..17], &packet[22..25]); + let body = &packet[25..]; + let start = cookie_extensions_start(body, message_type).expect("hello extensions"); + let length = u16::from_be_bytes([body[start], body[start + 1]]) as usize; + let mut extensions = &body[start + 2..start + 2 + length]; + while !extensions.is_empty() { + let kind = u16::from_be_bytes([extensions[0], extensions[1]]); + let length = u16::from_be_bytes([extensions[2], extensions[3]]) as usize; + if kind == extension_type { + return Some(&extensions[4..4 + length]); + } + extensions = &extensions[4 + length..]; + } + None +} + +#[test] +#[cfg(not(windows))] +fn dtls13_wolfssl_cookie_only_retry_preserves_key_share() { + use std::collections::VecDeque; + use std::time::Duration; + + use crate::wolfssl_helper::WolfDtlsCert; + + const COOKIE: u16 = 44; + const KEY_SHARE: u16 = 51; + + let server_cert = certificate(); + let wolf_cert = WolfDtlsCert::new(server_cert.certificate, server_cert.private_key); + let mut server = wolf_cert.new_dtls13_impl(true).expect("wolfSSL server"); + let mut events = VecDeque::new(); + let mut now = Instant::now(); + let mut client = Dtls::new_13(dtls13_config(), certificate(), now); + client.set_active(true); + + client.handle_timeout(now).expect("send CH1"); + let ch1 = drain_outputs(&mut client).packets; + assert_eq!(ch1.len(), 1); + let key_share = hello_extension(&ch1[0], 1, KEY_SHARE).expect("CH1 key_share"); + server + .handle_receive(&ch1[0], &mut events) + .expect("receive CH1"); + + let hrr = server.poll_datagram().expect("wolfSSL HRR"); + let cookie = hello_extension(&hrr, 2, COOKIE).expect("HRR cookie"); + assert!( + hello_extension(&hrr, 2, KEY_SHARE).is_none(), + "cookie-only HRR" + ); + client.handle_packet(&hrr).expect("receive HRR"); + let ch2 = drain_outputs(&mut client).packets; + assert_eq!(ch2.len(), 1); + assert_eq!(hello_extension(&ch2[0], 1, COOKIE), Some(cookie)); + assert_eq!(hello_extension(&ch2[0], 1, KEY_SHARE), Some(key_share)); + server + .handle_receive(&ch2[0], &mut events) + .expect("receive CH2"); + + let mut connected = false; + for _ in 0..50 { + while let Some(packet) = server.poll_datagram() { + client + .handle_packet(&packet) + .expect("receive wolfSSL flight"); + let out = drain_outputs(&mut client); + connected |= out.connected; + for packet in out.packets { + server + .handle_receive(&packet, &mut events) + .expect("receive client flight"); + } + } + if connected && server.is_connected() { + break; + } + now += Duration::from_millis(10); + client.handle_timeout(now).expect("client timeout"); + let out = drain_outputs(&mut client); + connected |= out.connected; + for packet in out.packets { + server + .handle_receive(&packet, &mut events) + .expect("receive client retry"); + } + } + assert!(connected, "dimpl client connected"); + assert!(server.is_connected(), "wolfSSL server connected"); + + let payload = b"cookie retry interop"; + server.write(payload).expect("wolfSSL write"); + let mut received = Vec::new(); + while let Some(packet) = server.poll_datagram() { + client + .handle_packet(&packet) + .expect("receive encrypted data"); + let out = drain_outputs(&mut client); + for data in out.app_data { + received.extend_from_slice(&data); + } + for packet in out.packets { + server + .handle_receive(&packet, &mut events) + .expect("receive client ACK"); + } + } + assert_eq!(received, payload); +} diff --git a/third_party/dimpl/tests/ossl/cert.rs b/third_party/dimpl/tests/ossl/cert.rs new file mode 100644 index 0000000..af9721c --- /dev/null +++ b/third_party/dimpl/tests/ossl/cert.rs @@ -0,0 +1,187 @@ +use std::fmt; +use std::time::SystemTime; + +use openssl::asn1::{Asn1Integer, Asn1Time, Asn1Type}; +use openssl::bn::BigNum; +use openssl::ec::{EcGroup, EcKey}; +use openssl::hash::MessageDigest; +use openssl::nid::Nid; +use openssl::pkey::{PKey, Private}; +use openssl::rsa::Rsa; +use openssl::x509::{X509, X509Name}; + +use super::CryptoError; +use super::OsslDtlsImpl; + +const RSA_F4: u32 = 0x10001; + +/// Certificate used for DTLS. +#[derive(Debug, Clone)] +pub struct OsslDtlsCert { + pub pkey: PKey, + pub x509: X509, +} + +/// Defines the type of key pair to generate for the DTLS certificate. +#[derive(Clone, Debug, Default)] +pub enum DtlsPKeyType { + /// Generate an RSA key pair + Rsa2048, + /// Generate an EC-DSA key pair using the NIST P-256 curve + #[default] + EcDsaP256, + /// Generate an EC-DSA key pair using the NIST P-384 curve + EcDsaP384, +} + +/// Controls certificate generation options. +#[derive(Clone, Debug)] +pub struct DtlsCertOptions { + /// The common name for the certificate. + pub common_name: String, + /// The type of key to generate. + pub pkey_type: DtlsPKeyType, +} + +const DTLS_CERT_IDENTITY: &str = "WebRTC"; + +impl Default for DtlsCertOptions { + fn default() -> Self { + Self { + common_name: DTLS_CERT_IDENTITY.into(), + pkey_type: Default::default(), + } + } +} + +impl OsslDtlsCert { + /// Creates a new (self signed) DTLS certificate. + pub fn new(options: DtlsCertOptions) -> Self { + Self::self_signed(options).expect("create dtls cert") + } + + // The libWebRTC code we try to match is at: + // https://webrtc.googlesource.com/src/+/1568f1b1330f94494197696fe235094e6293b258/rtc_base/openssl_certificate.cc#58 + fn self_signed(options: DtlsCertOptions) -> Result { + let f4 = BigNum::from_u32(RSA_F4)?; + let pkey = match options.pkey_type { + DtlsPKeyType::Rsa2048 => { + let key = Rsa::generate_with_e(2048, &f4)?; + PKey::from_rsa(key)? + } + DtlsPKeyType::EcDsaP256 => { + let nid = Nid::X9_62_PRIME256V1; // NIST P-256 curve + let group = EcGroup::from_curve_name(nid)?; + let key = EcKey::generate(&group)?; + PKey::from_ec_key(key)? + } + DtlsPKeyType::EcDsaP384 => { + let nid = Nid::SECP384R1; + let group = EcGroup::from_curve_name(nid)?; + let key = EcKey::generate(&group)?; + PKey::from_ec_key(key)? + } + }; + + let mut x509b = X509::builder()?; + x509b.set_version(2)?; // X509.V3 (zero indexed) + + // For Firefox, the serial number must be unique across all certificates, including those of other + // processes/machines! See https://github.com/versatica/mediasoup/issues/127#issuecomment-474460153 + // and https://github.com/algesten/str0m/issues/517 + let mut serial_buf = [0u8; 16]; + openssl::rand::rand_bytes(&mut serial_buf)?; + + let serial_bn = BigNum::from_slice(&serial_buf)?; + let serial = Asn1Integer::from_bn(&serial_bn)?; + x509b.set_serial_number(&serial)?; + let before = Asn1Time::from_unix(unix_time() - 3600)?; + x509b.set_not_before(&before)?; + let after = Asn1Time::days_from_now(7)?; + x509b.set_not_after(&after)?; + x509b.set_pubkey(&pkey)?; + + // The libWebRTC code for this is: + // + // !X509_NAME_add_entry_by_NID(name.get(), NID_commonName, MBSTRING_UTF8, + // (unsigned char*)params.common_name.c_str(), -1, -1, 0) || + // + // libWebRTC allows this name to be configured by the user of the library. + // That's a future TODO for str0m. + let mut nameb = X509Name::builder()?; + nameb.append_entry_by_nid_with_type( + Nid::COMMONNAME, + options.common_name.as_str(), + Asn1Type::UTF8STRING, + )?; + + let name = nameb.build(); + + x509b.set_subject_name(&name)?; + x509b.set_issuer_name(&name)?; + + x509b.sign(&pkey, MessageDigest::sha256())?; + let x509 = x509b.build(); + + Ok(OsslDtlsCert { pkey, x509 }) + } + + /// Produce a (public) fingerprint of the cert. + /// + /// This is sent via SDP to the other peer to lock down the DTLS + /// to this specific certificate. + pub fn fingerprint(&self) -> Fingerprint { + let digest: &[u8] = &self + .x509 + .digest(MessageDigest::sha256()) + .expect("digest to fingerprint"); + + Fingerprint { + hash_func: "sha-256".into(), + bytes: digest.to_vec(), + } + } + + pub fn new_dtls_impl(&self) -> Result { + OsslDtlsImpl::new(self.clone()) + } + + pub fn new_dtls_impl_with_groups( + &self, + groups_list: &str, + ) -> Result { + OsslDtlsImpl::new_with_groups(self.clone(), Some(groups_list)) + } +} + +#[derive(Debug)] +pub struct Fingerprint { + pub hash_func: String, + pub bytes: Vec, +} + +impl fmt::Display for Fingerprint { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} ", self.hash_func)?; + for (i, b) in self.bytes.iter().enumerate() { + if i > 0 { + write!(f, ":")?; + } + write!(f, "{:02X}", b)?; + } + Ok(()) + } +} + +// TODO: Refactor away this use of System::now, to instead go via InstantExt +// and base the time on the first Instant. This would require lazy init of +// Dtls, or that we pass a first ever Instant into the creation of Rtc. +// +// This is not a super high priority since it's only used for setting a before +// time in the generated certificate, and one hour back from that. +pub fn unix_time() -> libc::time_t { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_secs() as libc::time_t +} diff --git a/third_party/dimpl/tests/ossl/dtls.rs b/third_party/dimpl/tests/ossl/dtls.rs new file mode 100644 index 0000000..d91a2c8 --- /dev/null +++ b/third_party/dimpl/tests/ossl/dtls.rs @@ -0,0 +1,206 @@ +use std::collections::VecDeque; +use std::io::{self, Read, Write}; +use std::time::{Duration, Instant}; + +use dimpl::SrtpProfile; +use openssl::dh::Dh; +use openssl::ssl::{Ssl, SslContext, SslContextBuilder, SslMethod, SslOptions, SslVerifyMode}; + +use super::cert::OsslDtlsCert; +use super::io_buf::IoBuffer; +use super::stream::TlsStream; +use super::{CryptoError, DATAGRAM_MTU, DATAGRAM_MTU_WARN, DtlsEvent}; + +// We restrict cipher suites to those that include ephemeral Diffie-Hellman or +// ephemeral Elliptic Curve Diffie-Hellman and modern AEAD ciphers. +const DTLS_CIPHERS: &str = + "ECDHE+CHACHA20:DHE+CHACHA20:ECDHE+AESGCM:DHE+AESGCM:ECDHE+AES256:DHE+AES256"; + +pub struct OsslDtlsImpl { + /// Certificate for the DTLS session. + _cert: OsslDtlsCert, + + /// Context belongs together with Fingerprint. + /// + /// This just needs to be kept alive since it pins the entire openssl context + /// from which `Ssl` is created. + _context: SslContext, + + /// The actual openssl TLS stream. + tls: TlsStream, +} + +impl OsslDtlsImpl { + pub fn new(cert: OsslDtlsCert) -> Result { + Self::new_with_groups(cert, None) + } + + pub fn new_with_groups( + cert: OsslDtlsCert, + groups_list: Option<&str>, + ) -> Result { + let context = dtls_create_ctx_with_groups(&cert, groups_list)?; + let ssl = dtls_ssl_create(&context)?; + Ok(OsslDtlsImpl { + _cert: cert, + _context: context, + tls: TlsStream::new(ssl, IoBuffer::default()), + }) + } +} + +impl OsslDtlsImpl { + pub fn set_active(&mut self, active: bool) { + self.tls.set_active(active); + } + + pub fn is_active(&self) -> Option { + self.tls.is_active() + } + + pub fn handle_receive( + &mut self, + m: &[u8], + o: &mut VecDeque, + ) -> Result<(), CryptoError> { + self.tls.inner_mut().set_incoming(m); + + if self.handle_handshake(o)? { + // early return as long as we're handshaking + return Ok(()); + } + + let mut buf = vec![0; 2000]; + let n = match self.tls.read(&mut buf) { + Ok(v) => v, + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + return Ok(()); + } + Err(e) => return Err(e.into()), + }; + buf.truncate(n); + + o.push_back(DtlsEvent::Data(buf)); + + Ok(()) + } + + pub fn poll_datagram(&mut self) -> Option { + let x = self.tls.inner_mut().pop_outgoing(); + if let Some(x) = &x { + if x.len() > DATAGRAM_MTU_WARN { + eprintln!("DTLS above MTU {}: {}", DATAGRAM_MTU_WARN, x.len()); + } + } + x + } + + pub fn poll_timeout(&mut self, now: Instant) -> Option { + // OpenSSL has a built-in timeout of 1 second that is doubled for + // each retry. There is a way to get direct control over the + // timeout (using DTLS_set_timer_cb), but that function doesn't + // appear to be exposed in openssl crate yet. + // TODO(martin): Write PR for openssl crate to be able to use this + // callback to make a tighter timeout handling here. + self.tls + .is_handshaking() + .then(|| now + Duration::from_millis(500)) + } + + pub fn handle_input(&mut self, data: &[u8]) -> Result<(), CryptoError> { + Ok(self.tls.write_all(data)?) + } + + pub fn is_connected(&self) -> bool { + self.tls.is_connected() + } + + pub fn handle_handshake( + &mut self, + output: &mut VecDeque, + ) -> Result { + if self.tls.is_connected() { + // Nice. Nothing to do. + Ok(false) + } else if self.tls.complete_handshake_until_block()? { + output.push_back(DtlsEvent::Connected); + + let (keying_material, srtp_profile, fingerprint) = self + .tls + .take_srtp_keying_material() + .expect("Exported keying material"); + + output.push_back(DtlsEvent::RemoteFingerprint(fingerprint)); + + output.push_back(DtlsEvent::SrtpKeyingMaterial(keying_material, srtp_profile)); + Ok(false) + } else { + Ok(true) + } + } +} + +pub fn dtls_create_ctx(cert: &OsslDtlsCert) -> Result { + dtls_create_ctx_with_groups(cert, None) +} + +pub fn dtls_create_ctx_with_groups( + cert: &OsslDtlsCert, + groups_list: Option<&str>, +) -> Result { + // TODO: Technically we want to disallow DTLS < 1.2, but that requires + // us to use this commented out unsafe. We depend on browsers disallowing + // it instead. + // let method = unsafe { SslMethod::from_ptr(DTLSv1_2_method()) }; + let mut ctx = SslContextBuilder::new(SslMethod::dtls())?; + + ctx.set_cipher_list(DTLS_CIPHERS)?; + if let Some(groups) = groups_list { + ctx.set_groups_list(groups)?; + } + let srtp_profiles = { + // Rust can't join directly to a string, need to allocate a vec first :( + // This happens very rarely so the extra allocations don't matter + let all: Vec<_> = SrtpProfile::ALL.iter().map(openssl_name).collect(); + + all.join(":") + }; + ctx.set_tlsext_use_srtp(&srtp_profiles)?; + + let mut mode = SslVerifyMode::empty(); + mode.insert(SslVerifyMode::PEER); + mode.insert(SslVerifyMode::FAIL_IF_NO_PEER_CERT); + ctx.set_verify_callback(mode, |_ok, _ctx| true); + + ctx.set_private_key(&cert.pkey)?; + ctx.set_certificate(&cert.x509)?; + + let mut options = SslOptions::empty(); + options.insert(SslOptions::SINGLE_ECDH_USE); + options.insert(SslOptions::NO_DTLSV1); + ctx.set_options(options); + + // Enable DHE cipher suites by setting temporary DH parameters + if let Ok(dh) = Dh::get_2048_256() { + ctx.set_tmp_dh(dh.as_ref())?; + } + + let ctx = ctx.build(); + + Ok(ctx) +} + +fn openssl_name(profile: &SrtpProfile) -> &'static str { + match profile { + SrtpProfile::AES128_CM_SHA1_80 => "SRTP_AES128_CM_SHA1_80", + SrtpProfile::AEAD_AES_128_GCM => "SRTP_AEAD_AES_128_GCM", + SrtpProfile::AEAD_AES_256_GCM => "SRTP_AEAD_AES_256_GCM", + _ => unreachable!(), + } +} + +pub fn dtls_ssl_create(ctx: &SslContext) -> Result { + let mut ssl = Ssl::new(ctx)?; + ssl.set_mtu(DATAGRAM_MTU as u32)?; + Ok(ssl) +} diff --git a/third_party/dimpl/tests/ossl/io_buf.rs b/third_party/dimpl/tests/ossl/io_buf.rs new file mode 100644 index 0000000..f84daea --- /dev/null +++ b/third_party/dimpl/tests/ossl/io_buf.rs @@ -0,0 +1,83 @@ +use std::collections::VecDeque; +use std::io; +use std::ops::Deref; + +/// A wrapper for some payload that is to be sent. +#[derive(Debug)] +pub struct DatagramSend(Vec); + +impl Deref for DatagramSend { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +#[derive(Default, Debug)] +pub struct IoBuffer { + pub incoming: Vec, + pub outgoing: VecDeque, +} + +impl IoBuffer { + pub(crate) fn set_incoming(&mut self, buf: &[u8]) { + self.incoming.extend_from_slice(buf); + + // Each packet ought to be ~MTU 1400. If openssl is + // not consuming all incoming data, we got some problem. + assert!( + self.incoming.len() < 30_000, + "Incoming DTLS data is not being consumed" + ); + } + + pub(crate) fn pop_outgoing(&mut self) -> Option { + self.outgoing.pop_front() + } +} + +impl io::Read for IoBuffer { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let n = self.incoming.len(); + + if n == 0 { + return Err(io::Error::new(io::ErrorKind::WouldBlock, "WouldBlock")); + } + + let max = buf.len().min(n); + + buf[..max].copy_from_slice(&self.incoming[..max]); + + if max == self.incoming.len() { + // The typical case is that the entire input is consumed at once, + // which means the happy path is cheap. + self.incoming.truncate(0); + } else { + // Shifting data inside a vector is not good. This should be rare. + self.incoming.drain(..max); + } + + Ok(n) + } +} + +impl io::Write for IoBuffer { + fn write(&mut self, buf: &[u8]) -> io::Result { + let dsend = buf.to_vec().into(); + + self.outgoing.push_back(dsend); + + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl From> for DatagramSend { + fn from(v: Vec) -> Self { + DatagramSend(v) + } +} diff --git a/third_party/dimpl/tests/ossl/mod.rs b/third_party/dimpl/tests/ossl/mod.rs new file mode 100644 index 0000000..56bc60e --- /dev/null +++ b/third_party/dimpl/tests/ossl/mod.rs @@ -0,0 +1,64 @@ +#![allow(unused)] + +//! OpenSSL implementation of cryptographic functions. + +/// Errors that can arise in DTLS. +#[derive(Debug)] +pub enum CryptoError { + /// Some error from OpenSSL layer (used for DTLS). + OpenSsl(openssl::error::ErrorStack), + + /// Other IO errors. + Io(io::Error), +} + +impl From for CryptoError { + fn from(value: openssl::error::ErrorStack) -> Self { + CryptoError::OpenSsl(value) + } +} + +impl From for CryptoError { + fn from(value: io::Error) -> Self { + CryptoError::Io(value) + } +} + +mod cert; +use std::io; + +pub use cert::{DtlsCertOptions, DtlsPKeyType, Fingerprint, OsslDtlsCert}; + +pub mod io_buf; +mod stream; + +mod dtls; +use dimpl::SrtpProfile; +pub use dtls::{OsslDtlsImpl, dtls_ssl_create}; + +pub use io_buf::DatagramSend; +use std::collections::VecDeque; + +/// Targeted MTU +pub(crate) const DATAGRAM_MTU: usize = 1150; + +/// Warn if any packet we are about to send is above this size. +pub(crate) const DATAGRAM_MTU_WARN: usize = 1280; + +/// Events arising from a [`Dtls`] instance. +#[derive(Debug)] +pub enum DtlsEvent { + /// When the DTLS has finished handshaking. + Connected, + + /// Keying material for SRTP encryption master key and the selected SRTP profile. + SrtpKeyingMaterial(Vec, SrtpProfile), + + /// The fingerprint of the remote peer. + /// + /// This should be checked against the fingerprint communicated in the SDP. + RemoteFingerprint(Fingerprint), + + /// Decrypted data from incoming DTLS traffic. + Data(Vec), +} diff --git a/third_party/dimpl/tests/ossl/stream.rs b/third_party/dimpl/tests/ossl/stream.rs new file mode 100644 index 0000000..ff9a9c5 --- /dev/null +++ b/third_party/dimpl/tests/ossl/stream.rs @@ -0,0 +1,219 @@ +use std::panic::UnwindSafe; +use std::{io, mem}; + +use openssl::hash::MessageDigest; +use openssl::srtp::SrtpProfileId; +use openssl::ssl::{HandshakeError, MidHandshakeSslStream, Ssl, SslStream}; + +use super::{CryptoError, Fingerprint, SrtpProfile}; + +const DTLS_KEY_LABEL: &str = "EXTRACTOR-dtls_srtp"; + +pub struct TlsStream { + active: Option, + state: State, + keying_mat: Option<(Vec, SrtpProfile, Fingerprint)>, + exported: bool, +} + +pub enum State { + Init(Ssl, S), + Handshaking(MidHandshakeSslStream), + Established(SslStream), + Empty, +} + +/// This is okay because there is no way for a user of Rtc to interact with the Dtls subsystem +/// in a way that would allow them to observe a potentially broken invariant when catching a panic. +impl UnwindSafe for State {} + +impl TlsStream +where + S: io::Read + io::Write + UnwindSafe, +{ + pub fn new(ssl: Ssl, stream: S) -> Self { + TlsStream { + active: None, + state: State::Init(ssl, stream), + keying_mat: None, + exported: false, + } + } + + pub fn is_active(&self) -> Option { + self.active + } + + pub fn set_active(&mut self, active: bool) { + assert!( + self.active.is_none(), + "set_active should called exactly once" + ); + self.active = Some(active); + } + + pub fn complete_handshake_until_block(&mut self) -> Result { + if let Err(e) = self.handshaken() { + if e.kind() == io::ErrorKind::WouldBlock { + Ok(false) + } else { + Err(e.into()) + } + } else { + Ok(true) + } + } + + pub fn is_handshaking(&self) -> bool { + matches!(self.state, State::Init(_, _) | State::Handshaking(_)) + } + + pub fn is_connected(&self) -> bool { + matches!(self.state, State::Established(_)) + } + + pub fn handshaken(&mut self) -> Result<&mut SslStream, io::Error> { + let active = self.is_active().expect("set_active must be called"); + let v = self.state.handshaken(active)?; + + // first time we complete the handshake, we extract the keying material for SRTP. + if !self.exported { + let keying_mat = export_srtp_keying_material(v)?; + self.exported = true; + self.keying_mat = Some(keying_mat); + } + + Ok(v) + } + + pub fn take_srtp_keying_material(&mut self) -> Option<(Vec, SrtpProfile, Fingerprint)> { + self.keying_mat.take() + } + + pub fn inner_mut(&mut self) -> &mut S { + match &mut self.state { + State::Init(_, s) => s, + State::Handshaking(v) => v.get_mut(), + State::Established(v) => v.get_mut(), + State::Empty => panic!("inner_mut on empty dtls state"), + } + } +} + +impl State +where + S: io::Read + io::Write + UnwindSafe, +{ + fn handshaken(&mut self, active: bool) -> Result<&mut SslStream, io::Error> { + if let State::Established(v) = self { + return Ok(v); + } + + let taken = mem::replace(self, State::Empty); + + let result = match taken { + State::Empty | State::Established(_) => unreachable!(), + State::Init(ssl, stream) => { + if active { + println!("ossl Connect"); + ssl.connect(stream) + } else { + println!("ossl Accept"); + ssl.accept(stream) + } + } + State::Handshaking(mid) => mid.handshake(), + }; + + match result { + Ok(v) => { + println!("ossl Established version: {:}", v.ssl().version_str()); + + let _ = mem::replace(self, State::Established(v)); + + // recursively return the &mut SslStream. + self.handshaken(active) + } + Err(e) => Err(match e { + HandshakeError::WouldBlock(e) => { + let _ = mem::replace(self, State::Handshaking(e)); + io::Error::new(io::ErrorKind::WouldBlock, "WouldBlock") + } + HandshakeError::SetupFailure(e) => { + println!("ossl DTLS setup failed: {:?}", e); + io::Error::new(io::ErrorKind::InvalidInput, e) + } + HandshakeError::Failure(e) => { + let e = e.into_error(); + println!("ossl DTLS failure: {:?}", e); + io::Error::new(io::ErrorKind::InvalidData, e) + } + }), + } + } +} + +fn export_srtp_keying_material( + stream: &mut SslStream, +) -> Result<(Vec, SrtpProfile, Fingerprint), io::Error> { + let ssl = stream.ssl(); + + // remote peer certificate fingerprint + let x509 = ssl + .peer_certificate() + .ok_or_else(|| io::Error::other("No remote X509 cert"))?; + let digest: &[u8] = &x509.digest(MessageDigest::sha256())?; + + let fp = Fingerprint { + hash_func: "sha-256".into(), + bytes: digest.to_vec(), + }; + + let srtp_profile_id = ssl + .selected_srtp_profile() + .map(|s| s.id()) + .ok_or_else(|| io::Error::other("Failed to negotiate SRTP profile"))?; + + let srtp_profile = srtp_profile_from_id(srtp_profile_id)?; + + // extract SRTP keying material + let mut buf = vec![0_u8; srtp_profile.keying_material_len()]; + ssl.export_keying_material(&mut buf, DTLS_KEY_LABEL, None)?; + + Ok((buf, srtp_profile, fp)) +} + +impl io::Read for TlsStream +where + S: io::Read + io::Write + UnwindSafe, +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.handshaken()?.read(buf) + } +} + +impl io::Write for TlsStream +where + S: io::Read + io::Write + UnwindSafe, +{ + fn write(&mut self, buf: &[u8]) -> io::Result { + self.handshaken()?.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.handshaken()?.flush() + } +} + +/// Convert SrtpProfileId to SrtpProfile +fn srtp_profile_from_id(value: SrtpProfileId) -> Result { + match value { + SrtpProfileId::SRTP_AES128_CM_SHA1_80 => Ok(SrtpProfile::AES128_CM_SHA1_80), + SrtpProfileId::SRTP_AEAD_AES_128_GCM => Ok(SrtpProfile::AEAD_AES_128_GCM), + SrtpProfileId::SRTP_AEAD_AES_256_GCM => Ok(SrtpProfile::AEAD_AES_256_GCM), + x => Err(io::Error::other(format!( + "Unsupported SRTP profile {:x}", + x.as_raw() + ))), + } +} diff --git a/third_party/dimpl/tests/wolfssl/mod.rs b/third_party/dimpl/tests/wolfssl/mod.rs new file mode 100644 index 0000000..6677d9a --- /dev/null +++ b/third_party/dimpl/tests/wolfssl/mod.rs @@ -0,0 +1,291 @@ +#![allow(unused)] + +//! WolfSSL DTLS 1.3 implementation for interop testing. + +use std::cell::RefCell; +use std::collections::VecDeque; + +use bytes::BytesMut; +use wolfssl::ContextBuilder; +use wolfssl::IOCallbackResult; +use wolfssl::IOCallbacks; +use wolfssl::Method; +use wolfssl::Poll; +use wolfssl::RootCertificate; +use wolfssl::Secret; +use wolfssl::Session; +use wolfssl::SessionConfig; +use wolfssl::SslVerifyMode; + +/// Errors that can arise in DTLS. +#[derive(Debug)] +pub enum WolfError { + /// Some error from WolfSSL layer. + Wolf(wolfssl::Error), + /// Context builder error. + ContextBuilder(wolfssl::NewContextBuilderError), + /// Session error. + Session(wolfssl::NewSessionError), +} + +impl From for WolfError { + fn from(value: wolfssl::Error) -> Self { + WolfError::Wolf(value) + } +} + +impl From for WolfError { + fn from(value: wolfssl::NewContextBuilderError) -> Self { + WolfError::ContextBuilder(value) + } +} + +impl From for WolfError { + fn from(value: wolfssl::NewSessionError) -> Self { + WolfError::Session(value) + } +} + +/// Events arising from a [`WolfDtlsImpl`] instance. +#[derive(Debug)] +pub enum DtlsEvent { + /// When the DTLS has finished handshaking. + Connected, + + /// Application data received. + Data(Vec), +} + +/// IO buffer that allows pushing/popping datagrams for non-blocking I/O. +#[derive(Default)] +pub struct IoBuffer { + /// Incoming data (received from network). + incoming: RefCell>>, + /// Outgoing data (to send to network). + outgoing: RefCell>>, +} + +impl IoBuffer { + pub fn new() -> Self { + Self::default() + } + + /// Push incoming data (simulating receiving from network). + pub fn set_incoming(&self, data: &[u8]) { + self.incoming.borrow_mut().push_back(data.to_vec()); + } + + /// Pop outgoing data (to send to network). + pub fn pop_outgoing(&self) -> Option> { + self.outgoing.borrow_mut().pop_front() + } +} + +impl IOCallbacks for IoBuffer { + fn recv(&mut self, buf: &mut [u8]) -> IOCallbackResult { + let mut incoming = self.incoming.borrow_mut(); + if let Some(data) = incoming.pop_front() { + let n = std::cmp::min(buf.len(), data.len()); + buf[..n].copy_from_slice(&data[..n]); + IOCallbackResult::Ok(n) + } else { + IOCallbackResult::WouldBlock + } + } + + fn send(&mut self, buf: &[u8]) -> IOCallbackResult { + self.outgoing.borrow_mut().push_back(buf.to_vec()); + IOCallbackResult::Ok(buf.len()) + } +} + +/// DTLS 1.3 certificate and key for WolfSSL. +pub struct WolfDtlsCert { + /// DER-encoded certificate. + pub cert_der: Vec, + /// DER-encoded private key. + pub key_der: Vec, +} + +impl WolfDtlsCert { + /// Create a new WolfSSL DTLS certificate from DER-encoded cert and key. + pub fn new(cert_der: Vec, key_der: Vec) -> Self { + Self { cert_der, key_der } + } + + /// Create a DTLS 1.3 implementation from this certificate. + pub fn new_dtls13_impl(&self, is_server: bool) -> Result { + WolfDtlsImpl::new(self, is_server) + } +} + +/// WolfSSL DTLS 1.3 implementation wrapper. +pub struct WolfDtlsImpl { + session: Session, + is_connected: bool, +} + +impl WolfDtlsImpl { + /// Create a new WolfSSL DTLS 1.3 session. + pub fn new(cert: &WolfDtlsCert, is_server: bool) -> Result { + let method = if is_server { + Method::DtlsServerV1_3 + } else { + Method::DtlsClientV1_3 + }; + + let ctx = ContextBuilder::new(method)? + .with_certificate(Secret::Asn1Buffer(&cert.cert_der))? + .with_private_key(Secret::Asn1Buffer(&cert.key_der))? + .build(); + + let io = IoBuffer::new(); + let session_config = SessionConfig::new(io) + .with_dtls_nonblocking(true) + .with_ssl_verify_mode(SslVerifyMode::SslVerifyNone); + + let session = ctx.new_session(session_config)?; + + Ok(Self { + session, + is_connected: false, + }) + } + + /// Check if the session is connected. + pub fn is_connected(&self) -> bool { + self.is_connected + } + + /// Handle received data from the network. + pub fn handle_receive( + &mut self, + data: &[u8], + events: &mut VecDeque, + ) -> Result<(), WolfError> { + // First, try to read any pending application data before processing new input + if self.is_connected { + loop { + let mut buf = BytesMut::with_capacity(2048); + match self.session.try_read(&mut buf) { + Ok(Poll::Ready(n)) if n > 0 => { + events.push_back(DtlsEvent::Data(buf[..n].to_vec())); + } + Ok(Poll::PendingRead | Poll::PendingWrite) => break, + Ok(Poll::Ready(_)) => break, + Ok(Poll::AppData(data)) => { + events.push_back(DtlsEvent::Data(data.to_vec())); + } + Err(_) => break, // Ignore errors when draining + } + } + } + + // Push data to the IO buffer + self.session.io_cb_mut().set_incoming(data); + + // Try to progress the handshake or read data + if !self.is_connected { + self.handle_handshake(events)?; + } else { + // Try to read all available application data + loop { + let mut buf = BytesMut::with_capacity(2048); + match self.session.try_read(&mut buf) { + Ok(Poll::Ready(n)) if n > 0 => { + events.push_back(DtlsEvent::Data(buf[..n].to_vec())); + } + Ok(Poll::PendingRead | Poll::PendingWrite) => break, + Ok(Poll::Ready(_)) => break, + Ok(Poll::AppData(data)) => { + events.push_back(DtlsEvent::Data(data.to_vec())); + } + Err(e) => return Err(e.into()), + } + } + } + + Ok(()) + } + + /// Try to progress the handshake. + /// + /// Loops `try_negotiate` until wolfssl returns `PendingRead` (needs peer + /// data) so that the full server flight (ServerHello + encrypted records) + /// is flushed in one call rather than requiring an extra round-trip. + fn handle_handshake(&mut self, events: &mut VecDeque) -> Result<(), WolfError> { + loop { + match self.session.try_negotiate() { + Ok(Poll::Ready(())) => { + self.is_connected = true; + events.push_back(DtlsEvent::Connected); + break; + } + Ok(Poll::PendingRead) => { + // wolfssl needs more data from the peer — stop looping. + if self.session.is_init_finished() && !self.is_connected { + self.is_connected = true; + events.push_back(DtlsEvent::Connected); + } + break; + } + Ok(Poll::PendingWrite) => { + // wolfssl has more data to produce — keep going. + if self.session.is_init_finished() && !self.is_connected { + self.is_connected = true; + events.push_back(DtlsEvent::Connected); + break; + } + } + Ok(Poll::AppData(data)) => { + events.push_back(DtlsEvent::Data(data.to_vec())); + } + Err(e) => return Err(e.into()), + } + } + Ok(()) + } + + /// Poll for outgoing datagrams. + pub fn poll_datagram(&mut self) -> Option> { + self.session.io_cb_mut().pop_outgoing() + } + + /// Drain any pending application data (call before handle_receive if needed) + pub fn drain_pending_data(&mut self, events: &mut VecDeque) { + if !self.is_connected { + return; + } + loop { + let mut buf = BytesMut::with_capacity(2048); + match self.session.try_read(&mut buf) { + Ok(Poll::Ready(n)) if n > 0 => { + events.push_back(DtlsEvent::Data(buf[..n].to_vec())); + } + Ok(Poll::AppData(data)) => { + events.push_back(DtlsEvent::Data(data.to_vec())); + } + _ => break, + } + } + } + + /// Write application data. + pub fn write(&mut self, data: &[u8]) -> Result<(), WolfError> { + let mut buf = BytesMut::from(data); + match self.session.try_write(&mut buf) { + Ok(Poll::Ready(_)) => Ok(()), + Ok(Poll::PendingRead | Poll::PendingWrite) => Ok(()), + Ok(Poll::AppData(_)) => Ok(()), + Err(e) => Err(WolfError::Wolf(e)), + } + } + + /// Drive the handshake forward (call after setting up, for client). + pub fn initiate(&mut self) -> Result<(), WolfError> { + match self.session.try_negotiate() { + Ok(_) => Ok(()), + Err(e) => Err(e.into()), + } + } +}