Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions rtc-dtls/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ pub struct ConfigBuilder {
cipher_suites: Vec<CipherSuiteId>,
signature_schemes: Vec<SignatureScheme>,
srtp_protection_profiles: Vec<SrtpProtectionProfile>,
srtp_profile_selection: SrtpProfileSelection,
client_auth: ClientAuthType,
extended_master_secret: ExtendedMasterSecretType,
flight_interval: Duration,
Expand All @@ -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(),
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Vec<Box<dyn CipherSuite>>> {
// a client offers one family or the other, while a server can only offer them if
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -639,6 +672,7 @@ pub struct HandshakeConfig {
pub(crate) local_signature_schemes: Vec<SignatureHashAlgorithm>, // Available signature schemes
pub(crate) extended_master_secret: ExtendedMasterSecretType, // Policy for the Extended Master Support extension
pub(crate) local_srtp_protection_profiles: Vec<SrtpProtectionProfile>, // 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<Certificate>,
Expand Down Expand Up @@ -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![],
Expand Down
7 changes: 5 additions & 2 deletions rtc-dtls/src/conn/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
5 changes: 5 additions & 0 deletions rtc-dtls/src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion rtc-dtls/src/flight/flight0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
) {
Expand Down
5 changes: 3 additions & 2 deletions rtc-dtls/src/flight/flight3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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,
) {
Expand Down
74 changes: 74 additions & 0 deletions rtc-dtls/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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<SrtpProtectionProfile, ()> {
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],
Expand Down
121 changes: 121 additions & 0 deletions rtc-dtls/tests/srtp_profile_selection.rs
Original file line number Diff line number Diff line change
@@ -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<dyn std::error::Error>>;
type HandshakeResult = Result<ProfilePair, Box<dyn std::error::Error>>;

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(())
}