Skip to main content

rtci_srtp/context/
srtcp.rs

1use super::*;
2use crate::key_derivation::SRTCP_INDEX_SIZE;
3use shared::{error::Result, marshal::Unmarshal};
4
5use bytes::BytesMut;
6
7impl Context {
8    /// DecryptRTCP decrypts a RTCP packet with an encrypted payload
9    ///
10    /// The packet is authenticated whatever its E flag says, and decrypted only when the flag
11    /// is set (RFC 3711 section 3.4, RFC 7714 section 9.3).
12    ///
13    /// # Errors
14    ///
15    /// Fails if authentication fails, if the packet is a replay or too short, if it names a
16    /// master key the context does not have, or with [`Error::ErrExceededMaxPackets`] once the
17    /// master key reached its lifetime (RFC 3711 section 9.2).
18    pub fn decrypt_rtcp(&mut self, encrypted: &[u8]) -> Result<BytesMut> {
19        let result = self.unprotect_rtcp(encrypted);
20        let (ssrc, index) = match &result {
21            Err(Error::SrtcpSsrcDuplicated(ssrc, index)) => (*ssrc, *index as u64),
22            _ => {
23                // The SSRC and the SRTCP index (E flag cleared) as the packet gives them.
24                let ssrc = encrypted
25                    .get(4..8)
26                    .map_or(0, |b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
27                let tail = self.profile.rtcp_auth_tag_len() + self.mki_field_len();
28                let index = encrypted
29                    .len()
30                    .checked_sub(tail + SRTCP_INDEX_SIZE)
31                    .and_then(|at| encrypted.get(at..at + SRTCP_INDEX_SIZE))
32                    .map_or(0, |b| {
33                        u64::from(u32::from_be_bytes([b[0], b[1], b[2], b[3]]) & 0x7fff_ffff)
34                    });
35                (ssrc, index)
36            }
37        };
38        self.note_unprotect_result(PacketKind::Rtcp, ssrc, index, result)
39    }
40
41    fn unprotect_rtcp(&mut self, encrypted: &[u8]) -> Result<BytesMut> {
42        // A received SRTCP packet must be at least the minimum valid size for the
43        // negotiated profile: the RTCP header through the SSRC (read at bytes
44        // 4..8), the trailing SRTCP index, the MKI when the context uses one, and the
45        // auth tag that `get_rtcp_index` and the cipher read from the end (the HMAC
46        // tag for AES-CM, the AEAD tag for GCM). A shorter packet from the network
47        // would otherwise index out of bounds and panic (a remotely triggerable DoS).
48        // This is self-contained: it does not rely on the individual ciphers' own guards.
49        let auth_tag_len = self.profile.rtcp_auth_tag_len();
50        let mki_len = self.mki_field_len();
51        let min_len =
52            8 + SRTCP_INDEX_SIZE + mki_len + auth_tag_len + self.profile.aead_auth_tag_len();
53        if encrypted.len() < min_len {
54            return Err(Error::ErrTooShortRtcp);
55        }
56
57        let mut buf = encrypted;
58        rtcp::Header::unmarshal(&mut buf)?;
59
60        let key = self.receiving_key(encrypted, auth_tag_len)?;
61        self.check_key_lifetime(key, PacketKind::Rtcp)?;
62
63        let index = self.keys[key].cipher.get_rtcp_index(encrypted, mki_len);
64        let ssrc = u32::from_be_bytes([encrypted[4], encrypted[5], encrypted[6], encrypted[7]]);
65
66        // Per-SSRC state is created only once a packet for that SSRC authenticates, so packets
67        // under made-up SSRCs cannot grow the state map.
68        if let Some(state) = self.srtcp_ssrc_states.get_mut(&ssrc)
69            && let Some(replay_detector) = &mut state.replay_detector
70            && !replay_detector.check(index as u64)
71        {
72            return Err(Error::SrtcpSsrcDuplicated(ssrc, index));
73        }
74        // Refuse a further SSRC before spending a decryption on it.
75        self.check_srtcp_ssrc_capacity(ssrc)?;
76
77        let dst = self.keys[key]
78            .cipher
79            .decrypt_rtcp(encrypted, index, ssrc, mki_len)?;
80
81        let is_new = !self.srtcp_ssrc_states.contains_key(&ssrc);
82        if let Some(replay_detector) = &mut self.get_srtcp_ssrc_state(ssrc)?.replay_detector {
83            // A new SSRC's detector has not seen this index yet: check, then accept.
84            if !is_new || replay_detector.check(index as u64) {
85                replay_detector.accept();
86            }
87        }
88        self.count_packet(key, PacketKind::Rtcp);
89
90        Ok(dst)
91    }
92
93    /// EncryptRTCP marshals and encrypts an RTCP packet, writing to the dst buffer provided.
94    /// If the dst buffer does not have the capacity to hold `len(plaintext) + 14` bytes, a new one will be allocated and returned.
95    ///
96    /// The first packet of an SSRC carries SRTCP index 0, and each later one the next index
97    /// modulo 2^31 (RFC 3711 section 3.4).
98    ///
99    /// # Errors
100    ///
101    /// Fails with [`Error::ErrExceededMaxPackets`] once the master key has protected its
102    /// lifetime of SRTCP packets, 2^31 at most (RFC 3711 section 9.2, RFC 7714 section 9.4):
103    /// one more would reuse a keystream, or a GCM nonce, under the same key. See
104    /// [`ContextEvent::KeyExhausted`].
105    pub fn encrypt_rtcp(&mut self, decrypted: &[u8]) -> Result<BytesMut> {
106        if decrypted.len() < 8 {
107            return Err(Error::ErrTooShortRtcp);
108        }
109
110        let mut buf = decrypted;
111        rtcp::Header::unmarshal(&mut buf)?;
112
113        let ssrc = u32::from_be_bytes([decrypted[4], decrypted[5], decrypted[6], decrypted[7]]);
114
115        // No (master key, SSRC, index) triple is ever used twice: an SSRC's indexes are
116        // consecutive modulo 2^31, and a master key protects at most 2^31 SRTCP packets, over
117        // all its SSRCs. So an index may wrap only under another master key than the one it
118        // was first used with.
119        let key = self.sending_key;
120        self.check_key_lifetime(key, PacketKind::Rtcp)?;
121
122        let index = self.get_srtcp_ssrc_state(ssrc)?.srtcp_index;
123        let encrypt = self.srtcp_encryption;
124        let master_key = &mut self.keys[key];
125        let dst =
126            master_key
127                .cipher
128                .encrypt_rtcp(decrypted, index, ssrc, encrypt, &master_key.mki)?;
129
130        self.get_srtcp_ssrc_state(ssrc)?.srtcp_index = (index + 1) & MAX_SRTCP_INDEX;
131        self.count_packet(key, PacketKind::Rtcp);
132
133        Ok(dst)
134    }
135}