Skip to main content

rtci_srtp/context/
mod.rs

1#[cfg(test)]
2mod context_test;
3#[cfg(test)]
4mod cryptex_test;
5#[cfg(test)]
6mod discard_events_test;
7#[cfg(test)]
8mod header_extension_test;
9#[cfg(test)]
10mod key_lifetime_test;
11#[cfg(test)]
12mod keying_test;
13#[cfg(test)]
14mod profiles_test;
15#[cfg(test)]
16mod rfc3711_rows_test;
17#[cfg(test)]
18mod rfc7714_test;
19#[cfg(test)]
20mod srtcp_test;
21#[cfg(test)]
22mod srtp_test;
23#[cfg(test)]
24mod srtp_upstream_test;
25#[cfg(test)]
26mod test_support;
27#[cfg(test)]
28mod wrap_soak_test;
29
30use std::collections::{HashMap, VecDeque};
31use std::hash::{BuildHasher, RandomState};
32use std::sync::Arc;
33
34use crypto::{RTCCrypto, RTCCryptoProvider};
35use shared::replay_detector::*;
36
37use crate::cipher::cipher_aead_aes_gcm::*;
38use crate::cipher::cipher_aes_cm_hmac_sha1::*;
39use crate::cipher::*;
40use crate::cryptex::Cryptex;
41use crate::header_extension::EncryptedHeaderExtensions;
42use crate::keying::*;
43use crate::option::*;
44use crate::protection_profile::*;
45use shared::error::{Error, Result};
46
47/// SRTCP protection and unprotection.
48pub mod srtcp;
49/// SRTP protection and unprotection.
50pub mod srtp;
51
52const MAX_ROC: u32 = u32::MAX;
53const SEQ_NUM_MEDIAN: u16 = 1 << 15;
54const SEQ_NUM_MAX: u16 = u16::MAX;
55/// How many packet indexes behind the highest one sent the sender still tracks individually
56/// (the NACK responder's default buffer). An index protects one packet only (RFC 3711 Section
57/// 3.3.1, RFC 7714 Section 8.1): the same packet again is protected again (the output is the
58/// same), a different one is refused, and so is any index older than this window.
59pub(crate) const SRTP_SEND_INDEX_WINDOW: usize = 1024;
60/// How many SSRCs one context keeps SRTP state for, and separately SRTCP state for. Packets for
61/// a further SSRC are refused (existing state is never evicted).
62pub(crate) const MAX_SSRC_STATES: usize = 1024;
63/// How many master keys one context holds at a time (see [`Context::add_master_key`]).
64pub const MAX_MASTER_KEYS: usize = 64;
65
66/// Encrypt/Decrypt state for a single SRTP SSRC
67#[derive(Default)]
68pub(crate) struct SrtpSsrcState {
69    ssrc: u32,
70    index: u64,
71    rollover_has_processed: bool,
72    replay_detector: Option<Box<dyn ReplayDetector>>,
73    /// The packet indexes this (sending) context has encrypted, created on first encryption.
74    sent_indexes: Option<SentIndexes>,
75}
76
77/// What an SRTP index may protect, as decided by [`SentIndexes::check`].
78#[derive(Debug, PartialEq, Eq)]
79pub(crate) enum SendIndexUse {
80    /// Not used yet: protect the packet and record it.
81    New,
82    /// Already used for this very packet: protecting it again yields the same bytes.
83    SamePacket,
84    /// Used for a different packet, or too old to tell: refuse.
85    Refused,
86}
87
88/// The packet indexes a sending context protected within [`SRTP_SEND_INDEX_WINDOW`] of the
89/// highest one, each with a digest of the packet it protected.
90pub(crate) struct SentIndexes {
91    highest: Option<u64>,
92    /// `(index, digest)` by `index % SRTP_SEND_INDEX_WINDOW`; `None` when never written.
93    slots: Vec<Option<(u64, u64)>>,
94}
95
96impl SentIndexes {
97    pub(crate) fn new() -> Self {
98        SentIndexes {
99            highest: None,
100            slots: vec![None; SRTP_SEND_INDEX_WINDOW],
101        }
102    }
103
104    fn slot(index: u64) -> usize {
105        (index % SRTP_SEND_INDEX_WINDOW as u64) as usize
106    }
107
108    /// Whether `index` may protect the packet whose digest is `digest`.
109    pub(crate) fn check(&self, index: u64, digest: u64) -> SendIndexUse {
110        // Within the window every index has a slot of its own, so a slot holding another index
111        // holds an older one, and `index` is unused.
112        if let Some((used, used_digest)) = self.slots[Self::slot(index)]
113            && used == index
114        {
115            return if used_digest == digest {
116                SendIndexUse::SamePacket
117            } else {
118                SendIndexUse::Refused
119            };
120        }
121        match self.highest {
122            Some(highest) if index + SRTP_SEND_INDEX_WINDOW as u64 <= highest => {
123                SendIndexUse::Refused
124            }
125            _ => SendIndexUse::New,
126        }
127    }
128
129    /// Records that `index` protected the packet whose digest is `digest`.
130    pub(crate) fn record(&mut self, index: u64, digest: u64) {
131        self.slots[Self::slot(index)] = Some((index, digest));
132        if self.highest.is_none_or(|highest| index > highest) {
133            self.highest = Some(index);
134        }
135    }
136}
137
138/// Encrypt/Decrypt state for a single SRTCP SSRC
139#[derive(Default)]
140pub(crate) struct SrtcpSsrcState {
141    /// The index the next SRTCP packet of this SSRC is sent with: zero before the first one,
142    /// then one more, modulo 2^31, after each packet (RFC 3711 section 3.4). It is not reset
143    /// when the master key changes.
144    srtcp_index: usize,
145    ssrc: u32,
146    replay_detector: Option<Box<dyn ReplayDetector>>,
147}
148
149/// One master key of a context, as the session keys derived from it, with the number of
150/// packets processed under it (RFC 3711 section 3.2.1).
151struct MasterKey {
152    /// The key's MKI; empty when the context uses none.
153    mki: Vec<u8>,
154    cipher: Box<dyn Cipher>,
155    /// SRTP and SRTCP packets protected, or authenticated on reception, with this key.
156    packets: [u64; 2],
157    /// Whether [`ContextEvent::KeyLifetimeExpiring`] was raised, per packet kind.
158    expiring_reported: [bool; 2],
159    /// Whether [`ContextEvent::KeyExhausted`] was raised, per packet kind.
160    exhausted_reported: [bool; 2],
161}
162
163fn kind_index(kind: PacketKind) -> usize {
164    match kind {
165        PacketKind::Rtp => 0,
166        PacketKind::Rtcp => 1,
167    }
168}
169
170impl SrtpSsrcState {
171    pub fn next_rollover_count(&self, sequence_number: u16) -> (u32, i32, bool) {
172        let local_roc = (self.index >> 16) as u32;
173        let local_seq = self.index as u16;
174
175        let mut guess_roc = local_roc;
176
177        let diff = if self.rollover_has_processed {
178            let seq = (sequence_number as i32).wrapping_sub(local_seq as i32);
179            // When local_roc is equal to 0, and entering seq-local_seq > SEQ_NUM_MEDIAN
180            // judgment, it will cause guess_roc calculation error
181            if self.index > SEQ_NUM_MEDIAN as _ {
182                if local_seq < SEQ_NUM_MEDIAN {
183                    if seq > SEQ_NUM_MEDIAN as i32 {
184                        guess_roc = local_roc.wrapping_sub(1);
185                        seq.wrapping_sub(SEQ_NUM_MAX as i32 + 1)
186                    } else {
187                        seq
188                    }
189                } else if local_seq - SEQ_NUM_MEDIAN > sequence_number {
190                    guess_roc = local_roc.wrapping_add(1);
191                    seq.wrapping_add(SEQ_NUM_MAX as i32 + 1)
192                } else {
193                    seq
194                }
195            } else {
196                // local_roc is equal to 0
197                seq
198            }
199        } else {
200            0i32
201        };
202
203        (guess_roc, diff, (guess_roc == 0 && local_roc == MAX_ROC))
204    }
205
206    /// https://tools.ietf.org/html/rfc3550#appendix-A.1
207    ///
208    /// The highest index only moves forward: RFC 3711 Section 3.3.1 and Appendix A update `s_l`
209    /// and the ROC only for a packet ahead of them.
210    pub fn update_rollover_count(&mut self, sequence_number: u16, diff: i32) {
211        if !self.rollover_has_processed {
212            self.index |= sequence_number as u64;
213            self.rollover_has_processed = true;
214        } else if diff > 0 {
215            self.index = self.index.wrapping_add(diff as _);
216        }
217    }
218}
219
220/// Context represents a SRTP cryptographic context
221/// Context can only be used for one-way operations
222/// it must either used ONLY for encryption or ONLY for decryption
223///
224/// # Key lifetime
225///
226/// A master key protects a limited number of packets (RFC 3711 section 9.2): 2^48 SRTP and
227/// 2^31 SRTCP by default, less if [`set_key_lifetime`](Self::set_key_lifetime) says so. The
228/// context counts them. Shortly before a key runs out it raises
229/// [`ContextEvent::KeyLifetimeExpiring`]; at the limit it refuses every further packet with
230/// [`Error::ErrExceededMaxPackets`], in both directions, and raises
231/// [`ContextEvent::KeyExhausted`]. Read the events with [`poll_event`](Self::poll_event) and
232/// re-key: build new contexts from a new DTLS-SRTP handshake, or, with an MKI,
233/// [`add_master_key`](Self::add_master_key) and [`set_sending_mki`](Self::set_sending_mki).
234pub struct Context {
235    profile: ProtectionProfile,
236    /// The master-key table: one entry without an MKI, one or more with.
237    keys: Vec<MasterKey>,
238    /// The entry of `keys` packets are protected with.
239    sending_key: usize,
240    /// The length of the MKI field of every packet; `None` when the context uses no MKI. Fixed
241    /// for the context's lifetime (RFC 3711 section 3.2.1).
242    mki_len: Option<usize>,
243    /// Fixed for the context's lifetime (RFC 3711 section 4.3.1).
244    key_derivation_rate: KeyDerivationRate,
245    /// Kept by [`with_keying`](Self::with_keying), for further master keys and derivations.
246    provider: Option<Arc<dyn RTCCryptoProvider>>,
247    key_lifetime: KeyLifetime,
248
249    srtp_ssrc_states: HashMap<u32, SrtpSsrcState>,
250    srtcp_ssrc_states: HashMap<u32, SrtcpSsrcState>,
251
252    new_srtp_replay_detector: ContextOption,
253    new_srtcp_replay_detector: ContextOption,
254
255    cryptex: Cryptex,
256    /// Whether [`ContextEvent::CryptexRequiredViolation`] was raised since the Cryptex settings
257    /// last changed.
258    cryptex_violation_reported: bool,
259    encrypted_header_extensions: EncryptedHeaderExtensions,
260    /// Whether SRTCP packets are encrypted when protected (the E flag).
261    srtcp_encryption: bool,
262    events: VecDeque<ContextEvent>,
263    /// Received packets discarded as replays or for failed authentication, by reason.
264    discarded: [u64; 2],
265    /// Keys the digests of protected packets kept per sending SSRC (see [`SentIndexes`]).
266    sent_digest_hasher: RandomState,
267}
268
269impl Context {
270    /// Creates an SRTP context.
271    ///
272    /// The crypto implementation is supplied by the caller; this crate never resolves a default.
273    /// Borrowed, not owned: it is only needed to build the keyed cipher/MAC objects below, which
274    /// are what the context retains.
275    ///
276    /// `None` for a replay option means replay protection with a window of
277    /// [`DEFAULT_REPLAY_PROTECTION_WINDOW`] packets (RFC 3711 section 3.3.2); pass
278    /// [`srtp_no_replay_protection`] / [`srtcp_no_replay_protection`] to go without.
279    ///
280    /// The context has one master key, no MKI and a zero key derivation rate, which is what
281    /// DTLS-SRTP uses; see [`with_keying`](Self::with_keying) for the rest.
282    pub fn new(
283        master_key: &[u8],
284        master_salt: &[u8],
285        profile: ProtectionProfile,
286        srtp_ctx_opt: Option<ContextOption>,
287        srtcp_ctx_opt: Option<ContextOption>,
288        crypto: &dyn RTCCrypto,
289    ) -> Result<Context> {
290        Self::build(
291            master_key,
292            master_salt,
293            profile,
294            Keying::default(),
295            srtp_ctx_opt,
296            srtcp_ctx_opt,
297            crypto,
298            None,
299        )
300    }
301
302    /// Creates an SRTP context that uses a Master Key Identifier, a non-zero key derivation
303    /// rate, or both (RFC 3711 sections 3.1, 4.3.1 and 8.1).
304    ///
305    /// With [`Keying::mki`] set, every packet the context protects carries the MKI of the
306    /// master key in use, and every packet it unprotects is processed with the master key its
307    /// MKI names; further keys are added with [`add_master_key`](Self::add_master_key). With a
308    /// non-zero [`Keying::key_derivation_rate`] the session keys are derived again each time the
309    /// packet index crosses a multiple of the rate.
310    ///
311    /// Unlike [`new`](Self::new) the provider is retained, to key those later derivations, and
312    /// with a non-zero rate so are the master keys and salts (zeroized when dropped).
313    ///
314    /// With a non-zero rate a received packet whose estimated index falls in another derivation
315    /// epoch costs a key derivation before it can be authenticated, so a forged packet costs
316    /// more than with a zero rate (a few AES blocks and key schedules; the keys of the last two
317    /// epochs are kept).
318    ///
319    /// # Errors
320    ///
321    /// As [`new`](Self::new), and when the MKI is empty or longer than [`MAX_MKI_LEN`].
322    pub fn with_keying(
323        master_key: &[u8],
324        master_salt: &[u8],
325        profile: ProtectionProfile,
326        keying: Keying,
327        srtp_ctx_opt: Option<ContextOption>,
328        srtcp_ctx_opt: Option<ContextOption>,
329        provider: Arc<dyn RTCCryptoProvider>,
330    ) -> Result<Context> {
331        Self::build(
332            master_key,
333            master_salt,
334            profile,
335            keying,
336            srtp_ctx_opt,
337            srtcp_ctx_opt,
338            provider.crypto(),
339            Some(provider.clone()),
340        )
341    }
342
343    #[allow(clippy::too_many_arguments)]
344    fn build(
345        master_key: &[u8],
346        master_salt: &[u8],
347        profile: ProtectionProfile,
348        keying: Keying,
349        srtp_ctx_opt: Option<ContextOption>,
350        srtcp_ctx_opt: Option<ContextOption>,
351        crypto: &dyn RTCCrypto,
352        provider: Option<Arc<dyn RTCCryptoProvider>>,
353    ) -> Result<Context> {
354        if let Some(mki) = &keying.mki {
355            check_mki(mki)?;
356        }
357        let cipher = new_cipher(
358            profile,
359            master_key,
360            master_salt,
361            crypto,
362            keying.key_derivation_rate,
363            provider.clone(),
364        )?;
365
366        Ok(Context {
367            profile,
368            mki_len: keying.mki.as_ref().map(Vec::len),
369            keys: vec![MasterKey::new(keying.mki.unwrap_or_default(), cipher)],
370            sending_key: 0,
371            key_derivation_rate: keying.key_derivation_rate,
372            provider,
373            key_lifetime: profile.default_key_lifetime(),
374            srtp_ssrc_states: HashMap::new(),
375            srtcp_ssrc_states: HashMap::new(),
376            new_srtp_replay_detector: srtp_ctx_opt
377                .unwrap_or_else(|| srtp_window(DEFAULT_REPLAY_PROTECTION_WINDOW)),
378            new_srtcp_replay_detector: srtcp_ctx_opt
379                .unwrap_or_else(|| srtcp_window(DEFAULT_REPLAY_PROTECTION_WINDOW)),
380            cryptex: Cryptex::default(),
381            cryptex_violation_reported: false,
382            encrypted_header_extensions: EncryptedHeaderExtensions::default(),
383            srtcp_encryption: true,
384            events: VecDeque::new(),
385            discarded: [0; 2],
386            sent_digest_hasher: RandomState::new(),
387        })
388    }
389
390    /// The protection profile the context was created with.
391    pub fn profile(&self) -> ProtectionProfile {
392        self.profile
393    }
394
395    /// How this context uses Cryptex (RFC 9335); see [`Cryptex`].
396    pub fn cryptex(&self) -> Cryptex {
397        self.cryptex
398    }
399
400    /// Sets how this context uses Cryptex (RFC 9335). It applies from the next packet.
401    pub fn set_cryptex(&mut self, cryptex: Cryptex) {
402        self.cryptex = cryptex;
403        self.cryptex_violation_reported = false;
404    }
405
406    /// The header extension elements this context encrypts and decrypts as RFC 6904 has it.
407    pub fn encrypted_header_extensions(&self) -> EncryptedHeaderExtensions {
408        self.encrypted_header_extensions
409    }
410
411    /// Sets the header extension elements whose payload is encrypted (RFC 6904): the ids the
412    /// session negotiated with `urn:ietf:params:rtp-hdrext:encrypt`. It applies from the next
413    /// packet, in the direction the context is used for. The empty set turns it off.
414    ///
415    /// A packet protected with Cryptex is not also processed this way (RFC 9335 section 5).
416    /// When unprotecting, the header passed to
417    /// [`decrypt_rtp_with_header`](Self::decrypt_rtp_with_header) was parsed from the protected
418    /// packet, so its encrypted elements are ciphertext: read them from the returned packet.
419    pub fn set_encrypted_header_extensions(&mut self, ids: EncryptedHeaderExtensions) {
420        self.encrypted_header_extensions = ids;
421    }
422
423    /// Whether SRTCP packets are encrypted when protected.
424    pub fn srtcp_encryption(&self) -> bool {
425        self.srtcp_encryption
426    }
427
428    /// Sets whether SRTCP packets are encrypted when protected (the default) or only
429    /// authenticated, with the E flag clear (RFC 3711 section 3.4, RFC 7714 section 9.3).
430    /// Unprotecting follows each packet's E flag whatever this says; authentication is never
431    /// optional.
432    pub fn set_srtcp_encryption(&mut self, encrypt: bool) {
433        self.srtcp_encryption = encrypt;
434    }
435
436    /// The key derivation rate the context was created with.
437    pub fn key_derivation_rate(&self) -> KeyDerivationRate {
438        self.key_derivation_rate
439    }
440
441    /// How many packets a master key of this context may protect.
442    pub fn key_lifetime(&self) -> KeyLifetime {
443        self.key_lifetime
444    }
445
446    /// Sets how many packets a master key of this context may protect, for instance the
447    /// lifetime key management agreed on (RFC 5764 section 4.1.2: 2^31 packets for the
448    /// DTLS-SRTP profiles).
449    ///
450    /// # Errors
451    ///
452    /// A lifetime of zero, or above 2^48 SRTP or 2^31 SRTCP packets, is refused.
453    pub fn set_key_lifetime(&mut self, lifetime: KeyLifetime) -> Result<()> {
454        lifetime.validate()?;
455        self.key_lifetime = lifetime;
456        Ok(())
457    }
458
459    /// How much of the lifetime of the master key packets are protected with is used.
460    pub fn key_usage(&self) -> KeyUsage {
461        self.usage_of(&self.keys[self.sending_key])
462    }
463
464    /// How much of the lifetime of the master key with this MKI is used; `None` when the
465    /// context has no such key.
466    pub fn key_usage_of(&self, mki: &[u8]) -> Option<KeyUsage> {
467        self.mki_len?;
468        self.keys
469            .iter()
470            .find(|key| key.mki == mki)
471            .map(|key| self.usage_of(key))
472    }
473
474    fn usage_of(&self, key: &MasterKey) -> KeyUsage {
475        KeyUsage {
476            srtp_packets: key.packets[kind_index(PacketKind::Rtp)],
477            srtcp_packets: key.packets[kind_index(PacketKind::Rtcp)],
478            lifetime: self.key_lifetime,
479        }
480    }
481
482    /// The next thing the context has to tell the application; see [`ContextEvent`].
483    pub fn poll_event(&mut self) -> Option<ContextEvent> {
484        self.events.pop_front()
485    }
486
487    /// How many received packets were discarded so far: (replays, authentication failures)
488    /// (RFC 3711 section 3.3).
489    pub fn discarded_packets(&self) -> (u64, u64) {
490        (self.discarded[0], self.discarded[1])
491    }
492
493    /// Records the outcome of unprotecting a packet: a replay or an authentication failure
494    /// is counted, logged and reported (RFC 3711 section 3.3, steps 2 and 5: "the event
495    /// SHOULD be logged").
496    pub(crate) fn note_unprotect_result<T>(
497        &mut self,
498        kind: PacketKind,
499        ssrc: u32,
500        index: u64,
501        result: Result<T>,
502    ) -> Result<T> {
503        let reason = match &result {
504            Err(Error::SrtpSsrcDuplicated(..) | Error::SrtcpSsrcDuplicated(..)) => {
505                DiscardReason::Replay
506            }
507            Err(
508                Error::ErrFailedToVerifyAuthTag
509                | Error::RtpFailedToVerifyAuthTag
510                | Error::RtcpFailedToVerifyAuthTag,
511            ) => DiscardReason::AuthenticationFailed,
512            _ => return result,
513        };
514        let slot = match reason {
515            DiscardReason::Replay => 0,
516            _ => 1,
517        };
518        self.discarded[slot] = self.discarded[slot].saturating_add(1);
519        let pending = self
520            .events
521            .iter()
522            .filter(|event| matches!(event, ContextEvent::PacketDiscarded { .. }))
523            .count();
524        if pending < MAX_PENDING_DISCARD_EVENTS {
525            self.events.push_back(ContextEvent::PacketDiscarded {
526                kind,
527                ssrc,
528                index,
529                reason,
530            });
531        }
532        result
533    }
534
535    /// Adds a master key under `mki` (RFC 3711 section 8.1). Packets carrying that MKI are
536    /// unprotected with it from now on; packets are protected with it once
537    /// [`set_sending_mki`](Self::set_sending_mki) selects it. The rollover counters, the SRTCP
538    /// indexes and the replay lists carry over (RFC 3711 sections 3.3.1 and 3.4).
539    ///
540    /// A master key must never be one used before (RFC 3711 section 9.2); that is for key
541    /// management to ensure, the context cannot tell.
542    ///
543    /// # Errors
544    ///
545    /// Fails when the context was not created with an MKI ([`with_keying`](Self::with_keying)),
546    /// when `mki` is not of the context's MKI length or already names a key, when the key or
547    /// salt length is not the profile's, or when [`MAX_MASTER_KEYS`] keys are held.
548    pub fn add_master_key(
549        &mut self,
550        mki: &[u8],
551        master_key: &[u8],
552        master_salt: &[u8],
553    ) -> Result<()> {
554        let (Some(mki_len), Some(provider)) = (self.mki_len, self.provider.clone()) else {
555            return Err(Error::Other(
556                "this SRTP context uses no MKI: it has one master key".to_owned(),
557            ));
558        };
559        if mki.len() != mki_len {
560            return Err(Error::Other(format!(
561                "MKI of {} octets in a context whose MKIs have {mki_len}",
562                mki.len()
563            )));
564        }
565        if self.keys.iter().any(|key| key.mki == mki) {
566            return Err(Error::Other(
567                "the MKI already names a master key".to_owned(),
568            ));
569        }
570        if self.keys.len() >= MAX_MASTER_KEYS {
571            return Err(Error::Other(format!(
572                "the SRTP context already holds {MAX_MASTER_KEYS} master keys"
573            )));
574        }
575        let cipher = new_cipher(
576            self.profile,
577            master_key,
578            master_salt,
579            provider.crypto(),
580            self.key_derivation_rate,
581            Some(provider.clone()),
582        )?;
583        self.keys.push(MasterKey::new(mki.to_vec(), cipher));
584        Ok(())
585    }
586
587    /// Removes the master key under `mki`, erasing the session keys derived from it. Packets
588    /// carrying that MKI are refused from now on.
589    ///
590    /// # Errors
591    ///
592    /// Fails when no key has that MKI, or when it is the key packets are protected with.
593    pub fn remove_master_key(&mut self, mki: &[u8]) -> Result<()> {
594        let at = self.key_by_mki(mki)?;
595        if at == self.sending_key {
596            return Err(Error::Other(
597                "the master key in use for sending cannot be removed".to_owned(),
598            ));
599        }
600        self.keys.remove(at);
601        if self.sending_key > at {
602            self.sending_key -= 1;
603        }
604        Ok(())
605    }
606
607    /// Protects packets with the master key under `mki` from the next packet on.
608    ///
609    /// # Errors
610    ///
611    /// Fails when no key has that MKI.
612    pub fn set_sending_mki(&mut self, mki: &[u8]) -> Result<()> {
613        self.sending_key = self.key_by_mki(mki)?;
614        Ok(())
615    }
616
617    /// The MKI of the master key packets are protected with; `None` when the context uses no
618    /// MKI.
619    pub fn sending_mki(&self) -> Option<&[u8]> {
620        self.mki_len?;
621        Some(&self.keys[self.sending_key].mki)
622    }
623
624    /// The MKIs of the master keys the context holds; empty when it uses no MKI.
625    pub fn mkis(&self) -> impl Iterator<Item = &[u8]> {
626        self.keys
627            .iter()
628            .filter(|_| self.mki_len.is_some())
629            .map(|key| key.mki.as_slice())
630    }
631
632    fn key_by_mki(&self, mki: &[u8]) -> Result<usize> {
633        if self.mki_len.is_none() {
634            return Err(Error::Other(
635                "this SRTP context uses no MKI: it has one master key".to_owned(),
636            ));
637        }
638        self.keys
639            .iter()
640            .position(|key| key.mki == mki)
641            .ok_or_else(|| Error::Other("no master key has this MKI".to_owned()))
642    }
643
644    /// The length of the MKI field of this context's packets; zero without an MKI.
645    fn mki_field_len(&self) -> usize {
646        self.mki_len.unwrap_or(0)
647    }
648
649    /// The master key a received packet names. The MKI sits `trailing_tag_len` octets before
650    /// the end: before the authentication tag of the HMAC profiles, at the very end with the
651    /// AEAD ones. The caller has checked that the packet holds it.
652    ///
653    /// The MKI is not authenticated (RFC 3711 section 3.1); it only selects the key the
654    /// packet is then authenticated with.
655    fn receiving_key(&self, packet: &[u8], trailing_tag_len: usize) -> Result<usize> {
656        let Some(mki_len) = self.mki_len else {
657            return Ok(0);
658        };
659        let end = packet.len() - trailing_tag_len;
660        let mki = &packet[end - mki_len..end];
661        self.keys
662            .iter()
663            .position(|key| key.mki == mki)
664            .ok_or_else(|| Error::Other("SRTP packet carries an unknown MKI".to_owned()))
665    }
666
667    /// Refuses a packet for a master key that reached its lifetime (RFC 3711 section 9.2), and
668    /// says so once per key and packet kind.
669    fn check_key_lifetime(&mut self, key: usize, kind: PacketKind) -> Result<()> {
670        let limit = self.key_lifetime.limit(kind);
671        let master_key = &mut self.keys[key];
672        let at = kind_index(kind);
673        if master_key.packets[at] < limit {
674            return Ok(());
675        }
676        if !master_key.exhausted_reported[at] {
677            master_key.exhausted_reported[at] = true;
678            self.events.push_back(ContextEvent::KeyExhausted {
679                mki: master_key.mki.clone(),
680                kind,
681            });
682        }
683        Err(Error::ErrExceededMaxPackets)
684    }
685
686    /// Counts a packet processed with a master key, and asks for a new key once the last
687    /// sixteenth of its lifetime is reached.
688    fn count_packet(&mut self, key: usize, kind: PacketKind) {
689        let limit = self.key_lifetime.limit(kind);
690        let master_key = &mut self.keys[key];
691        let at = kind_index(kind);
692        master_key.packets[at] += 1;
693        let remaining = limit.saturating_sub(master_key.packets[at]);
694        if remaining <= (limit / 16).max(1) && !master_key.expiring_reported[at] {
695            master_key.expiring_reported[at] = true;
696            self.events.push_back(ContextEvent::KeyLifetimeExpiring {
697                mki: master_key.mki.clone(),
698                kind,
699                remaining,
700            });
701        }
702    }
703
704    /// Fails with [`Error::SrtpTooManySsrcs`] if `ssrc` has no SRTP state yet and the context
705    /// already holds [`MAX_SSRC_STATES`] of them.
706    fn check_srtp_ssrc_capacity(&self, ssrc: u32) -> Result<()> {
707        if self.srtp_ssrc_states.len() >= MAX_SSRC_STATES
708            && !self.srtp_ssrc_states.contains_key(&ssrc)
709        {
710            return Err(Error::SrtpTooManySsrcs(ssrc, MAX_SSRC_STATES));
711        }
712        Ok(())
713    }
714
715    /// Fails with [`Error::SrtpTooManySsrcs`] if `ssrc` has no SRTCP state yet and the context
716    /// already holds [`MAX_SSRC_STATES`] of them.
717    fn check_srtcp_ssrc_capacity(&self, ssrc: u32) -> Result<()> {
718        if self.srtcp_ssrc_states.len() >= MAX_SSRC_STATES
719            && !self.srtcp_ssrc_states.contains_key(&ssrc)
720        {
721            return Err(Error::SrtpTooManySsrcs(ssrc, MAX_SSRC_STATES));
722        }
723        Ok(())
724    }
725
726    fn get_srtp_ssrc_state(&mut self, ssrc: u32) -> Result<&mut SrtpSsrcState> {
727        self.check_srtp_ssrc_capacity(ssrc)?;
728        // `or_insert_with` so the replay detector (a boxed sliding-window
729        // detector backed by a heap-allocated bit buffer) is only constructed on
730        // the first packet for a given SSRC. `or_insert` would build — and then
731        // immediately drop — a fresh detector on every decrypted packet.
732        let new_srtp_replay_detector = &self.new_srtp_replay_detector;
733        Ok(self
734            .srtp_ssrc_states
735            .entry(ssrc)
736            .or_insert_with(|| SrtpSsrcState {
737                ssrc,
738                replay_detector: Some(new_srtp_replay_detector()),
739                ..Default::default()
740            }))
741    }
742
743    fn get_srtcp_ssrc_state(&mut self, ssrc: u32) -> Result<&mut SrtcpSsrcState> {
744        self.check_srtcp_ssrc_capacity(ssrc)?;
745        let new_srtcp_replay_detector = &self.new_srtcp_replay_detector;
746        Ok(self
747            .srtcp_ssrc_states
748            .entry(ssrc)
749            .or_insert_with(|| SrtcpSsrcState {
750                ssrc,
751                replay_detector: Some(new_srtcp_replay_detector()),
752                ..Default::default()
753            }))
754    }
755
756    /// roc returns SRTP rollover counter value of specified SSRC.
757    fn get_roc(&self, ssrc: u32) -> Option<u32> {
758        self.srtp_ssrc_states
759            .get(&ssrc)
760            .map(|s| (s.index >> 16) as _)
761    }
762
763    /// set_roc sets SRTP rollover counter value of specified SSRC.
764    fn set_roc(&mut self, ssrc: u32, roc: u32) {
765        if let Ok(state) = self.get_srtp_ssrc_state(ssrc) {
766            state.index = (roc as u64) << 16;
767            state.rollover_has_processed = false;
768        }
769    }
770
771    /// The SRTCP index the next packet of the specified SSRC is sent with.
772    fn get_index(&self, ssrc: u32) -> Option<usize> {
773        self.srtcp_ssrc_states.get(&ssrc).map(|s| s.srtcp_index)
774    }
775
776    /// Sets the SRTCP index the next packet of the specified SSRC is sent with.
777    fn set_index(&mut self, ssrc: u32, index: usize) {
778        if let Ok(state) = self.get_srtcp_ssrc_state(ssrc) {
779            state.srtcp_index = index % (MAX_SRTCP_INDEX + 1);
780        }
781    }
782
783    /// Sets the number of packets counted against the sending master key, to test what happens
784    /// at the end of a key's lifetime without sending 2^31 packets.
785    #[cfg(test)]
786    fn set_packets_processed(&mut self, kind: PacketKind, packets: u64) {
787        self.keys[self.sending_key].packets[kind_index(kind)] = packets;
788    }
789
790    /// A context around a given cipher, for test vectors that state session keys.
791    #[cfg(test)]
792    fn from_cipher(profile: ProtectionProfile, cipher: Box<dyn Cipher>) -> Context {
793        Context {
794            profile,
795            mki_len: None,
796            keys: vec![MasterKey::new(Vec::new(), cipher)],
797            sending_key: 0,
798            key_derivation_rate: KeyDerivationRate::ZERO,
799            provider: None,
800            key_lifetime: profile.default_key_lifetime(),
801            srtp_ssrc_states: HashMap::new(),
802            srtcp_ssrc_states: HashMap::new(),
803            new_srtp_replay_detector: srtp_window(DEFAULT_REPLAY_PROTECTION_WINDOW),
804            new_srtcp_replay_detector: srtcp_window(DEFAULT_REPLAY_PROTECTION_WINDOW),
805            cryptex: Cryptex::default(),
806            cryptex_violation_reported: false,
807            encrypted_header_extensions: EncryptedHeaderExtensions::default(),
808            srtcp_encryption: true,
809            events: VecDeque::new(),
810            discarded: [0; 2],
811            sent_digest_hasher: RandomState::new(),
812        }
813    }
814}
815
816impl MasterKey {
817    fn new(mki: Vec<u8>, cipher: Box<dyn Cipher>) -> Self {
818        Self {
819            mki,
820            cipher,
821            packets: [0; 2],
822            expiring_reported: [false; 2],
823            exhausted_reported: [false; 2],
824        }
825    }
826}
827
828fn check_mki(mki: &[u8]) -> Result<()> {
829    if mki.is_empty() || mki.len() > MAX_MKI_LEN {
830        return Err(Error::Other(format!(
831            "an MKI has 1 to {MAX_MKI_LEN} octets, not {}",
832            mki.len()
833        )));
834    }
835    Ok(())
836}
837
838fn new_cipher(
839    profile: ProtectionProfile,
840    master_key: &[u8],
841    master_salt: &[u8],
842    crypto: &dyn RTCCrypto,
843    rate: KeyDerivationRate,
844    provider: Option<Arc<dyn RTCCryptoProvider>>,
845) -> Result<Box<dyn Cipher>> {
846    let key_len = profile.key_len();
847    let salt_len = profile.salt_len();
848
849    if master_key.len() != key_len {
850        return Err(Error::SrtpMasterKeyLength(key_len, master_key.len()));
851    } else if master_salt.len() != salt_len {
852        return Err(Error::SrtpSaltLength(salt_len, master_salt.len()));
853    }
854    profile.ensure_crypto_supported(crypto)?;
855
856    // Deriving the session keys and building their ciphers and MACs puts the master key, the
857    // session keys, their AES schedules, GHASH keys and HMAC states into the stack frames of
858    // the functions that do it, this crate's and the provider's. RFC 7714 section 13.1: "All
859    // keys MUST be properly erased when no longer needed". So all of it runs in frames below
860    // one that overwrites the stack under it afterwards; what comes back is a box.
861    crypto::on_erased_stack(|| {
862        build_cipher(profile, master_key, master_salt, crypto, rate, provider)
863    })
864}
865
866fn build_cipher(
867    profile: ProtectionProfile,
868    master_key: &[u8],
869    master_salt: &[u8],
870    crypto: &dyn RTCCrypto,
871    rate: KeyDerivationRate,
872    provider: Option<Arc<dyn RTCCryptoProvider>>,
873) -> Result<Box<dyn Cipher>> {
874    Ok(if profile.is_aead() {
875        // `CipherAeadAesGcm::new` selects AES-128 vs AES-256 from the profile itself.
876        Box::new(CipherAeadAesGcm::new(
877            profile,
878            master_key,
879            master_salt,
880            crypto,
881            rate,
882            provider,
883        )?)
884    } else {
885        Box::new(CipherAesCmHmacSha1::new(
886            profile,
887            master_key,
888            master_salt,
889            crypto,
890            rate,
891            provider,
892        )?)
893    })
894}