str0m_proto/crypto/provider.rs
1//! Cryptographic provider traits for pluggable crypto backends.
2//!
3//! This module defines the trait-based interface for cryptographic operations
4//! in str0m, allowing users to provide custom crypto implementations for SRTP,
5//! SHA-1 and SHA-256 hashing, SHA1 HMAC (for STUN), and DTLS.
6//!
7//! Implementors of a crypto provider only need to depend on this module.
8
9use std::fmt;
10use std::fmt::Debug;
11use std::panic::{RefUnwindSafe, UnwindSafe};
12use std::sync::OnceLock;
13use std::time::Instant;
14
15use subtle::ConstantTimeEq;
16
17use crate::crypto::dtls::*;
18use crate::crypto::error::CryptoError;
19
20// ============================================================================
21// CryptoProvider
22// ============================================================================
23
24/// Cryptographic provider for SRTP, hashing, SHA1 HMAC, and DTLS operations.
25///
26/// This struct holds references to all cryptographic components needed
27/// for WebRTC operations. Users can provide custom implementations of each component
28/// to replace the default OpenSSL-based provider.
29///
30/// # Design
31///
32/// The provider uses static trait object references (`&'static dyn Trait`) which
33/// provides zero runtime overhead for trait dispatch. This design is inspired by
34/// dimpl's CryptoProvider and ensures efficient crypto operations.
35#[derive(Debug, Clone)]
36pub struct CryptoProvider {
37 /// SRTP provider for creating cipher instances and key derivation.
38 pub srtp_provider: &'static dyn SrtpProvider,
39 /// SHA1 HMAC provider for STUN message integrity.
40 pub sha1_hmac_provider: &'static dyn Sha1HmacProvider,
41 /// SHA-1 hash provider for legacy certificate fingerprints.
42 pub sha1_provider: &'static dyn Sha1Provider,
43 /// SHA-256 hash provider.
44 pub sha256_provider: &'static dyn Sha256Provider,
45 /// DTLS provider for creating DTLS instances.
46 pub dtls_provider: &'static dyn DtlsProvider,
47}
48
49/// CryptoProvider contains only static references to thread-safe traits,
50/// so it's safe to use across panic boundaries.
51impl UnwindSafe for CryptoProvider {}
52impl RefUnwindSafe for CryptoProvider {}
53
54/// Static storage for the default crypto provider.
55static DEFAULT: OnceLock<CryptoProvider> = OnceLock::new();
56
57impl CryptoProvider {
58 /// Install this provider as the process-wide default.
59 pub fn install_process_default(self) {
60 let _ = DEFAULT.set(self);
61 }
62
63 /// Install a default crypto provider for the process.
64 ///
65 /// # Panics
66 ///
67 /// Panics if called more than once.
68 pub fn install_default(provider: CryptoProvider) {
69 DEFAULT
70 .set(provider)
71 .expect("CryptoProvider::install_default() called more than once");
72 }
73
74 /// Get the default crypto provider, if one has been installed.
75 pub fn get_default() -> Option<&'static CryptoProvider> {
76 DEFAULT.get()
77 }
78}
79
80impl fmt::Display for CryptoProvider {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 write!(f, "CryptoProvider")
83 }
84}
85
86// ============================================================================
87// Marker Trait
88// ============================================================================
89
90pub use crate::{CryptoSafe, Sha1HmacProvider};
91
92// ============================================================================
93// Main Provider Traits
94// ============================================================================
95
96/// SRTP provider for creating cipher instances and key derivation.
97pub trait SrtpProvider: CryptoSafe {
98 /// Factory for AES-128-CM-SHA1-80 ciphers.
99 fn aes_128_cm_sha1_80(&self) -> &'static dyn SupportedAes128CmSha1_80;
100
101 /// Factory for AEAD-AES-128-GCM ciphers.
102 fn aead_aes_128_gcm(&self) -> &'static dyn SupportedAeadAes128Gcm;
103
104 /// Factory for AEAD-AES-256-GCM ciphers.
105 fn aead_aes_256_gcm(&self) -> &'static dyn SupportedAeadAes256Gcm;
106
107 /// Perform AES-128-ECB round for key derivation.
108 fn srtp_aes_128_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]);
109
110 /// Perform AES-256-ECB round for key derivation.
111 fn srtp_aes_256_ecb_round(&self, key: &[u8], input: &[u8], output: &mut [u8]);
112}
113
114/// SHA-1 hash provider for legacy certificate fingerprints.
115pub trait Sha1Provider: CryptoSafe {
116 /// Compute SHA-1 hash of the input data.
117 fn sha1(&self, data: &[u8]) -> [u8; 20];
118}
119
120/// SHA-256 hash provider.
121pub trait Sha256Provider: CryptoSafe {
122 /// Compute SHA-256 hash of the input data.
123 fn sha256(&self, data: &[u8]) -> [u8; 32];
124}
125
126/// Which DTLS version(s) to use for the handshake.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128#[non_exhaustive]
129pub enum DtlsVersion {
130 /// Use only DTLS 1.2.
131 #[default]
132 Dtls12,
133 /// Use only DTLS 1.3.
134 Dtls13,
135 /// Auto-detect: the first incoming ClientHello determines the version.
136 Auto,
137}
138
139impl fmt::Display for DtlsVersion {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 match self {
142 DtlsVersion::Dtls12 => write!(f, "DTLS 1.2"),
143 DtlsVersion::Dtls13 => write!(f, "DTLS 1.3"),
144 DtlsVersion::Auto => write!(f, "DTLS Auto-detect"),
145 }
146 }
147}
148
149/// Factory for DTLS instances and certificates.
150pub trait DtlsProvider: CryptoSafe {
151 /// Generate a new self-signed DTLS certificate.
152 ///
153 /// Returns `None` if this provider does not support certificate generation.
154 /// In that case, the user must supply a certificate via `RtcConfig::set_dtls_cert`.
155 fn generate_certificate(&self) -> Option<DtlsCert>;
156
157 /// Create a new DTLS instance with the given certificate.
158 ///
159 /// mtu: Backends that can size their record layer according to the provided MTU should do so;
160 /// backends that cannot ignore it. `None` means use the backend's default.
161 fn new_dtls(
162 &self,
163 cert: &DtlsCert,
164 now: Instant,
165 dtls_version: DtlsVersion,
166 mtu: Option<usize>,
167 ) -> Result<Box<dyn DtlsInstance>, CryptoError>;
168
169 /// Whether the provider is used in a test context.
170 fn is_test(&self) -> bool {
171 cfg!(feature = "_internal_test_exports")
172 }
173}
174
175// ============================================================================
176// DTLS Instance Trait
177// ============================================================================
178
179/// DTLS instance operations (matches dimpl's Dtls API surface).
180pub trait DtlsInstance: CryptoSafe {
181 /// Set whether this instance is active (client) or passive (server).
182 fn set_active(&mut self, active: bool);
183
184 /// Handle an incoming DTLS packet.
185 fn handle_packet(&mut self, packet: &[u8]) -> Result<(), DtlsImplError>;
186
187 /// Poll for output from the DTLS instance.
188 ///
189 /// The buffer must be large enough to hold the largest possible DTLS record.
190 fn poll_output<'a>(&mut self, buf: &'a mut [u8]) -> DtlsOutput<'a>;
191
192 /// Handle a timeout event.
193 fn handle_timeout(&mut self, now: Instant) -> Result<(), DtlsImplError>;
194
195 /// Send application data over DTLS.
196 ///
197 /// Returns the number of bytes accepted for buffering or transmission.
198 /// Accepts either the entire slice or none of it; retain unaccepted data
199 /// and retry after the handshake progresses. An empty slice returns zero
200 /// on success and does not indicate handshake readiness.
201 fn send_application_data(&mut self, data: &[u8]) -> Result<usize, DtlsImplError>;
202
203 /// Return true if the instance is operating in the client role.
204 fn is_active(&self) -> bool;
205
206 /// Return the negotiated DTLS protocol version. May return `None` before handshake completion.
207 fn protocol_version(&self) -> Option<ProtocolVersion>;
208
209 /// Return true after close has started and while close output may still need polling.
210 fn is_closing(&self) -> bool {
211 false
212 }
213
214 /// Return true once close output has drained and the instance is closed.
215 fn is_closed(&self) -> bool {
216 false
217 }
218
219 /// Initiate graceful shutdown by sending a DTLS `close_notify` alert.
220 fn close(&mut self) -> Result<(), DtlsImplError>;
221}
222
223// ============================================================================
224// SRTP Cipher Factory Traits
225// ============================================================================
226
227/// Factory for AES-128-CM-SHA1-80 cipher instances.
228pub trait SupportedAes128CmSha1_80: CryptoSafe {
229 /// Create a cipher instance with the given key.
230 fn create_cipher(&self, key: [u8; 16], encrypt: bool) -> Box<dyn Aes128CmSha1_80Cipher>;
231}
232
233/// Factory for AEAD-AES-128-GCM cipher instances.
234pub trait SupportedAeadAes128Gcm: CryptoSafe {
235 /// Create a cipher instance with the given key.
236 fn create_cipher(&self, key: [u8; 16], encrypt: bool) -> Box<dyn AeadAes128GcmCipher>;
237}
238
239/// Factory for AEAD-AES-256-GCM cipher instances.
240pub trait SupportedAeadAes256Gcm: CryptoSafe {
241 /// Create a cipher instance with the given key.
242 fn create_cipher(&self, key: [u8; 32], encrypt: bool) -> Box<dyn AeadAes256GcmCipher>;
243}
244
245// ============================================================================
246// SRTP Cipher Instance Traits
247// ============================================================================
248
249/// AES-128-CM-SHA1-80 cipher instance for SRTP encryption/decryption.
250pub trait Aes128CmSha1_80Cipher: CryptoSafe {
251 /// Encrypt input with the given IV.
252 fn encrypt(
253 &mut self,
254 iv: &[u8; 16],
255 input: &[u8],
256 output: &mut [u8],
257 ) -> Result<(), CryptoError>;
258
259 /// Decrypt input with the given IV.
260 fn decrypt(
261 &mut self,
262 iv: &[u8; 16],
263 input: &[u8],
264 output: &mut [u8],
265 ) -> Result<(), CryptoError>;
266}
267
268/// AEAD-AES-128-GCM cipher instance for SRTP encryption/decryption.
269pub trait AeadAes128GcmCipher: CryptoSafe {
270 /// Encrypt input with the given IV and AAD.
271 fn encrypt(
272 &mut self,
273 iv: &[u8; 12],
274 aad: &[u8],
275 input: &[u8],
276 output: &mut [u8],
277 ) -> Result<(), CryptoError>;
278
279 /// Decrypt input with the given IV and AADs.
280 fn decrypt(
281 &mut self,
282 iv: &[u8; 12],
283 aads: &[&[u8]],
284 input: &[u8],
285 output: &mut [u8],
286 ) -> Result<usize, CryptoError>;
287}
288
289/// AEAD-AES-256-GCM cipher instance for SRTP encryption/decryption.
290pub trait AeadAes256GcmCipher: CryptoSafe {
291 /// Encrypt input with the given IV and AAD.
292 fn encrypt(
293 &mut self,
294 iv: &[u8; 12],
295 aad: &[u8],
296 input: &[u8],
297 output: &mut [u8],
298 ) -> Result<(), CryptoError>;
299
300 /// Decrypt input with the given IV and AADs.
301 fn decrypt(
302 &mut self,
303 iv: &[u8; 12],
304 aads: &[&[u8]],
305 input: &[u8],
306 output: &mut [u8],
307 ) -> Result<usize, CryptoError>;
308}
309
310// ============================================================================
311// SRTP Profile Definitions
312// ============================================================================
313
314/// AES-128-CM-SHA1-80 SRTP profile.
315///
316/// This struct provides constants, types, and protocol functions for the
317/// AES-128-CM-SHA1-80 SRTP protection profile (RFC 5764).
318#[derive(Debug, Clone, Copy)]
319pub struct Aes128CmSha1_80;
320
321impl Aes128CmSha1_80 {
322 /// Key length in bytes.
323 pub const KEY_LEN: usize = 16;
324 /// Salt length in bytes.
325 pub const SALT_LEN: usize = 14;
326 /// HMAC key length in bytes.
327 pub const HMAC_KEY_LEN: usize = 20;
328 /// HMAC tag length in bytes.
329 pub const HMAC_TAG_LEN: usize = 10;
330
331 /// Compute and append RTP HMAC tag.
332 pub fn rtp_hmac(
333 sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20],
334 key: &[u8],
335 buf: &mut [u8],
336 srtp_index: u64,
337 hmac_start: usize,
338 ) {
339 let roc = (srtp_index >> 16) as u32;
340 let tag = sha1_hmac(key, &[&buf[..hmac_start], &roc.to_be_bytes()]);
341 buf[hmac_start..(hmac_start + Self::HMAC_TAG_LEN)]
342 .copy_from_slice(&tag[0..Self::HMAC_TAG_LEN]);
343 }
344
345 /// Verify RTP HMAC tag.
346 pub fn rtp_verify(
347 sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20],
348 key: &[u8],
349 buf: &[u8],
350 srtp_index: u64,
351 cmp: &[u8],
352 ) -> bool {
353 let roc = (srtp_index >> 16) as u32;
354 let tag = sha1_hmac(key, &[buf, &roc.to_be_bytes()]);
355 tag[0..Self::HMAC_TAG_LEN].ct_eq(cmp).into()
356 }
357
358 /// Compute RTP IV.
359 pub fn rtp_iv(salt: [u8; 14], ssrc: u32, srtp_index: u64) -> [u8; 16] {
360 let mut iv = [0; 16];
361 let ssrc_be = ssrc.to_be_bytes();
362 let srtp_be = srtp_index.to_be_bytes();
363 iv[4..8].copy_from_slice(&ssrc_be);
364 for i in 0..8 {
365 iv[i + 6] ^= srtp_be[i];
366 }
367 for i in 0..14 {
368 iv[i] ^= salt[i];
369 }
370 iv
371 }
372
373 /// Compute and append RTCP HMAC tag.
374 pub fn rtcp_hmac(
375 sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20],
376 key: &[u8],
377 buf: &mut [u8],
378 hmac_index: usize,
379 ) {
380 let tag = sha1_hmac(key, &[&buf[0..hmac_index]]);
381 buf[hmac_index..(hmac_index + Self::HMAC_TAG_LEN)]
382 .copy_from_slice(&tag[0..Self::HMAC_TAG_LEN]);
383 }
384
385 /// Verify RTCP HMAC tag.
386 pub fn rtcp_verify(
387 sha1_hmac: impl Fn(&[u8], &[&[u8]]) -> [u8; 20],
388 key: &[u8],
389 buf: &[u8],
390 cmp: &[u8],
391 ) -> bool {
392 let tag = sha1_hmac(key, &[buf]);
393 tag[0..Self::HMAC_TAG_LEN].ct_eq(cmp).into()
394 }
395}
396
397/// AEAD-AES-128-GCM SRTP profile.
398///
399/// This struct provides constants, types, and protocol functions for the
400/// AEAD-AES-128-GCM SRTP protection profile (RFC 7714).
401#[derive(Debug, Clone, Copy)]
402pub struct AeadAes128Gcm;
403
404impl AeadAes128Gcm {
405 /// Key length in bytes.
406 pub const KEY_LEN: usize = 16;
407 /// Salt length in bytes.
408 pub const SALT_LEN: usize = 12;
409 /// RTCP AAD length in bytes.
410 pub const RTCP_AAD_LEN: usize = 12;
411 /// Authentication tag length in bytes.
412 pub const TAG_LEN: usize = 16;
413 /// IV length in bytes.
414 pub const IV_LEN: usize = 12;
415
416 /// Compute RTP IV.
417 pub fn rtp_iv(salt: [u8; 12], ssrc: u32, roc: u32, seq: u16) -> [u8; 12] {
418 // See: https://www.rfc-editor.org/rfc/rfc7714#section-8.1
419 let mut iv = [0; 12];
420
421 let ssrc_be = ssrc.to_be_bytes();
422 let roc_be = roc.to_be_bytes();
423 let seq_be = seq.to_be_bytes();
424
425 iv[2..6].copy_from_slice(&ssrc_be);
426 iv[6..10].copy_from_slice(&roc_be);
427 iv[10..12].copy_from_slice(&seq_be);
428
429 for i in 0..12 {
430 iv[i] ^= salt[i];
431 }
432
433 iv
434 }
435
436 /// Compute RTCP IV.
437 pub fn rtcp_iv(salt: [u8; 12], ssrc: u32, srtp_index: u32) -> [u8; 12] {
438 // See: https://www.rfc-editor.org/rfc/rfc7714#section-9.1
439 let mut iv = [0; 12];
440
441 let ssrc_be = ssrc.to_be_bytes();
442 let srtp_be = srtp_index.to_be_bytes();
443
444 iv[2..6].copy_from_slice(&ssrc_be);
445 iv[8..12].copy_from_slice(&srtp_be);
446
447 for i in 0..12 {
448 iv[i] ^= salt[i];
449 }
450
451 iv
452 }
453}
454
455/// AEAD-AES-256-GCM SRTP profile.
456///
457/// This struct provides constants, types, and protocol functions for the
458/// AEAD-AES-256-GCM SRTP protection profile (RFC 7714).
459#[derive(Debug, Clone, Copy)]
460pub struct AeadAes256Gcm;
461
462impl AeadAes256Gcm {
463 /// Key length in bytes.
464 pub const KEY_LEN: usize = 32;
465 /// Salt length in bytes.
466 pub const SALT_LEN: usize = 12;
467 /// RTCP AAD length in bytes.
468 pub const RTCP_AAD_LEN: usize = 12;
469 /// Authentication tag length in bytes.
470 pub const TAG_LEN: usize = 16;
471 /// IV length in bytes.
472 pub const IV_LEN: usize = 12;
473
474 /// Compute RTP IV.
475 pub fn rtp_iv(salt: [u8; 12], ssrc: u32, roc: u32, seq: u16) -> [u8; 12] {
476 // See: https://www.rfc-editor.org/rfc/rfc7714#section-8.1
477 let mut iv = [0; 12];
478
479 let ssrc_be = ssrc.to_be_bytes();
480 let roc_be = roc.to_be_bytes();
481 let seq_be = seq.to_be_bytes();
482
483 iv[2..6].copy_from_slice(&ssrc_be);
484 iv[6..10].copy_from_slice(&roc_be);
485 iv[10..12].copy_from_slice(&seq_be);
486
487 for i in 0..12 {
488 iv[i] ^= salt[i];
489 }
490
491 iv
492 }
493
494 /// Compute RTCP IV.
495 pub fn rtcp_iv(salt: [u8; 12], ssrc: u32, srtp_index: u32) -> [u8; 12] {
496 // See: https://www.rfc-editor.org/rfc/rfc7714#section-9.1
497 let mut iv = [0; 12];
498
499 let ssrc_be = ssrc.to_be_bytes();
500 let srtp_be = srtp_index.to_be_bytes();
501
502 iv[2..6].copy_from_slice(&ssrc_be);
503 iv[8..12].copy_from_slice(&srtp_be);
504
505 for i in 0..12 {
506 iv[i] ^= salt[i];
507 }
508
509 iv
510 }
511}