dimpl: configurable SRTP profile order

A DTLS 1.2 server in dimpl picks AES-256-GCM whenever the client offers it,
and there is no setting. Our str0m peers are the DTLS server for official
TeamSpeak 6 viewers, which offer all profiles, so our streams used GCM while
official streams use AES_CM_128_HMAC_SHA1_80.

ConfigBuilder::srtp_profiles sets the profiles in order of preference: the
server picks the first of them the client offered, clients offer them in
that order and reject a server that picks another. Unset, everything is as
upstream. VOELIN-PATCH.md describes the patch and how to drop it.

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:36:41 +00:00
1 parent ce7c833aa8
commit 37d52bc604
14 files changed
+448 -32

No files matched your search

+1 -1
View File
@@ -91,7 +91,7 @@ debug = "line-tables-only"
[profile.dev.package."*"]
debug = false
# dimpl (DTLS for str0m), vendored to be patched; see
# dimpl (DTLS for str0m) with a configurable SRTP profile order; see
# third_party/dimpl/VOELIN-PATCH.md.
[patch.crates-io]
dimpl = { path = "third_party/dimpl" }
+4
View File
@@ -245,3 +245,7 @@ version = "0.18"
[target."cfg(not(windows))".dev-dependencies.wolfssl]
version = "7.2.0"
# Voelin: a workspace of its own, so its tests run from this directory
# (see VOELIN-PATCH.md).
[workspace]
+59 -6
View File
@@ -13,20 +13,73 @@ 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.
`scripts/own-crates.sh` leaves it out of the strict fmt/clippy checks. The
manifest keeps upstream's `license`, so cargo-deny and cargo-about treat it
like the crates.io crate.
The first commit that added this directory is the unmodified crate as
published (the `.crate` contents, `Cargo.toml` normalized by crates.io,
The 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.
## The patch: SRTP profile order
Upstream, a DTLS 1.2 server picks the SRTP protection profile (RFC 5764) in a
fixed order, AEAD_AES_256_GCM, AEAD_AES_128_GCM, then AES128_CM_SHA1_80, and
a client always offers all three; there is no setting. In TeamSpeak 6
streams our str0m peer is the DTLS server, and the official clients
(libwebrtc) offer all three, so our streams ended up with AES-256-GCM, while
streams between official clients use AES_CM_128_HMAC_SHA1_80. The patch:
- `ConfigBuilder::srtp_profiles(&[SrtpProfile])`: the profiles in order of
preference (duplicates dropped; an empty list is `ConfigError::NoSrtpProfiles`).
`Config::srtp_profiles()` returns it, or `SrtpProfile::ALL` when unset.
- `Config::select_srtp_profile(offered)`: the first configured profile the
client offered. The DTLS 1.2 server uses it; with the default list that is
exactly upstream's fixed order. The DTLS 1.3 server uses it when a list was
configured, otherwise it keeps upstream's choice (the client's order).
- Clients (DTLS 1.2, 1.3 and the auto/hybrid ClientHello) offer the configured
profiles in their order (`UseSrtpExtension::from_profiles`); by default
that is upstream's offer. A client rejects a server that selects a profile
it did not offer (`SecurityError::ServerSelectedUnofferedSrtpProfile`, as
RFC 5764 requires; with the default offer any profile dimpl parses was
offered, so nothing changes there).
- `[workspace]` at the end of `Cargo.toml`, so the crate's tests run from this
directory even inside another workspace's tree (e.g. a git worktree under
the repository).
- Unit tests: `config::tests::srtp_profiles_*`,
`use_srtp::tests::from_profiles_keeps_order`, and `srtp_profile_order` in
`src/lib.rs` (full DTLS 1.2/1.3 handshakes: the server's order wins over a
browser-like GCM-first offer; unset, the result is upstream's).
`voelin-stream` (`crates/voelin-stream/src/dtls.rs`) builds its dimpl
configurations with the order from `PeerConfig::srtp_profiles`.
## Dropping the patch
Once upstream dimpl can configure the SRTP profiles (and str0m either passes
such a setting through or lets `voelin-stream` keep building its own dimpl
`Config` as it does now): switch `crates/voelin-stream/src/dtls.rs` to the
upstream API, remove the `[patch.crates-io]` entry and `"third_party"` from
`exclude` in the root `Cargo.toml` if nothing else is vendored, delete this
directory, and run `cargo update -p dimpl` so `Cargo.lock` points at
crates.io again. `scripts/notices.sh --check` and `cargo deny check` should
pass unchanged.
To update the vendored version instead: copy the new release from
`~/.cargo/registry/src/*/dimpl-<version>` in a commit of its own (plus the
`[workspace]` table), re-apply the changes above, and `cargo update -p dimpl`.
## Running its tests
From this directory (its own workspace; it has its own `Cargo.lock`):
From this directory (its own workspace with its own `Cargo.lock`):
```sh
cargo test --lib
cargo test --locked --lib # unit tests, including the patch's
cargo test --locked # plus upstream's OpenSSL/wolfSSL interop tests
```
The upstream dev-dependencies (OpenSSL vendored, wolfSSL) are built for
that, so the first run takes a few minutes.
that, so the first run takes a few minutes. Do not run `cargo fmt` here: our
`rustfmt.toml` would reformat the crate; format changed files with an empty
rustfmt config (`rustfmt --edition 2024 --config-path <empty dir> <files>`).
+1 -1
View File
@@ -168,7 +168,7 @@ impl HybridClientHello {
// 5. use_srtp
let start = ext_buf.len();
let use_srtp = UseSrtpExtension::default();
let use_srtp = UseSrtpExtension::from_profiles(config.srtp_profiles());
use_srtp.serialize(&mut ext_buf);
ext_entries.push((EXT_USE_SRTP, start, ext_buf.len()));
+125 -1
View File
@@ -3,7 +3,7 @@ use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::Arc;
use std::time::Duration;
use crate::crypto::{CryptoProvider, SupportedDtls12CipherSuite};
use crate::crypto::{CryptoProvider, SrtpProfile, SupportedDtls12CipherSuite};
use crate::crypto::{SupportedDtls13CipherSuite, SupportedKxGroup};
use crate::dtls12::message::Dtls12CipherSuite;
use crate::types::{Dtls13CipherSuite, NamedGroup};
@@ -75,6 +75,7 @@ pub struct Config {
dtls12_cipher_suites: Option<Vec<Dtls12CipherSuite>>,
dtls13_cipher_suites: Option<Vec<Dtls13CipherSuite>>,
kx_groups: Option<Vec<NamedGroup>>,
srtp_profiles: Option<Vec<SrtpProfile>>,
psk: Option<Psk>,
}
@@ -96,6 +97,7 @@ impl Config {
dtls12_cipher_suites: None,
dtls13_cipher_suites: None,
kx_groups: None,
srtp_profiles: None,
psk: None,
}
}
@@ -285,6 +287,30 @@ impl Config {
None => true,
})
}
/// SRTP protection profiles in order of preference.
///
/// The list set with the builder's `srtp_profiles` method, or all
/// supported profiles in the order of [`SrtpProfile::ALL`].
pub fn srtp_profiles(&self) -> &[SrtpProfile] {
self.srtp_profiles.as_deref().unwrap_or(SrtpProfile::ALL)
}
/// The SRTP profile a server selects from the client's `offered`
/// profiles: the first of [`srtp_profiles`](Self::srtp_profiles) that
/// the client offered, whatever the client's order.
pub fn select_srtp_profile(&self, offered: &[SrtpProfile]) -> Option<SrtpProfile> {
self.srtp_profiles()
.iter()
.copied()
.find(|profile| offered.contains(profile))
}
/// Whether an SRTP profile order was configured. Without one, a DTLS 1.3
/// server keeps the client's order.
pub(crate) fn has_srtp_profile_order(&self) -> bool {
self.srtp_profiles.is_some()
}
}
/// Builder for [`Config`]. See each setter for defaults.
@@ -303,6 +329,7 @@ pub struct ConfigBuilder {
dtls12_cipher_suites: Option<Vec<Dtls12CipherSuite>>,
dtls13_cipher_suites: Option<Vec<Dtls13CipherSuite>>,
kx_groups: Option<Vec<NamedGroup>>,
srtp_profiles: Option<Vec<SrtpProfile>>,
psk: Option<Psk>,
}
@@ -452,6 +479,28 @@ impl ConfigBuilder {
self
}
/// Set the SRTP protection profiles (DTLS-SRTP, RFC 5764) in order of
/// preference.
///
/// A client offers these profiles in this order and rejects a server
/// that selects another one. A server selects the first of them that
/// the client offered, whatever the client's order (DTLS 1.2 and 1.3).
/// Duplicates are ignored; an empty list fails [`build`](Self::build).
///
/// By default all supported profiles are used in the order of
/// [`SrtpProfile::ALL`], and a DTLS 1.3 server selects the first
/// profile of the client's offer that it supports.
pub fn srtp_profiles(mut self, profiles: &[SrtpProfile]) -> Self {
let mut list: Vec<SrtpProfile> = Vec::with_capacity(profiles.len());
for profile in profiles {
if !list.contains(profile) {
list.push(*profile);
}
}
self.srtp_profiles = Some(list);
self
}
/// Configure PSK for a client endpoint.
///
/// The `identity` is sent to the server during the handshake.
@@ -518,6 +567,11 @@ impl ConfigBuilder {
return Err(Error::ConfigError(ConfigError::AeadEncryptionLimitTooSmall));
}
// Validate srtp_profiles: an empty list cannot be offered (RFC 5764)
if self.srtp_profiles.as_ref().is_some_and(Vec::is_empty) {
return Err(Error::ConfigError(ConfigError::NoSrtpProfiles));
}
// Validate cipher suite filters: at least one version must have suites.
// Mirror Config::dtls12_cipher_suites() by dropping PSK suites when no PSK
// is configured, so a PSK-only filter without a PSK resolver fails fast.
@@ -609,6 +663,7 @@ impl ConfigBuilder {
dtls12_cipher_suites: self.dtls12_cipher_suites,
dtls13_cipher_suites: self.dtls13_cipher_suites,
kx_groups: self.kx_groups,
srtp_profiles: self.srtp_profiles,
psk: self.psk,
})
}
@@ -659,6 +714,7 @@ impl fmt::Debug for Config {
.field("dtls12_cipher_suites", &self.dtls12_cipher_suites)
.field("dtls13_cipher_suites", &self.dtls13_cipher_suites)
.field("kx_groups", &self.kx_groups)
.field("srtp_profiles", &self.srtp_profiles)
.field("psk", &self.psk)
.finish()
}
@@ -684,6 +740,7 @@ impl fmt::Debug for ConfigBuilder {
.field("dtls12_cipher_suites", &self.dtls12_cipher_suites)
.field("dtls13_cipher_suites", &self.dtls13_cipher_suites)
.field("kx_groups", &self.kx_groups)
.field("srtp_profiles", &self.srtp_profiles)
.field("psk", &self.psk)
.finish()
}
@@ -995,6 +1052,73 @@ mod tests {
.expect("PSK-only client with empty kx_groups should build");
}
#[test]
fn srtp_profiles_default_order() {
let config = Config::default();
assert_eq!(config.srtp_profiles(), SrtpProfile::ALL);
assert!(!config.has_srtp_profile_order());
// Upstream's server preference: AES-256-GCM, AES-128-GCM, then SHA1.
let offered = [
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AEAD_AES_256_GCM,
];
assert_eq!(
config.select_srtp_profile(&offered),
Some(SrtpProfile::AEAD_AES_256_GCM)
);
assert_eq!(
config.select_srtp_profile(&offered[..2]),
Some(SrtpProfile::AEAD_AES_128_GCM)
);
assert_eq!(config.select_srtp_profile(&[]), None);
}
#[test]
fn srtp_profiles_configured_order() {
let config = Config::builder()
.srtp_profiles(&[
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AES128_CM_SHA1_80,
])
.build()
.expect("should accept an SRTP profile order");
assert!(config.has_srtp_profile_order());
assert_eq!(
config.srtp_profiles(),
&[
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_128_GCM
],
"duplicates are dropped"
);
// Our order wins over the client's (a browser offers GCM first).
let browser = [
SrtpProfile::AEAD_AES_256_GCM,
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AES128_CM_SHA1_80,
];
assert_eq!(
config.select_srtp_profile(&browser),
Some(SrtpProfile::AES128_CM_SHA1_80)
);
assert_eq!(
config.select_srtp_profile(&browser[..2]),
Some(SrtpProfile::AEAD_AES_128_GCM)
);
assert_eq!(config.select_srtp_profile(&browser[..1]), None);
}
#[test]
fn empty_srtp_profiles_rejected() {
match Config::builder().srtp_profiles(&[]).build() {
Err(Error::ConfigError(ConfigError::NoSrtpProfiles)) => {}
Err(other) => panic!("expected ConfigError, got: {other:?}"),
Ok(_) => panic!("expected error for an empty SRTP profile list"),
}
}
#[test]
fn filter_with_explicit_provider() {
#[cfg(feature = "aws-lc-rs")]
+8 -1
View File
@@ -524,7 +524,14 @@ impl State {
UseSrtpExtension::parse(extension_data).map_err(InternalError::from)?;
// Store the first profile as our negotiated profile
if !use_srtp.profiles.is_empty() {
client.negotiated_srtp_profile = Some(use_srtp.profiles[0].into());
let profile: SrtpProfile = use_srtp.profiles[0].into();
if !client.engine.config().srtp_profiles().contains(&profile) {
return Err(Error::SecurityError(
crate::SecurityError::ServerSelectedUnofferedSrtpProfile(profile),
)
.into());
}
client.negotiated_srtp_profile = Some(profile);
trace!(
"ServerHello UseSRTP extension processed; selected profile: {:?}",
client.negotiated_srtp_profile
+1 -1
View File
@@ -81,7 +81,7 @@ impl ClientHello {
ranges.push((ExtensionType::SignatureAlgorithms, start_pos, buf.len()));
// Add use_srtp extension for DTLS-SRTP support
let use_srtp = UseSrtpExtension::default();
let use_srtp = UseSrtpExtension::from_profiles(config.srtp_profiles());
let start_pos = buf.len();
use_srtp.serialize(buf);
ranges.push((ExtensionType::UseSrtp, start_pos, buf.len()));
@@ -87,7 +87,26 @@ impl UseSrtpExtension {
UseSrtpExtension { profiles, mki }
}
/// A UseSrtpExtension offering `profiles` in this order (duplicates
/// skipped).
pub fn from_profiles(profiles: &[SrtpProfile]) -> Self {
let mut ids = SrtpProfileVec::new();
for profile in profiles {
let id = SrtpProfileId::from(*profile);
if !ids.contains(&id) {
// At most one entry per profile, so this always fits.
let _ = ids.try_push(id);
}
}
UseSrtpExtension {
profiles: ids,
mki: ArrayVec::new(),
}
}
/// Create a default UseSrtpExtension with standard profiles
// Offers now come from Config::srtp_profiles (from_profiles).
#[allow(dead_code)]
pub fn default() -> Self {
let mut profiles = SrtpProfileVec::new();
// Add profiles in order of preference (most secure first)
@@ -206,6 +225,28 @@ mod tests {
assert_eq!(parsed.mki, mki);
}
#[test]
fn from_profiles_keeps_order() {
let ext = UseSrtpExtension::from_profiles(&[
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_256_GCM,
SrtpProfile::AES128_CM_SHA1_80,
]);
assert_eq!(
ext.profiles.as_slice(),
&[
SrtpProfileId::SRTP_AES128_CM_SHA1_80,
SrtpProfileId::SRTP_AEAD_AES_256_GCM
]
);
assert!(ext.mki.is_empty());
// The default offer is the default configuration's.
assert_eq!(
UseSrtpExtension::from_profiles(SrtpProfile::ALL),
UseSrtpExtension::default()
);
}
#[test]
fn test_use_srtp_parse_provided_bytes() {
// Provided bytes: [0,8,0,7,0,8,0,1,0,2,0]
+5 -13
View File
@@ -471,21 +471,13 @@ impl State {
.into());
}
// Select SRTP profile according to server priority: AES256GCM, AES128GCM, then SHA1
// Select SRTP profile according to server priority: the configured
// profiles (by default AES256GCM, AES128GCM, then SHA1)
if let Some(profiles) = client_srtp_profiles {
// Map client profile ids to SrtpProfile, then pick our preferred
let mut selected_profile: Option<SrtpProfile> = None;
for preferred in [
SrtpProfile::AEAD_AES_256_GCM,
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AES128_CM_SHA1_80,
] {
if profiles.iter().any(|pid| preferred == (*pid).into()) {
selected_profile = Some(preferred);
break;
}
}
server.negotiated_srtp_profile = selected_profile;
let offered: ArrayVec<SrtpProfile, { SrtpProfileId::supported().len() }> =
profiles.iter().map(|pid| (*pid).into()).collect();
server.negotiated_srtp_profile = server.engine.config().select_srtp_profile(&offered);
if let Some(profile) = server.negotiated_srtp_profile {
debug!("Negotiated SRTP profile: {:?}", profile);
}
+9 -2
View File
@@ -718,7 +718,14 @@ impl State {
let (_, use_srtp) =
UseSrtpExtension::parse(ext_data).map_err(InternalError::from)?;
if !use_srtp.profiles.is_empty() {
client.negotiated_srtp_profile = Some(use_srtp.profiles[0].into());
let profile: SrtpProfile = use_srtp.profiles[0].into();
if !client.engine.config().srtp_profiles().contains(&profile) {
return Err(Error::SecurityError(
crate::SecurityError::ServerSelectedUnofferedSrtpProfile(profile),
)
.into());
}
client.negotiated_srtp_profile = Some(profile);
trace!(
"EncryptedExtensions UseSRTP; selected profile: {:?}",
client.negotiated_srtp_profile
@@ -1272,7 +1279,7 @@ fn handshake_create_client_hello(
// 5. use_srtp extension
let srtp_start = ext_buf.len();
let use_srtp = UseSrtpExtension::default();
let use_srtp = UseSrtpExtension::from_profiles(engine.config().srtp_profiles());
use_srtp.serialize(&mut ext_buf);
let srtp_end = ext_buf.len();
extensions.push(Extension {
@@ -85,7 +85,26 @@ impl UseSrtpExtension {
UseSrtpExtension { profiles, mki }
}
/// A UseSrtpExtension offering `profiles` in this order (duplicates
/// skipped).
pub fn from_profiles(profiles: &[SrtpProfile]) -> Self {
let mut ids = ArrayVec::new();
for profile in profiles {
let id = SrtpProfileId::from(*profile);
if !ids.contains(&id) {
// At most one entry per profile, so this always fits.
let _ = ids.try_push(id);
}
}
UseSrtpExtension {
profiles: ids,
mki: ArrayVec::new(),
}
}
/// Create a default UseSrtpExtension with standard profiles
// Offers now come from Config::srtp_profiles (from_profiles).
#[allow(dead_code)]
pub fn default() -> Self {
let mut profiles = ArrayVec::new();
// Add profiles in order of preference (most secure first)
+15 -6
View File
@@ -732,15 +732,24 @@ impl State {
server.shared_secret = Some(shared_secret);
// Select SRTP profile: first from client list that the server supports.
// Select SRTP profile: with a configured order, the first of ours
// that the client offers; otherwise the first from the client list
// that the server supports.
// Per RFC 5764 Section 4.1.1, the server MUST select a profile that
// both sides support.
if let Some(ref profiles) = client_srtp_profiles {
for profile_id in profiles {
let profile: SrtpProfile = (*profile_id).into();
if SrtpProfile::ALL.contains(&profile) {
server.negotiated_srtp_profile = Some(profile);
break;
if server.engine.config().has_srtp_profile_order() {
let offered: ArrayVec<SrtpProfile, 3> =
profiles.iter().map(|pid| (*pid).into()).collect();
server.negotiated_srtp_profile =
server.engine.config().select_srtp_profile(&offered);
} else {
for profile_id in profiles {
let profile: SrtpProfile = (*profile_id).into();
if SrtpProfile::ALL.contains(&profile) {
server.negotiated_srtp_profile = Some(profile);
break;
}
}
}
}
+11
View File
@@ -436,6 +436,8 @@ pub enum SecurityError {
ServerSelectedDisallowedCipherSuite(Dtls12CipherSuite),
/// The server selected a DTLS 1.3 cipher suite disallowed by configuration.
ServerSelectedDisallowedDtls13CipherSuite(Dtls13CipherSuite),
/// The server selected an SRTP protection profile the client did not offer.
ServerSelectedUnofferedSrtpProfile(crate::SrtpProfile),
/// DTLS 1.2 extended master secret was required but not negotiated.
ExtendedMasterSecretNotNegotiated,
/// No mutually acceptable cipher suite was found.
@@ -555,6 +557,8 @@ pub enum ConfigError {
NoDtls12KeyExchangeGroupsAfterFiltering,
/// DTLS 1.3 suites are enabled but no key exchange group remains enabled.
NoDtls13KeyExchangeGroupsAfterFiltering,
/// The configured list of SRTP protection profiles is empty.
NoSrtpProfiles,
/// Crypto provider validation failed.
CryptoProvider(CryptoProviderValidationError),
}
@@ -1119,6 +1123,12 @@ impl fmt::Display for SecurityError {
Self::ServerSelectedDisallowedDtls13CipherSuite(suite) => {
write!(f, "server selected disallowed cipher suite: {suite:?}")
}
Self::ServerSelectedUnofferedSrtpProfile(profile) => {
write!(
f,
"server selected SRTP profile {profile} that was not offered"
)
}
Self::ExtendedMasterSecretNotNegotiated => {
write!(f, "extended master secret not negotiated")
}
@@ -1251,6 +1261,7 @@ impl fmt::Display for ConfigError {
f,
"DTLS 1.3 cipher suites are enabled but no key exchange groups remain after filtering"
),
Self::NoSrtpProfiles => write!(f, "no SRTP protection profiles configured"),
Self::CryptoProvider(err) => write!(f, "crypto provider validation failed: {err}"),
}
}
+149
View File
@@ -1546,3 +1546,152 @@ mod test {
);
}
}
/// Voelin patch (VOELIN-PATCH.md): the SRTP profile a handshake ends with
/// for the configured profile orders.
#[cfg(test)]
#[cfg(feature = "rcgen")]
mod srtp_profile_order {
use std::time::Duration;
use super::*;
use crate::certificate::generate_self_signed_certificate;
type New = fn(Arc<Config>, DtlsCertificate, Instant) -> Dtls;
const BROWSER: [SrtpProfile; 3] = [
SrtpProfile::AEAD_AES_256_GCM,
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AES128_CM_SHA1_80,
];
fn config(profiles: Option<&[SrtpProfile]>) -> Config {
let builder = Config::builder();
match profiles {
Some(p) => builder.srtp_profiles(p),
None => builder,
}
.build()
.expect("config")
}
/// Poll `dtls` until `Timeout`: its packets, and its SRTP profile once
/// the keying material is out.
fn drain(dtls: &mut Dtls, profile: &mut Option<SrtpProfile>) -> Vec<Vec<u8>> {
let mut buf = vec![0; 2048];
let mut packets = Vec::new();
loop {
match dtls.poll_output(&mut buf) {
Output::Packet(p) => packets.push(p.to_vec()),
Output::KeyingMaterial(_, p) => *profile = Some(p),
Output::Timeout(_) => return packets,
_ => {}
}
}
}
/// Handshake `client` with `server`; the profile each side ends with.
fn negotiate(new: New, client: Config, server: Config) -> (SrtpProfile, SrtpProfile) {
let mut now = Instant::now();
let cert = || generate_self_signed_certificate().expect("certificate");
let mut client = new(Arc::new(client), cert(), now);
client.set_active(true);
let mut server = new(Arc::new(server), cert(), now);
server.set_active(false);
let (mut client_profile, mut server_profile) = (None, None);
for _ in 0..50 {
client.handle_timeout(now).expect("client timeout");
server.handle_timeout(now).expect("server timeout");
let to_server = drain(&mut client, &mut client_profile);
let to_client = drain(&mut server, &mut server_profile);
for p in to_server {
server.handle_packet(&p).expect("server input");
}
for p in to_client {
client.handle_packet(&p).expect("client input");
}
if let (Some(c), Some(s)) = (client_profile, server_profile) {
return (c, s);
}
now += Duration::from_millis(10);
}
panic!("no keying material: client {client_profile:?}, server {server_profile:?}");
}
#[test]
fn dtls12_server_order_wins() {
let server = config(Some(&[
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AEAD_AES_256_GCM,
]));
// A client offering everything, GCM first (as browsers do).
let client = config(Some(&BROWSER));
let (c, s) = negotiate(Dtls::new_12, client, server);
assert_eq!(
(c, s),
(
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AES128_CM_SHA1_80
)
);
}
#[test]
fn dtls12_default_order_unchanged() {
let (c, s) = negotiate(Dtls::new_12, config(None), config(None));
assert_eq!(
(c, s),
(SrtpProfile::AEAD_AES_256_GCM, SrtpProfile::AEAD_AES_256_GCM)
);
// Upstream's server preference with a client that offers SHA1 first.
let client = config(Some(&[
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_128_GCM,
]));
let (c, s) = negotiate(Dtls::new_12, client, config(None));
assert_eq!(
(c, s),
(SrtpProfile::AEAD_AES_128_GCM, SrtpProfile::AEAD_AES_128_GCM)
);
}
#[test]
fn dtls12_client_offers_configured_profiles() {
let client = config(Some(&[SrtpProfile::AES128_CM_SHA1_80]));
let (c, s) = negotiate(Dtls::new_12, client, config(None));
assert_eq!(
(c, s),
(
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AES128_CM_SHA1_80
)
);
}
#[test]
fn dtls13_server_order_wins() {
let server = config(Some(&[
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AEAD_AES_256_GCM,
]));
let (c, s) = negotiate(Dtls::new_13, config(Some(&BROWSER)), server);
assert_eq!(
(c, s),
(
SrtpProfile::AES128_CM_SHA1_80,
SrtpProfile::AES128_CM_SHA1_80
)
);
// Without an order the DTLS 1.3 server keeps the client's (upstream).
let client = config(Some(&[
SrtpProfile::AEAD_AES_128_GCM,
SrtpProfile::AEAD_AES_256_GCM,
]));
let (c, s) = negotiate(Dtls::new_13, client, config(None));
assert_eq!(
(c, s),
(SrtpProfile::AEAD_AES_128_GCM, SrtpProfile::AEAD_AES_128_GCM)
);
}
}