Vendor dimpl 0.7.4 unmodified and patch it in from third_party

str0m's DTLS stack (dimpl) hard-codes the SRTP profile a DTLS server picks
(AES-256-GCM first), with no way to configure it. Official TeamSpeak 6
clients use AES_CM_128_HMAC_SHA1_80, so we need to patch dimpl. This commit
only vendors the crate as published and routes crates.io's dimpl to it;
the change follows separately so it can be reviewed and dropped on its own.

third_party is excluded from the workspace so dimpl's dev-dependencies and
tests stay out of our builds, and own-crates.sh skips it like crates/proto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-26 23:27:21 +00:00
1 parent 3aba9a165d
commit ce7c833aa8
152 files changed
+56138 -5

No files matched your search

Generated
-2
View File
@@ -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",
+8 -1
View File
@@ -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" }
+2 -2
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env bash
# Print `-p <crate>` 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' ' '
+2
View File
@@ -0,0 +1,2 @@
[env]
MACOSX_DEPLOYMENT_TARGET = "11.0"
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "09bf3fc89c3cdb06030a90e8e1043983c791e2b6"
},
"path_in_vcs": ""
}
+85
View File
@@ -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
+101
View File
@@ -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}}"
+55
View File
@@ -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 }}/
+2
View File
@@ -0,0 +1,2 @@
/target
.wt
+8
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
{
"rust-analyzer.showUnlinkedFileNotification": false
}
+130
View File
@@ -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
+175
View File
@@ -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
+130
View File
@@ -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
+1742
View File
File diff suppressed because it is too large. Load diff
+247
View File
@@ -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 <martin@algesten.se>"]
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"
+88
View File
@@ -0,0 +1,88 @@
[package]
name = "dimpl"
authors = ["Martin Algesten <martin@algesten.se>"]
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"
+201
View File
@@ -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.
+7
View File
@@ -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.
+214
View File
@@ -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<u8>), Timer(Instant) }
fn wait_next_event(_next_wake: Option<Instant>) -> 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<Instant> = 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<Vec<u8>> {
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
+32
View File
@@ -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.
+29
View File
@@ -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
+6
View File
@@ -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"]
+68
View File
@@ -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)
]
+662
View File
@@ -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<dyn ActiveKeyExchange>,
/// 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<Config>) -> Result<Self, Error> {
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<u16, 16> = 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<NamedGroup, 4> = 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::<usize>();
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<Config>,
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<Instant>,
/// How many retransmits have occurred.
retransmit_count: usize,
}
impl ClientPending {
pub fn new(
config: Arc<Config>,
certificate: DtlsCertificate,
now: Instant,
) -> Result<Self, Error> {
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<Config>, 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<DetectedVersion> {
// 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<u16> {
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<Vec<u8>> {
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"
);
}
}
+220
View File
@@ -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<u8>` 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<Buf>,
}
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<u8>` that provides convenient access to byte buffers
/// and integrates with dimpl's buffer pooling system.
#[derive(Default)]
pub struct Buf(Vec<u8>);
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<u8>`.
pub fn into_vec(mut self) -> Vec<u8> {
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<T: IntoIterator<Item = &'a u8>>(&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<u8> {
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);
}
}
+184
View File
@@ -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<DtlsCertificate, CertificateError> {
// 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::<String>::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<u8> {
// 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::<Vec<String>>()
.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<u8> {
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());
}
}
}
+1020
View File
File diff suppressed because it is too large. Load diff
+458
View File
@@ -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<Self, CryptoError> {
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<Self, CryptoError> {
// 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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()
);
}
}
+48
View File
@@ -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<dyn HashContext> {
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;
+40
View File
@@ -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<hmac::Algorithm, CryptoError> {
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<usize, CryptoError> {
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;
+159
View File
@@ -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<Self, CryptoError> {
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<Self>, 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<Box<dyn ActiveKeyExchange>, 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<Box<dyn ActiveKeyExchange>, 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<Box<dyn ActiveKeyExchange>, 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))
);
}
}
+120
View File
@@ -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,
}
}
+20
View File
@@ -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;
+295
View File
@@ -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<Box<dyn SigningKey>, 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,
}
);
}
}
+88
View File
@@ -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::Aes128, U8, U12>;
/// AES-128-CCM-8 cipher for TLS_PSK_WITH_AES_128_CCM_8.
pub struct AesCcm8Cipher {
cipher: Box<Aes128Ccm8>,
}
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<Self, CryptoError> {
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(())
}
}
+207
View File
@@ -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<usize> {
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<u8, 13>);
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());
}
}
+71
View File
@@ -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<u8>);
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"),
}
}
}
+62
View File
@@ -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
}
}
+538
View File
@@ -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<u8>;
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<Vec<u8>, 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<u8> {
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());
}
}
+665
View File
@@ -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<Self, CryptoError> {
//! 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<Box<dyn Cipher>, 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<T: Send + Sync + Debug + UnwindSafe + RefUnwindSafe> 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<Self>, 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<Box<dyn Cipher>, 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<Box<dyn ActiveKeyExchange>, 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<NamedGroup, CertificateError> {
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<Box<dyn SigningKey>, 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<dyn HashContext>;
}
/// 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<usize, CryptoError>;
}
// ============================================================================
// 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<Box<dyn Cipher>, 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, <zero bytes>)`.
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<CryptoProvider> = 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::<String>::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::<String>::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());
}
}
+482
View File
@@ -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<Aes128Gcm>),
Aes256(Box<Aes256Gcm>),
}
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<Self, CryptoError> {
match key.len() {
16 => {
let key = Key::<Aes128Gcm>::from_slice(key);
Ok(AesGcm::Aes128(Box::new(Aes128Gcm::new(key))))
}
32 => {
let key = Key::<Aes256Gcm>::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<u8, U12>
use generic_array::{GenericArray, typenum::U12};
let aes_nonce = GenericArray::<u8, U12>::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<u8, U12>
use generic_array::{GenericArray, typenum::U12};
let aes_nonce = GenericArray::<u8, U12>::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<u8, U12>
use generic_array::{GenericArray, typenum::U12};
let aes_nonce = GenericArray::<u8, U12>::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<u8, U12>
use generic_array::{GenericArray, typenum::U12};
let aes_nonce = GenericArray::<u8, U12>::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<ChaCha20Poly1305Aead>,
}
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<Self, CryptoError> {
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::<u8, U12>::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::<u8, U12>::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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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<Box<dyn Cipher>, 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()
);
}
}
+69
View File
@@ -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<dyn HashContext> {
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;
+47
View File
@@ -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<usize, CryptoError> {
match hash {
HashAlgorithm::SHA256 => {
let mut mac = Hmac::<Sha256>::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::<Sha384>::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;
+209
View File
@@ -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<Self, CryptoError> {
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<Self>, 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<Box<dyn ActiveKeyExchange>, 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<Box<dyn ActiveKeyExchange>, 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<Box<dyn ActiveKeyExchange>, 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))
);
}
}
+102
View File
@@ -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,
}
}
+20
View File
@@ -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;
+329
View File
@@ -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<NistP256>),
P384(SigningKey<NistP384>),
}
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<NistP256> = 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<NistP384> = 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<Box<dyn SigningKeyTrait>, CryptoError> {
// Try PKCS#8 DER format first (most common)
if let Ok(key) = SigningKey::<NistP256>::from_pkcs8_der(key_der) {
return Ok(Box::new(EcdsaSigningKey::P256(key)));
}
if let Ok(key) = SigningKey::<NistP384>::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::<NistP256>::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::<NistP384>::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::<NistP256>::from_sec1_bytes(pubkey_bytes)
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp256r1))?;
let sig = Signature::<NistP256>::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::<NistP384>::from_sec1_bytes(pubkey_bytes)
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp384r1))?;
let sig = Signature::<NistP384>::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,
}
);
}
}
+761
View File
@@ -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<Item = &'static dyn SupportedDtls12CipherSuite> {
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<Item = &'static dyn SupportedKxGroup> {
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<Item = &'static dyn SupportedDtls12CipherSuite> {
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<Vec<HashAlgorithm>, Error> {
// Collect unique hash algorithms from supported cipher suites
let required_hashes: Vec<HashAlgorithm> = 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));
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
0d0uçhI¶»Û³I‚Ôà)<ݽм�ò#¼ºšzu¹•Ö|™)¤ý ëh¦ÏÛØã^djÒE08{ Aõ™ôÙ Ñìíé½Ìíðì¹]²™e¦=î(HºzDl‚�¢«„J␍hó
+1
View File
@@ -0,0 +1 @@
test data for signature validation
File diff suppressed because it is too large. Load diff
+696
View File
@@ -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<crate::Config>,
/// Key exchange mechanism
key_exchange: Option<Box<dyn crypto::ActiveKeyExchange>>,
/// Our public key from the key exchange (stored for reuse)
key_exchange_public_key: Option<Vec<u8>>,
/// Group info from the key exchange (stored for reuse)
key_exchange_group: Option<NamedGroup>,
/// Client write key
client_write_key: Option<Buf>,
/// Server write key
server_write_key: Option<Buf>,
/// Client write IV (4 bytes for AES-GCM, 12 bytes for ChaCha20-Poly1305)
client_write_iv: Option<Iv>,
/// Server write IV (4 bytes for AES-GCM, 12 bytes for ChaCha20-Poly1305)
server_write_iv: Option<Iv>,
/// Client MAC key (not used for AEAD ciphers)
client_mac_key: Option<Buf>,
/// Server MAC key (not used for AEAD ciphers)
server_mac_key: Option<Buf>,
/// Master secret
master_secret: Option<ArrayVec<u8, 128>>,
/// Pre-master secret (temporary)
pre_master_secret: Option<Buf>,
/// Client cipher
client_cipher: Option<Box<dyn crypto::Cipher>>,
/// Server cipher
server_cipher: Option<Box<dyn crypto::Cipher>>,
/// Authentication mode: certificate or PSK.
auth: AuthMode,
/// Resolved PSK value (set during handshake after identity exchange)
psk: Option<Vec<u8>>,
/// Client random (needed for SRTP key export per RFC 5705)
client_random: Option<ArrayVec<u8, 32>>,
/// Server random (needed for SRTP key export per RFC 5705)
server_random: Option<ArrayVec<u8, 32>>,
}
/// Authentication mode for a DTLS 1.2 session.
pub enum AuthMode {
/// Certificate-based authentication (ECDHE_ECDSA suites).
Certificate {
/// DER-encoded certificate.
certificate: Vec<u8>,
/// Parsed signing key for the certificate.
private_key: Box<dyn crypto::SigningKey>,
},
/// 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<crate::Config>) -> 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<u8>) {
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<ArrayVec<u8, 128>, 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<ArrayVec<u8, 88>, 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::<u8, 64>::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<SignatureAlgorithm> {
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<HashAlgorithm> {
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<dyn crypto::HashContext> {
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<Iv> {
self.client_write_iv
}
/// Get the server write IV if derived.
pub fn get_server_write_iv(&self) -> Option<Iv> {
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"
);
}
}
File diff suppressed because it is too large. Load diff
+485
View File
@@ -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<Records>,
}
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<Item = Record> {
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<Dtls12CipherSuite>,
) -> Result<Option<Self>, 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<Record, 8>,
}
impl Records {
pub fn parse(
mut packet: &[u8],
decrypt: &mut dyn RecordHandler,
cs: Option<Dtls12CipherSuite>,
) -> Result<Records, InternalError> {
let mut parsed_records: ArrayVec<Record, 8> = 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<ParsedRecord>,
}
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<Dtls12CipherSuite>,
) -> Result<Option<Record>, 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<Handshake, 8>,
handled: AtomicBool,
}
impl ParsedRecord {
pub fn parse(
input: &[u8],
cipher_suite: Option<Dtls12CipherSuite>,
offset: usize,
) -> Result<ParsedRecord, InternalError> {
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<Option<Record>, 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<Dtls12CipherSuite>,
) -> ArrayVec<Handshake, 8> {
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<Option<Record>, 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<u8> {
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);
}
}
+104
View File
@@ -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<Asn1Cert, 32>,
}
impl Certificate {
pub fn new(certificate_list: ArrayVec<Asn1Cert, 32>) -> 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"
);
}
}
@@ -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<DistinguishedName, 32>,
}
impl CertificateRequest {
pub fn new(
certificate_types: CertificateTypeVec,
supported_signature_algorithms: SignatureAndHashAlgorithmVec,
certificate_authorities: ArrayVec<DistinguishedName, 32>,
) -> 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"
);
}
}
@@ -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);
}
}
+352
View File
@@ -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"
);
}
}
}
@@ -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<usize>,
}
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<usize>,
}
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());
}
}
View File
Whitespace-only changes.
@@ -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<usize>,
}
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);
}
}
+249
View File
@@ -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<Extension, { ExtensionType::supported().len() }>;
#[derive(Debug, PartialEq, Eq, Default)]
pub struct Extension {
pub extension_type: ExtensionType,
pub extension_data_range: Range<usize>,
}
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::<ExtensionType>(), 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);
}
}
@@ -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<ECPointFormat, 3>,
}
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,
..
}))
));
}
}
@@ -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;
@@ -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"
);
}
}
@@ -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"
);
}
}
@@ -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<SrtpProfileId, { SrtpProfileId::supported().len() }>;
/// 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<SrtpProfile> 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<SrtpProfileId> 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<u8, 255>, // MKI value (usually empty)
}
impl UseSrtpExtension {
pub fn new(profiles: SrtpProfileVec, mki: ArrayVec<u8, 255>) -> 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::<u8, 255>::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,
..
})
));
}
}
+64
View File
@@ -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<usize>,
}
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[..]);
}
}
+836
View File
@@ -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<Dtls12CipherSuite>,
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<Item = (&'b Handshake, &'b [u8])>,
buffer: &mut Buf,
cipher_suite: Option<Dtls12CipherSuite>,
transcript: Option<&mut Buf>,
) -> Result<Handshake, crate::InternalError> {
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<Item = Handshake> + '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<u16> {
// 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<usize>),
Finished(Finished),
Unknown(u8),
Fragment(Range<usize>),
}
impl Default for Body {
fn default() -> Self {
Self::Unknown(0)
}
}
impl Body {
pub fn parse(
input: &[u8],
base_offset: usize,
m: MessageType,
c: Option<Dtls12CipherSuite>,
) -> 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::<MessageType>(), 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());
}
}
+93
View File
@@ -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());
}
}
+128
View File
@@ -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<Self, InvalidLength> {
#[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, Self::Error> {
Self::try_new(value)
}
}
impl<'a> TryFrom<&'a str> for $name {
type Error = InvalidLength;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
Self::try_new(value.as_bytes())
}
}
};
}
var_array!(SessionId, 0, 32);
var_array!(Cookie, 0, 255);
+465
View File
@@ -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<Dtls12CipherSuite, { Dtls12CipherSuite::supported().len() }>;
/// 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<SignatureAlgorithm> {
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<CompressionMethod, { CompressionMethod::supported().len() }>;
#[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<ClientCertificateType, { ClientCertificateType::supported().len() }>;
#[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<SignatureAndHashAlgorithm, { SignatureAndHashAlgorithm::supported().len() }>;
#[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::<Dtls12CipherSuite>(), 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::<ClientCertificateType>(), 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())
);
}
}
+94
View File
@@ -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::<CurveType>(), 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)");
}
}
+258
View File
@@ -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<usize>,
}
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<usize> = 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<u8> {
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+"
);
}
}
+256
View File
@@ -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<ExtensionVec>,
}
impl ServerHello {
pub fn new(
server_version: ProtocolVersion,
random: Random,
session_id: SessionId,
cipher_suite: Dtls12CipherSuite,
compression_method: CompressionMethod,
extensions: Option<ExtensionVec>,
) -> 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<SrtpProfileId>) -> 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"
);
}
}
}
@@ -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<usize>,
pub signature: Option<DigitallySigned>,
}
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<usize>,
}
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());
}
}
+40
View File
@@ -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<usize>);
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);
+38
View File
@@ -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;
+118
View File
@@ -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<Incoming>);
impl QueueRx {
pub fn new() -> Self {
Self(VecDeque::new())
}
}
impl Deref for QueueRx {
type Target = VecDeque<Incoming>;
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<Buf>);
impl QueueTx {
pub fn new() -> Self {
Self(VecDeque::new())
}
}
impl Deref for QueueTx {
type Target = VecDeque<Buf>;
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()
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+633
View File
@@ -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<Records>,
}
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<Item = Record> {
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<Dtls13CipherSuite>,
) -> Result<Option<Self>, 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<Record, 16>,
}
impl Records {
pub fn parse(
mut packet: &[u8],
decrypt: &mut dyn RecordHandler,
cs: Option<Dtls13CipherSuite>,
) -> Result<Records, InternalError> {
let mut parsed_records: ArrayVec<Record, 16> = 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<ParsedRecord>,
}
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<Dtls13CipherSuite>,
) -> Result<Option<Record>, 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<Handshake, 8>,
handled: AtomicBool,
}
impl ParsedRecord {
pub fn parse(
input: &[u8],
cipher_suite: Option<Dtls13CipherSuite>,
) -> Result<ParsedRecord, InternalError> {
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<Dtls13CipherSuite>,
) -> 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<Option<Record>, 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<Dtls13CipherSuite>,
) -> ArrayVec<Handshake, 8> {
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<Option<Record>, 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<u8> {
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<u8> {
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);
}
}
+158
View File
@@ -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<usize>,
}
/// TLS 1.3 Certificate message (RFC 8446 Section 4.4.2).
#[derive(Debug, PartialEq, Eq)]
pub struct Certificate {
pub context_range: Range<usize>,
pub certificate_list: ArrayVec<CertificateEntry, 32>,
}
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"
);
}
}
@@ -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);
}
}
+385
View File
@@ -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<Dtls13CipherSuite, 3>,
pub legacy_compression_methods: ArrayVec<CompressionMethod, 1>,
pub extensions: ArrayVec<Extension, 8>,
}
impl ClientHello {
pub fn new(
legacy_version: ProtocolVersion,
random: Random,
legacy_session_id: SessionId,
legacy_cookie: Cookie,
cipher_suites: ArrayVec<Dtls13CipherSuite, 3>,
legacy_compression_methods: ArrayVec<CompressionMethod, 1>,
) -> 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<Extension, 8>> {
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"
);
}
}
@@ -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<usize>,
}
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);
}
}
@@ -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<Extension, 5>,
}
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"
);
}
}
+244
View File
@@ -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<usize>,
}
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::<ExtensionType>(), 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);
}
}
@@ -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]);
}
}
@@ -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<usize>,
}
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<KeyShareEntry, { NamedGroup::supported().len() }>,
}
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"
);
}
}
@@ -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;
@@ -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<SignatureScheme, 2>,
}
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<SignatureScheme, 2> = 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<SignatureScheme, 2> = 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"
);
}
}
@@ -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<NamedGroup, 4>,
}
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<NamedGroup, 4> = 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"
);
}
}
@@ -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<ProtocolVersion, 3>,
}
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"
);
}
}
@@ -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<SrtpProfile> 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<SrtpProfileId> 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<SrtpProfileId, 3>,
pub mki: ArrayVec<u8, 255>, // MKI value (usually empty)
}
impl UseSrtpExtension {
pub fn new(profiles: ArrayVec<SrtpProfileId, 3>, mki: ArrayVec<u8, 255>) -> 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<SrtpProfileId, 3> = 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::<u8, 255>::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,
..
})
));
}
}
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more