From 83cbc6fb2eebc24676fa52d154b5a4cf88db7f31 Mon Sep 17 00:00:00 2001 From: "ig.kuzmin" Date: Fri, 20 Nov 2026 13:47:46 +0300 Subject: [PATCH] feat(dtls): server-side SRTP protection profile preference option MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit flight0/flight3 select the SRTP protection profile by iterating the client's use_srtp offer first; Config::local_srtp_protection_profiles acts only as a membership filter, so its order never affects the outcome. Standard TLS practice is server preference (RFC 5246/8446), and RFC 5764 §4.1.1 mandates only that the server select a single profile the client offered — the policy within the offered set is the server's. Add ConfigBuilder::with_srtp_profile_selection (SrtpProfileSelection::ClientPreference | ServerPreference; the default keeps the historical client-order behavior) and route both server-side call sites through select_srtp_profile. Expose DTLSConn::selected_srtp_protection_profile publicly (pion parity: Connection.SelectedSRTPProtectionProfile) and add Endpoint::connection(&remote) so integrators can inspect the negotiated profile; include integration tests pinning both policies over real handshakes. Without ServerPreference, gateways that must rank the intersection by their own policy (AEAD when offered, legacy HMAC-SHA1 otherwise) have to parse the client's ClientHello themselves before feeding it to the engine, duplicating the use_srtp parsing the library already performs. --- rtc-dtls/src/config.rs | 35 +++++++ rtc-dtls/src/conn/mod.rs | 7 +- rtc-dtls/src/endpoint.rs | 5 + rtc-dtls/src/flight/flight0.rs | 3 +- rtc-dtls/src/flight/flight3.rs | 5 +- rtc-dtls/src/lib.rs | 74 ++++++++++++++ rtc-dtls/tests/srtp_profile_selection.rs | 121 +++++++++++++++++++++++ 7 files changed, 245 insertions(+), 5 deletions(-) create mode 100644 rtc-dtls/tests/srtp_profile_selection.rs diff --git a/rtc-dtls/src/config.rs b/rtc-dtls/src/config.rs index bc21c05d5..10714fcdc 100644 --- a/rtc-dtls/src/config.rs +++ b/rtc-dtls/src/config.rs @@ -113,6 +113,7 @@ pub struct ConfigBuilder { cipher_suites: Vec, signature_schemes: Vec, srtp_protection_profiles: Vec, + srtp_profile_selection: SrtpProfileSelection, client_auth: ClientAuthType, extended_master_secret: ExtendedMasterSecretType, flight_interval: Duration, @@ -138,6 +139,7 @@ impl Default for ConfigBuilder { cipher_suites: vec![], signature_schemes: vec![], srtp_protection_profiles: vec![], + srtp_profile_selection: SrtpProfileSelection::default(), client_auth: ClientAuthType::default(), extended_master_secret: ExtendedMasterSecretType::default(), flight_interval: Duration::default(), @@ -199,6 +201,19 @@ impl ConfigBuilder { self } + /// srtp_profile_selection declares whose preference order wins when the + /// server intersects the client's `use_srtp` offer with the configured + /// profiles. The default is [`SrtpProfileSelection::ClientPreference`] + /// (historical behavior); [`SrtpProfileSelection::ServerPreference`] + /// makes the server pick by its own configured order. + pub fn with_srtp_profile_selection( + mut self, + srtp_profile_selection: SrtpProfileSelection, + ) -> Self { + self.srtp_profile_selection = srtp_profile_selection; + self + } + /// client_auth determines the server's policy for /// TLS Client Authentication. The default is NoClientCert. pub fn with_client_auth(mut self, client_auth: ClientAuthType) -> Self { @@ -367,6 +382,23 @@ pub enum ExtendedMasterSecretType { Disable = 2, } +/// SrtpProfileSelection declares whose preference order wins when the server +/// intersects the client's `use_srtp` offer with the server's configured +/// protection profiles. +/// +/// [RFC 5764, §4.1.1] requires only that the server select a single profile +/// the client offered; the selection policy within the offered set is the +/// server's. The historical pion/webrtc-rs behavior iterates the client's +/// list first. +#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)] +pub enum SrtpProfileSelection { + /// The client's `use_srtp` offer order wins (historical behavior). + #[default] + ClientPreference, + /// The server's configured profile order wins. + ServerPreference, +} + impl ConfigBuilder { fn offered_cipher_suites(&self, is_client: bool) -> Result>> { // a client offers one family or the other, while a server can only offer them if @@ -580,6 +612,7 @@ impl ConfigBuilder { local_signature_schemes, extended_master_secret: self.extended_master_secret, local_srtp_protection_profiles: self.srtp_protection_profiles, + srtp_profile_selection: self.srtp_profile_selection, server_name, client_auth: self.client_auth, local_certificates: self.certificates, @@ -639,6 +672,7 @@ pub struct HandshakeConfig { pub(crate) local_signature_schemes: Vec, // Available signature schemes pub(crate) extended_master_secret: ExtendedMasterSecretType, // Policy for the Extended Master Support extension pub(crate) local_srtp_protection_profiles: Vec, // Available SRTPProtectionProfiles, if empty no SRTP support + pub(crate) srtp_profile_selection: SrtpProfileSelection, // Whose order wins when intersecting the client's use_srtp offer pub(crate) server_name: String, pub(crate) client_auth: ClientAuthType, // If we are a client should we request a client certificate pub(crate) local_certificates: Vec, @@ -696,6 +730,7 @@ impl HandshakeConfig { local_signature_schemes: vec![], extended_master_secret: ExtendedMasterSecretType::Disable, local_srtp_protection_profiles: vec![], + srtp_profile_selection: SrtpProfileSelection::default(), server_name: String::new(), client_auth: ClientAuthType::NoClientCert, local_certificates: vec![], diff --git a/rtc-dtls/src/conn/mod.rs b/rtc-dtls/src/conn/mod.rs index f26342d90..b1a8c4bff 100644 --- a/rtc-dtls/src/conn/mod.rs +++ b/rtc-dtls/src/conn/mod.rs @@ -251,8 +251,11 @@ impl DTLSConn { &self.state } - // selected_srtp_protection_profile returns the selected SRTPProtectionProfile - pub(crate) fn selected_srtp_protection_profile(&self) -> SrtpProtectionProfile { + /// selected_srtp_protection_profile returns the SRTPProtectionProfile + /// negotiated via the `use_srtp` extension + /// ([`SrtpProtectionProfile::Unsupported`] when SRTP is not negotiated). + /// Pion parity: `Connection.SelectedSRTPProtectionProfile`. + pub fn selected_srtp_protection_profile(&self) -> SrtpProtectionProfile { self.state.srtp_protection_profile } diff --git a/rtc-dtls/src/endpoint.rs b/rtc-dtls/src/endpoint.rs index cb0ae4ff1..79bd2e85b 100644 --- a/rtc-dtls/src/endpoint.rs +++ b/rtc-dtls/src/endpoint.rs @@ -90,6 +90,11 @@ impl Endpoint { } } + /// Get the established connection with the remote address, if any. + pub fn connection(&self, remote: SocketAddr) -> Option<&DTLSConn> { + self.connections.get(&remote) + } + /// Initiate an Association pub fn connect( &mut self, diff --git a/rtc-dtls/src/flight/flight0.rs b/rtc-dtls/src/flight/flight0.rs index 24c9d7ff3..2297c5498 100644 --- a/rtc-dtls/src/flight/flight0.rs +++ b/rtc-dtls/src/flight/flight0.rs @@ -111,7 +111,8 @@ impl Flight for Flight0 { } } Extension::UseSrtp(e) => { - if let Ok(profile) = find_matching_srtp_profile( + if let Ok(profile) = select_srtp_profile( + cfg.srtp_profile_selection, &e.protection_profiles, &cfg.local_srtp_protection_profiles, ) { diff --git a/rtc-dtls/src/flight/flight3.rs b/rtc-dtls/src/flight/flight3.rs index 83e89d45a..09c796dce 100644 --- a/rtc-dtls/src/flight/flight3.rs +++ b/rtc-dtls/src/flight/flight3.rs @@ -19,7 +19,7 @@ use shared::error::Error; use crate::cipher_suite::cipher_suite_for_id; use crate::prf::{prf_pre_master_secret, prf_psk_pre_master_secret}; -use crate::{find_matching_cipher_suite, find_matching_srtp_profile}; +use crate::{find_matching_cipher_suite, select_srtp_profile}; use crate::extension::renegotiation_info::ExtensionRenegotiationInfo; @@ -184,7 +184,8 @@ impl Flight for Flight3 { for extension in &h.extensions { match extension { Extension::UseSrtp(e) => { - let profile = match find_matching_srtp_profile( + let profile = match select_srtp_profile( + cfg.srtp_profile_selection, &e.protection_profiles, &cfg.local_srtp_protection_profiles, ) { diff --git a/rtc-dtls/src/lib.rs b/rtc-dtls/src/lib.rs index 45bd9c0e6..b576acad5 100644 --- a/rtc-dtls/src/lib.rs +++ b/rtc-dtls/src/lib.rs @@ -105,6 +105,7 @@ pub mod signature_hash_algorithm; pub mod state; use cipher_suite::*; +use config::SrtpProfileSelection; use extension::extension_use_srtp::SrtpProtectionProfile; pub(crate) fn find_matching_srtp_profile( @@ -121,6 +122,79 @@ pub(crate) fn find_matching_srtp_profile( Err(()) } +/// Select the SRTP protection profile per the configured policy: whose list +/// order wins when intersecting the client's `use_srtp` offer with the +/// server's configured profiles. [RFC 5764, §4.1.1] mandates only that the +/// selected profile is one the client offered; the order policy is the +/// server's choice. +pub(crate) fn select_srtp_profile( + selection: SrtpProfileSelection, + client_offer: &[SrtpProtectionProfile], + local_profiles: &[SrtpProtectionProfile], +) -> Result { + match selection { + SrtpProfileSelection::ServerPreference => { + find_matching_srtp_profile(local_profiles, client_offer) + } + SrtpProfileSelection::ClientPreference => { + find_matching_srtp_profile(client_offer, local_profiles) + } + } +} + +#[cfg(test)] +mod srtp_selection_tests { + use super::*; + + const SHA1_80: SrtpProtectionProfile = SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80; + const SHA1_32: SrtpProtectionProfile = SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32; + const GCM128: SrtpProtectionProfile = SrtpProtectionProfile::Srtp_Aead_Aes_128_Gcm; + + #[test] + fn client_preference_follows_the_client_order() { + let client = [SHA1_80, SHA1_32]; + let server = [SHA1_32, SHA1_80]; + assert_eq!( + select_srtp_profile(SrtpProfileSelection::ClientPreference, &client, &server), + Ok(SHA1_80) + ); + } + + #[test] + fn server_preference_follows_the_server_order() { + let client = [SHA1_80, SHA1_32]; + let server = [SHA1_32, SHA1_80]; + assert_eq!( + select_srtp_profile(SrtpProfileSelection::ServerPreference, &client, &server), + Ok(SHA1_32) + ); + } + + #[test] + fn server_preference_still_selects_within_the_client_offer() { + // The server order only ranks the intersection: a profile the client + // did not offer is never selected (RFC 5764 §4.1.1). + let client = [SHA1_80, GCM128]; + let server = [SHA1_32, GCM128]; + assert_eq!( + select_srtp_profile(SrtpProfileSelection::ServerPreference, &client, &server), + Ok(GCM128) + ); + } + + #[test] + fn no_intersection_is_an_error() { + let client = [GCM128]; + let server = [SHA1_80, SHA1_32]; + assert!( + select_srtp_profile(SrtpProfileSelection::ServerPreference, &client, &server).is_err() + ); + assert!( + select_srtp_profile(SrtpProfileSelection::ClientPreference, &client, &server).is_err() + ); + } +} + pub(crate) fn find_matching_cipher_suite( a: &[CipherSuiteId], b: &[CipherSuiteId], diff --git a/rtc-dtls/tests/srtp_profile_selection.rs b/rtc-dtls/tests/srtp_profile_selection.rs new file mode 100644 index 000000000..a4457df75 --- /dev/null +++ b/rtc-dtls/tests/srtp_profile_selection.rs @@ -0,0 +1,121 @@ +//! Server-side SRTP protection profile selection: whose offer order wins +//! when the client's `use_srtp` list and the server's configured profiles +//! intersect. RFC 5764 §4.1.1 mandates only that the server select a +//! profile the client offered; [`SrtpProfileSelection::ServerPreference`] +//! makes the server rank the intersection by its own order. + +use crypto::default_provider; +use rtc_dtls::{ + config::{ClientAuthType, ConfigBuilder, SrtpProfileSelection}, + crypto::Certificate, + endpoint::{Endpoint, EndpointEvent}, + extension::extension_use_srtp::SrtpProtectionProfile, +}; +use shared::TransportProtocol; +use std::{net::SocketAddr, sync::Arc, time::Instant}; + +type TestResult = Result<(), Box>; +type HandshakeResult = Result>; + +type ProfilePair = (SrtpProtectionProfile, SrtpProtectionProfile); + +const SHA1_80: SrtpProtectionProfile = SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80; +const SHA1_32: SrtpProtectionProfile = SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32; + +/// Run a full handshake; return the profile selected on each side. +fn handshake(selection: SrtpProfileSelection) -> HandshakeResult { + let provider = default_provider()?; + let client_cert = Certificate::generate_self_signed(vec!["client".into()], provider.crypto())?; + let server_cert = + Certificate::generate_self_signed(vec!["localhost".into()], provider.crypto())?; + + // The client prefers HMAC-SHA1; the server prefers AEAD-capable order + // here SHA1_32-first: the two orders disagree on the intersection, so + // the test pins whose order actually wins. + let client_profiles = vec![SHA1_80, SHA1_32]; + let server_profiles = vec![SHA1_32, SHA1_80]; + + let client_config = ConfigBuilder::default() + .with_crypto_provider(provider.clone().into()) + .with_certificates(vec![client_cert]) + .with_insecure_skip_verify(true) + .with_client_auth(ClientAuthType::RequireAnyClientCert) + .with_srtp_protection_profiles(client_profiles); + let server_config = ConfigBuilder::default() + .with_crypto_provider(provider.into()) + .with_certificates(vec![server_cert]) + .with_insecure_skip_verify(true) + .with_client_auth(ClientAuthType::RequireAnyClientCert) + .with_srtp_protection_profiles(server_profiles) + .with_srtp_profile_selection(selection); + + let client_addr: SocketAddr = "127.0.0.1:44003".parse()?; + let server_addr: SocketAddr = "127.0.0.1:44004".parse()?; + let start = Instant::now(); + let mut client = Endpoint::new(client_addr, TransportProtocol::UDP, None); + let mut server = Endpoint::new( + server_addr, + TransportProtocol::UDP, + Some(Arc::new(server_config.build(false, None)?)), + ); + client.connect( + start, + server_addr, + Arc::new(client_config.build(true, None)?), + None, + )?; + + // Pump the flights between the endpoints until both sides complete. + let mut client_completed = false; + let mut server_completed = false; + for _ in 0..6 { + while let Some(packet) = client.poll_transmit() { + server_completed |= server + .read(start, client_addr, packet.transport.ecn, packet.message)? + .iter() + .any(|event| matches!(event, EndpointEvent::HandshakeComplete)); + } + while let Some(packet) = server.poll_transmit() { + client_completed |= client + .read(start, server_addr, packet.transport.ecn, packet.message)? + .iter() + .any(|event| matches!(event, EndpointEvent::HandshakeComplete)); + } + if client_completed && server_completed { + break; + } + } + assert!( + client_completed && server_completed, + "the handshake must complete with {selection:?}" + ); + + Ok(( + client + .connection(server_addr) + .expect("client connection") + .selected_srtp_protection_profile(), + server + .connection(client_addr) + .expect("server connection") + .selected_srtp_protection_profile(), + )) +} + +#[test] +fn client_preference_selects_by_the_client_order() -> TestResult { + let (client, server) = handshake(SrtpProfileSelection::ClientPreference)?; + // Client order: SHA1_80 first. + assert_eq!(client, SHA1_80); + assert_eq!(server, SHA1_80); + Ok(()) +} + +#[test] +fn server_preference_selects_by_the_server_order() -> TestResult { + let (client, server) = handshake(SrtpProfileSelection::ServerPreference)?; + // Server order: SHA1_32 first. + assert_eq!(client, SHA1_32); + assert_eq!(server, SHA1_32); + Ok(()) +}