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

+187
View File
@@ -0,0 +1,187 @@
use std::fmt;
use std::time::SystemTime;
use openssl::asn1::{Asn1Integer, Asn1Time, Asn1Type};
use openssl::bn::BigNum;
use openssl::ec::{EcGroup, EcKey};
use openssl::hash::MessageDigest;
use openssl::nid::Nid;
use openssl::pkey::{PKey, Private};
use openssl::rsa::Rsa;
use openssl::x509::{X509, X509Name};
use super::CryptoError;
use super::OsslDtlsImpl;
const RSA_F4: u32 = 0x10001;
/// Certificate used for DTLS.
#[derive(Debug, Clone)]
pub struct OsslDtlsCert {
pub pkey: PKey<Private>,
pub x509: X509,
}
/// Defines the type of key pair to generate for the DTLS certificate.
#[derive(Clone, Debug, Default)]
pub enum DtlsPKeyType {
/// Generate an RSA key pair
Rsa2048,
/// Generate an EC-DSA key pair using the NIST P-256 curve
#[default]
EcDsaP256,
/// Generate an EC-DSA key pair using the NIST P-384 curve
EcDsaP384,
}
/// Controls certificate generation options.
#[derive(Clone, Debug)]
pub struct DtlsCertOptions {
/// The common name for the certificate.
pub common_name: String,
/// The type of key to generate.
pub pkey_type: DtlsPKeyType,
}
const DTLS_CERT_IDENTITY: &str = "WebRTC";
impl Default for DtlsCertOptions {
fn default() -> Self {
Self {
common_name: DTLS_CERT_IDENTITY.into(),
pkey_type: Default::default(),
}
}
}
impl OsslDtlsCert {
/// Creates a new (self signed) DTLS certificate.
pub fn new(options: DtlsCertOptions) -> Self {
Self::self_signed(options).expect("create dtls cert")
}
// The libWebRTC code we try to match is at:
// https://webrtc.googlesource.com/src/+/1568f1b1330f94494197696fe235094e6293b258/rtc_base/openssl_certificate.cc#58
fn self_signed(options: DtlsCertOptions) -> Result<Self, CryptoError> {
let f4 = BigNum::from_u32(RSA_F4)?;
let pkey = match options.pkey_type {
DtlsPKeyType::Rsa2048 => {
let key = Rsa::generate_with_e(2048, &f4)?;
PKey::from_rsa(key)?
}
DtlsPKeyType::EcDsaP256 => {
let nid = Nid::X9_62_PRIME256V1; // NIST P-256 curve
let group = EcGroup::from_curve_name(nid)?;
let key = EcKey::generate(&group)?;
PKey::from_ec_key(key)?
}
DtlsPKeyType::EcDsaP384 => {
let nid = Nid::SECP384R1;
let group = EcGroup::from_curve_name(nid)?;
let key = EcKey::generate(&group)?;
PKey::from_ec_key(key)?
}
};
let mut x509b = X509::builder()?;
x509b.set_version(2)?; // X509.V3 (zero indexed)
// For Firefox, the serial number must be unique across all certificates, including those of other
// processes/machines! See https://github.com/versatica/mediasoup/issues/127#issuecomment-474460153
// and https://github.com/algesten/str0m/issues/517
let mut serial_buf = [0u8; 16];
openssl::rand::rand_bytes(&mut serial_buf)?;
let serial_bn = BigNum::from_slice(&serial_buf)?;
let serial = Asn1Integer::from_bn(&serial_bn)?;
x509b.set_serial_number(&serial)?;
let before = Asn1Time::from_unix(unix_time() - 3600)?;
x509b.set_not_before(&before)?;
let after = Asn1Time::days_from_now(7)?;
x509b.set_not_after(&after)?;
x509b.set_pubkey(&pkey)?;
// The libWebRTC code for this is:
//
// !X509_NAME_add_entry_by_NID(name.get(), NID_commonName, MBSTRING_UTF8,
// (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
//
// libWebRTC allows this name to be configured by the user of the library.
// That's a future TODO for str0m.
let mut nameb = X509Name::builder()?;
nameb.append_entry_by_nid_with_type(
Nid::COMMONNAME,
options.common_name.as_str(),
Asn1Type::UTF8STRING,
)?;
let name = nameb.build();
x509b.set_subject_name(&name)?;
x509b.set_issuer_name(&name)?;
x509b.sign(&pkey, MessageDigest::sha256())?;
let x509 = x509b.build();
Ok(OsslDtlsCert { pkey, x509 })
}
/// Produce a (public) fingerprint of the cert.
///
/// This is sent via SDP to the other peer to lock down the DTLS
/// to this specific certificate.
pub fn fingerprint(&self) -> Fingerprint {
let digest: &[u8] = &self
.x509
.digest(MessageDigest::sha256())
.expect("digest to fingerprint");
Fingerprint {
hash_func: "sha-256".into(),
bytes: digest.to_vec(),
}
}
pub fn new_dtls_impl(&self) -> Result<OsslDtlsImpl, CryptoError> {
OsslDtlsImpl::new(self.clone())
}
pub fn new_dtls_impl_with_groups(
&self,
groups_list: &str,
) -> Result<OsslDtlsImpl, CryptoError> {
OsslDtlsImpl::new_with_groups(self.clone(), Some(groups_list))
}
}
#[derive(Debug)]
pub struct Fingerprint {
pub hash_func: String,
pub bytes: Vec<u8>,
}
impl fmt::Display for Fingerprint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ", self.hash_func)?;
for (i, b) in self.bytes.iter().enumerate() {
if i > 0 {
write!(f, ":")?;
}
write!(f, "{:02X}", b)?;
}
Ok(())
}
}
// TODO: Refactor away this use of System::now, to instead go via InstantExt
// and base the time on the first Instant. This would require lazy init of
// Dtls, or that we pass a first ever Instant into the creation of Rtc.
//
// This is not a super high priority since it's only used for setting a before
// time in the generated certificate, and one hour back from that.
pub fn unix_time() -> libc::time_t {
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs() as libc::time_t
}
+206
View File
@@ -0,0 +1,206 @@
use std::collections::VecDeque;
use std::io::{self, Read, Write};
use std::time::{Duration, Instant};
use dimpl::SrtpProfile;
use openssl::dh::Dh;
use openssl::ssl::{Ssl, SslContext, SslContextBuilder, SslMethod, SslOptions, SslVerifyMode};
use super::cert::OsslDtlsCert;
use super::io_buf::IoBuffer;
use super::stream::TlsStream;
use super::{CryptoError, DATAGRAM_MTU, DATAGRAM_MTU_WARN, DtlsEvent};
// We restrict cipher suites to those that include ephemeral Diffie-Hellman or
// ephemeral Elliptic Curve Diffie-Hellman and modern AEAD ciphers.
const DTLS_CIPHERS: &str =
"ECDHE+CHACHA20:DHE+CHACHA20:ECDHE+AESGCM:DHE+AESGCM:ECDHE+AES256:DHE+AES256";
pub struct OsslDtlsImpl {
/// Certificate for the DTLS session.
_cert: OsslDtlsCert,
/// Context belongs together with Fingerprint.
///
/// This just needs to be kept alive since it pins the entire openssl context
/// from which `Ssl` is created.
_context: SslContext,
/// The actual openssl TLS stream.
tls: TlsStream<IoBuffer>,
}
impl OsslDtlsImpl {
pub fn new(cert: OsslDtlsCert) -> Result<Self, CryptoError> {
Self::new_with_groups(cert, None)
}
pub fn new_with_groups(
cert: OsslDtlsCert,
groups_list: Option<&str>,
) -> Result<Self, CryptoError> {
let context = dtls_create_ctx_with_groups(&cert, groups_list)?;
let ssl = dtls_ssl_create(&context)?;
Ok(OsslDtlsImpl {
_cert: cert,
_context: context,
tls: TlsStream::new(ssl, IoBuffer::default()),
})
}
}
impl OsslDtlsImpl {
pub fn set_active(&mut self, active: bool) {
self.tls.set_active(active);
}
pub fn is_active(&self) -> Option<bool> {
self.tls.is_active()
}
pub fn handle_receive(
&mut self,
m: &[u8],
o: &mut VecDeque<DtlsEvent>,
) -> Result<(), CryptoError> {
self.tls.inner_mut().set_incoming(m);
if self.handle_handshake(o)? {
// early return as long as we're handshaking
return Ok(());
}
let mut buf = vec![0; 2000];
let n = match self.tls.read(&mut buf) {
Ok(v) => v,
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
return Ok(());
}
Err(e) => return Err(e.into()),
};
buf.truncate(n);
o.push_back(DtlsEvent::Data(buf));
Ok(())
}
pub fn poll_datagram(&mut self) -> Option<super::DatagramSend> {
let x = self.tls.inner_mut().pop_outgoing();
if let Some(x) = &x {
if x.len() > DATAGRAM_MTU_WARN {
eprintln!("DTLS above MTU {}: {}", DATAGRAM_MTU_WARN, x.len());
}
}
x
}
pub fn poll_timeout(&mut self, now: Instant) -> Option<Instant> {
// OpenSSL has a built-in timeout of 1 second that is doubled for
// each retry. There is a way to get direct control over the
// timeout (using DTLS_set_timer_cb), but that function doesn't
// appear to be exposed in openssl crate yet.
// TODO(martin): Write PR for openssl crate to be able to use this
// callback to make a tighter timeout handling here.
self.tls
.is_handshaking()
.then(|| now + Duration::from_millis(500))
}
pub fn handle_input(&mut self, data: &[u8]) -> Result<(), CryptoError> {
Ok(self.tls.write_all(data)?)
}
pub fn is_connected(&self) -> bool {
self.tls.is_connected()
}
pub fn handle_handshake(
&mut self,
output: &mut VecDeque<DtlsEvent>,
) -> Result<bool, CryptoError> {
if self.tls.is_connected() {
// Nice. Nothing to do.
Ok(false)
} else if self.tls.complete_handshake_until_block()? {
output.push_back(DtlsEvent::Connected);
let (keying_material, srtp_profile, fingerprint) = self
.tls
.take_srtp_keying_material()
.expect("Exported keying material");
output.push_back(DtlsEvent::RemoteFingerprint(fingerprint));
output.push_back(DtlsEvent::SrtpKeyingMaterial(keying_material, srtp_profile));
Ok(false)
} else {
Ok(true)
}
}
}
pub fn dtls_create_ctx(cert: &OsslDtlsCert) -> Result<SslContext, CryptoError> {
dtls_create_ctx_with_groups(cert, None)
}
pub fn dtls_create_ctx_with_groups(
cert: &OsslDtlsCert,
groups_list: Option<&str>,
) -> Result<SslContext, CryptoError> {
// TODO: Technically we want to disallow DTLS < 1.2, but that requires
// us to use this commented out unsafe. We depend on browsers disallowing
// it instead.
// let method = unsafe { SslMethod::from_ptr(DTLSv1_2_method()) };
let mut ctx = SslContextBuilder::new(SslMethod::dtls())?;
ctx.set_cipher_list(DTLS_CIPHERS)?;
if let Some(groups) = groups_list {
ctx.set_groups_list(groups)?;
}
let srtp_profiles = {
// Rust can't join directly to a string, need to allocate a vec first :(
// This happens very rarely so the extra allocations don't matter
let all: Vec<_> = SrtpProfile::ALL.iter().map(openssl_name).collect();
all.join(":")
};
ctx.set_tlsext_use_srtp(&srtp_profiles)?;
let mut mode = SslVerifyMode::empty();
mode.insert(SslVerifyMode::PEER);
mode.insert(SslVerifyMode::FAIL_IF_NO_PEER_CERT);
ctx.set_verify_callback(mode, |_ok, _ctx| true);
ctx.set_private_key(&cert.pkey)?;
ctx.set_certificate(&cert.x509)?;
let mut options = SslOptions::empty();
options.insert(SslOptions::SINGLE_ECDH_USE);
options.insert(SslOptions::NO_DTLSV1);
ctx.set_options(options);
// Enable DHE cipher suites by setting temporary DH parameters
if let Ok(dh) = Dh::get_2048_256() {
ctx.set_tmp_dh(dh.as_ref())?;
}
let ctx = ctx.build();
Ok(ctx)
}
fn openssl_name(profile: &SrtpProfile) -> &'static str {
match profile {
SrtpProfile::AES128_CM_SHA1_80 => "SRTP_AES128_CM_SHA1_80",
SrtpProfile::AEAD_AES_128_GCM => "SRTP_AEAD_AES_128_GCM",
SrtpProfile::AEAD_AES_256_GCM => "SRTP_AEAD_AES_256_GCM",
_ => unreachable!(),
}
}
pub fn dtls_ssl_create(ctx: &SslContext) -> Result<Ssl, CryptoError> {
let mut ssl = Ssl::new(ctx)?;
ssl.set_mtu(DATAGRAM_MTU as u32)?;
Ok(ssl)
}
+83
View File
@@ -0,0 +1,83 @@
use std::collections::VecDeque;
use std::io;
use std::ops::Deref;
/// A wrapper for some payload that is to be sent.
#[derive(Debug)]
pub struct DatagramSend(Vec<u8>);
impl Deref for DatagramSend {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Default, Debug)]
pub struct IoBuffer {
pub incoming: Vec<u8>,
pub outgoing: VecDeque<DatagramSend>,
}
impl IoBuffer {
pub(crate) fn set_incoming(&mut self, buf: &[u8]) {
self.incoming.extend_from_slice(buf);
// Each packet ought to be ~MTU 1400. If openssl is
// not consuming all incoming data, we got some problem.
assert!(
self.incoming.len() < 30_000,
"Incoming DTLS data is not being consumed"
);
}
pub(crate) fn pop_outgoing(&mut self) -> Option<DatagramSend> {
self.outgoing.pop_front()
}
}
impl io::Read for IoBuffer {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = self.incoming.len();
if n == 0 {
return Err(io::Error::new(io::ErrorKind::WouldBlock, "WouldBlock"));
}
let max = buf.len().min(n);
buf[..max].copy_from_slice(&self.incoming[..max]);
if max == self.incoming.len() {
// The typical case is that the entire input is consumed at once,
// which means the happy path is cheap.
self.incoming.truncate(0);
} else {
// Shifting data inside a vector is not good. This should be rare.
self.incoming.drain(..max);
}
Ok(n)
}
}
impl io::Write for IoBuffer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let dsend = buf.to_vec().into();
self.outgoing.push_back(dsend);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl From<Vec<u8>> for DatagramSend {
fn from(v: Vec<u8>) -> Self {
DatagramSend(v)
}
}
+64
View File
@@ -0,0 +1,64 @@
#![allow(unused)]
//! OpenSSL implementation of cryptographic functions.
/// Errors that can arise in DTLS.
#[derive(Debug)]
pub enum CryptoError {
/// Some error from OpenSSL layer (used for DTLS).
OpenSsl(openssl::error::ErrorStack),
/// Other IO errors.
Io(io::Error),
}
impl From<openssl::error::ErrorStack> for CryptoError {
fn from(value: openssl::error::ErrorStack) -> Self {
CryptoError::OpenSsl(value)
}
}
impl From<io::Error> for CryptoError {
fn from(value: io::Error) -> Self {
CryptoError::Io(value)
}
}
mod cert;
use std::io;
pub use cert::{DtlsCertOptions, DtlsPKeyType, Fingerprint, OsslDtlsCert};
pub mod io_buf;
mod stream;
mod dtls;
use dimpl::SrtpProfile;
pub use dtls::{OsslDtlsImpl, dtls_ssl_create};
pub use io_buf::DatagramSend;
use std::collections::VecDeque;
/// Targeted MTU
pub(crate) const DATAGRAM_MTU: usize = 1150;
/// Warn if any packet we are about to send is above this size.
pub(crate) const DATAGRAM_MTU_WARN: usize = 1280;
/// Events arising from a [`Dtls`] instance.
#[derive(Debug)]
pub enum DtlsEvent {
/// When the DTLS has finished handshaking.
Connected,
/// Keying material for SRTP encryption master key and the selected SRTP profile.
SrtpKeyingMaterial(Vec<u8>, SrtpProfile),
/// The fingerprint of the remote peer.
///
/// This should be checked against the fingerprint communicated in the SDP.
RemoteFingerprint(Fingerprint),
/// Decrypted data from incoming DTLS traffic.
Data(Vec<u8>),
}
+219
View File
@@ -0,0 +1,219 @@
use std::panic::UnwindSafe;
use std::{io, mem};
use openssl::hash::MessageDigest;
use openssl::srtp::SrtpProfileId;
use openssl::ssl::{HandshakeError, MidHandshakeSslStream, Ssl, SslStream};
use super::{CryptoError, Fingerprint, SrtpProfile};
const DTLS_KEY_LABEL: &str = "EXTRACTOR-dtls_srtp";
pub struct TlsStream<S> {
active: Option<bool>,
state: State<S>,
keying_mat: Option<(Vec<u8>, SrtpProfile, Fingerprint)>,
exported: bool,
}
pub enum State<S> {
Init(Ssl, S),
Handshaking(MidHandshakeSslStream<S>),
Established(SslStream<S>),
Empty,
}
/// This is okay because there is no way for a user of Rtc to interact with the Dtls subsystem
/// in a way that would allow them to observe a potentially broken invariant when catching a panic.
impl<S> UnwindSafe for State<S> {}
impl<S> TlsStream<S>
where
S: io::Read + io::Write + UnwindSafe,
{
pub fn new(ssl: Ssl, stream: S) -> Self {
TlsStream {
active: None,
state: State::Init(ssl, stream),
keying_mat: None,
exported: false,
}
}
pub fn is_active(&self) -> Option<bool> {
self.active
}
pub fn set_active(&mut self, active: bool) {
assert!(
self.active.is_none(),
"set_active should called exactly once"
);
self.active = Some(active);
}
pub fn complete_handshake_until_block(&mut self) -> Result<bool, CryptoError> {
if let Err(e) = self.handshaken() {
if e.kind() == io::ErrorKind::WouldBlock {
Ok(false)
} else {
Err(e.into())
}
} else {
Ok(true)
}
}
pub fn is_handshaking(&self) -> bool {
matches!(self.state, State::Init(_, _) | State::Handshaking(_))
}
pub fn is_connected(&self) -> bool {
matches!(self.state, State::Established(_))
}
pub fn handshaken(&mut self) -> Result<&mut SslStream<S>, io::Error> {
let active = self.is_active().expect("set_active must be called");
let v = self.state.handshaken(active)?;
// first time we complete the handshake, we extract the keying material for SRTP.
if !self.exported {
let keying_mat = export_srtp_keying_material(v)?;
self.exported = true;
self.keying_mat = Some(keying_mat);
}
Ok(v)
}
pub fn take_srtp_keying_material(&mut self) -> Option<(Vec<u8>, SrtpProfile, Fingerprint)> {
self.keying_mat.take()
}
pub fn inner_mut(&mut self) -> &mut S {
match &mut self.state {
State::Init(_, s) => s,
State::Handshaking(v) => v.get_mut(),
State::Established(v) => v.get_mut(),
State::Empty => panic!("inner_mut on empty dtls state"),
}
}
}
impl<S> State<S>
where
S: io::Read + io::Write + UnwindSafe,
{
fn handshaken(&mut self, active: bool) -> Result<&mut SslStream<S>, io::Error> {
if let State::Established(v) = self {
return Ok(v);
}
let taken = mem::replace(self, State::Empty);
let result = match taken {
State::Empty | State::Established(_) => unreachable!(),
State::Init(ssl, stream) => {
if active {
println!("ossl Connect");
ssl.connect(stream)
} else {
println!("ossl Accept");
ssl.accept(stream)
}
}
State::Handshaking(mid) => mid.handshake(),
};
match result {
Ok(v) => {
println!("ossl Established version: {:}", v.ssl().version_str());
let _ = mem::replace(self, State::Established(v));
// recursively return the &mut SslStream.
self.handshaken(active)
}
Err(e) => Err(match e {
HandshakeError::WouldBlock(e) => {
let _ = mem::replace(self, State::Handshaking(e));
io::Error::new(io::ErrorKind::WouldBlock, "WouldBlock")
}
HandshakeError::SetupFailure(e) => {
println!("ossl DTLS setup failed: {:?}", e);
io::Error::new(io::ErrorKind::InvalidInput, e)
}
HandshakeError::Failure(e) => {
let e = e.into_error();
println!("ossl DTLS failure: {:?}", e);
io::Error::new(io::ErrorKind::InvalidData, e)
}
}),
}
}
}
fn export_srtp_keying_material<S>(
stream: &mut SslStream<S>,
) -> Result<(Vec<u8>, SrtpProfile, Fingerprint), io::Error> {
let ssl = stream.ssl();
// remote peer certificate fingerprint
let x509 = ssl
.peer_certificate()
.ok_or_else(|| io::Error::other("No remote X509 cert"))?;
let digest: &[u8] = &x509.digest(MessageDigest::sha256())?;
let fp = Fingerprint {
hash_func: "sha-256".into(),
bytes: digest.to_vec(),
};
let srtp_profile_id = ssl
.selected_srtp_profile()
.map(|s| s.id())
.ok_or_else(|| io::Error::other("Failed to negotiate SRTP profile"))?;
let srtp_profile = srtp_profile_from_id(srtp_profile_id)?;
// extract SRTP keying material
let mut buf = vec![0_u8; srtp_profile.keying_material_len()];
ssl.export_keying_material(&mut buf, DTLS_KEY_LABEL, None)?;
Ok((buf, srtp_profile, fp))
}
impl<S> io::Read for TlsStream<S>
where
S: io::Read + io::Write + UnwindSafe,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.handshaken()?.read(buf)
}
}
impl<S> io::Write for TlsStream<S>
where
S: io::Read + io::Write + UnwindSafe,
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.handshaken()?.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.handshaken()?.flush()
}
}
/// Convert SrtpProfileId to SrtpProfile
fn srtp_profile_from_id(value: SrtpProfileId) -> Result<SrtpProfile, io::Error> {
match value {
SrtpProfileId::SRTP_AES128_CM_SHA1_80 => Ok(SrtpProfile::AES128_CM_SHA1_80),
SrtpProfileId::SRTP_AEAD_AES_128_GCM => Ok(SrtpProfile::AEAD_AES_128_GCM),
SrtpProfileId::SRTP_AEAD_AES_256_GCM => Ok(SrtpProfile::AEAD_AES_256_GCM),
x => Err(io::Error::other(format!(
"Unsupported SRTP profile {:x}",
x.as_raw()
))),
}
}