Skip to main content

rtci_srtp/context/
srtp.rs

1use super::*;
2use crate::cryptex;
3use shared::{
4    error::{Error, Result},
5    marshal::{MarshalSize, Unmarshal},
6};
7
8use bytes::BytesMut;
9
10impl Context {
11    /// Decrypts an SRTP packet whose header has already been parsed.
12    ///
13    /// Saves re-parsing when the caller needed the header to route the packet. The header must
14    /// be the one belonging to `encrypted`.
15    ///
16    /// # Errors
17    ///
18    /// Fails if authentication fails, if the packet is a replay, if it is too short to hold
19    /// the profile's auth tag, if it names a master key the context does not have, or with
20    /// [`Error::ErrExceededMaxPackets`] once the master key reached its lifetime or the packet
21    /// index would pass 2^48 - 1 (RFC 3711 sections 3.3.1 and 9.2).
22    pub fn decrypt_rtp_with_header(
23        &mut self,
24        encrypted: &[u8],
25        header: &rtp::Header,
26    ) -> Result<BytesMut> {
27        let result = self.unprotect_rtp(encrypted, header);
28        self.note_unprotect_result(
29            PacketKind::Rtp,
30            header.ssrc,
31            u64::from(header.sequence_number),
32            result,
33        )
34    }
35
36    fn unprotect_rtp(&mut self, encrypted: &[u8], header: &rtp::Header) -> Result<BytesMut> {
37        let auth_tag_len = self.profile.rtp_auth_tag_len();
38        let mki_len = self.mki_field_len();
39        if encrypted.len() < header.marshal_size() + auth_tag_len + mki_len {
40            return Err(Error::ErrTooShortRtp);
41        }
42
43        // The MKI, which nothing authenticates, only selects the key the packet is then
44        // authenticated with.
45        let key = self.receiving_key(encrypted, auth_tag_len)?;
46        self.check_key_lifetime(key, PacketKind::Rtp)?;
47
48        // Per-SSRC state is created only once a packet for that SSRC authenticates, so packets
49        // under made-up SSRCs cannot grow the state map.
50        let (roc, diff) = match self.srtp_ssrc_states.get_mut(&header.ssrc) {
51            Some(state) => {
52                let (roc, diff, overflow) = state.next_rollover_count(header.sequence_number);
53                if overflow {
54                    // The estimate is past ROC 2^32 - 1, i.e. packet index 2^48 or more. The
55                    // rollover counter does not wrap under a master key (RFC 3711 section
56                    // 3.3.1, RFC 7714 section 13.1): trying the packet with ROC 0 would accept
57                    // a keystream (or GCM nonce) used at the start of the stream.
58                    return Err(Error::ErrExceededMaxPackets);
59                }
60                if let Some(replay_detector) = &mut state.replay_detector
61                    && !replay_detector.check(header.sequence_number as u64)
62                {
63                    return Err(Error::SrtpSsrcDuplicated(
64                        header.ssrc,
65                        header.sequence_number,
66                    ));
67                }
68                (roc, diff)
69            }
70            None => {
71                // Refuse a further SSRC before spending a decryption on it.
72                self.check_srtp_ssrc_capacity(header.ssrc)?;
73                let fresh = SrtpSsrcState {
74                    ssrc: header.ssrc,
75                    ..Default::default()
76                };
77                let (roc, diff, _) = fresh.next_rollover_count(header.sequence_number);
78                (roc, diff)
79            }
80        };
81
82        let mki_end = encrypted.len() - auth_tag_len;
83        let options = PacketOptions {
84            mki: &encrypted[mki_end - mki_len..mki_end],
85            header_extensions: &self.encrypted_header_extensions,
86        };
87        let cipher = &mut self.keys[key].cipher;
88        let dst = match cryptex::received(encrypted) {
89            cryptex::Received::Cryptex(layout) => {
90                let mut dst =
91                    cipher.decrypt_rtp_cryptex(encrypted, header, roc, layout, options)?;
92                cryptex::restore_profile(&mut dst, layout);
93                dst
94            }
95            cryptex::Received::Clear if self.cryptex.require => {
96                // Authenticate before blaming the peer: only a packet it really sent is a
97                // violation of the policy (RFC 9335 section 5.2). The packet is discarded
98                // either way, and leaves no state behind.
99                cipher.decrypt_rtp(encrypted, header, roc, options)?;
100                if !self.cryptex_violation_reported {
101                    self.cryptex_violation_reported = true;
102                    self.events
103                        .push_back(ContextEvent::CryptexRequiredViolation { ssrc: header.ssrc });
104                }
105                return Err(Error::Other(format!(
106                    "SRTP packet (SSRC {}, sequence number {}) carries CSRCs or header \
107                     extensions without Cryptex, which is required",
108                    header.ssrc, header.sequence_number
109                )));
110            }
111            _ => cipher.decrypt_rtp(encrypted, header, roc, options)?,
112        };
113        {
114            let is_new = !self.srtp_ssrc_states.contains_key(&header.ssrc);
115            let state = self.get_srtp_ssrc_state(header.ssrc)?;
116            if let Some(replay_detector) = &mut state.replay_detector {
117                // A new SSRC's detector has not seen this sequence number yet: check, then accept.
118                if !is_new || replay_detector.check(header.sequence_number as u64) {
119                    replay_detector.accept();
120                }
121            }
122            state.update_rollover_count(header.sequence_number, diff);
123        }
124        self.count_packet(key, PacketKind::Rtp);
125
126        Ok(dst)
127    }
128
129    /// DecryptRTP decrypts a RTP packet with an encrypted payload
130    pub fn decrypt_rtp(&mut self, encrypted: &[u8]) -> Result<BytesMut> {
131        let mut buf = encrypted;
132        let header = rtp::Header::unmarshal(&mut buf)?;
133        self.decrypt_rtp_with_header(encrypted, &header)
134    }
135
136    /// Encrypts an RTP payload, using an already-parsed header.
137    ///
138    /// Saves re-parsing when the caller has just built the header. Returns the full protected
139    /// packet, header included.
140    ///
141    /// # Errors
142    ///
143    /// Fails if the SRTP context has no key for this SSRC, if the cipher rejects the input, or
144    /// with [`Error::SrtpIndexReused`] if this packet index (ROC and sequence number) already
145    /// protected a different packet, or lies more than a window behind the highest index sent.
146    /// The same packet under the same index (a retransmission) is protected again, which yields
147    /// the same bytes.
148    ///
149    /// Fails with [`Error::ErrExceededMaxPackets`] once the master key reached its lifetime, or
150    /// the stream its 2^48th packet (RFC 3711 sections 3.3.1 and 9.2); see
151    /// [`ContextEvent::KeyExhausted`].
152    ///
153    /// With Cryptex required ([`Cryptex::require`]), fails for a packet that has CSRCs or a
154    /// header extension and cannot be protected with Cryptex (an extension that is not RFC
155    /// 8285's, or two-byte headers with non-zero "appbits"): nothing leaves with them in the
156    /// clear.
157    pub fn encrypt_rtp_with_header(
158        &mut self,
159        plaintext: &[u8],
160        header: &rtp::Header,
161    ) -> Result<BytesMut> {
162        if plaintext.len() < header.marshal_size() {
163            return Err(Error::ErrTooShortRtp);
164        }
165        let key = self.sending_key;
166        self.check_key_lifetime(key, PacketKind::Rtp)?;
167
168        let digest = self.sent_digest_hasher.hash_one(plaintext);
169        let (roc, diff, index, is_new) = {
170            let state = self.get_srtp_ssrc_state(header.ssrc)?;
171            let (roc, diff, ovf) = state.next_rollover_count(header.sequence_number);
172            if ovf {
173                // ... when 2^48 SRTP packets or 2^31 SRTCP packets have been secured with the same key
174                // (whichever occurs before), the key management MUST be called to provide new master key(s)
175                // (previously stored and used keys MUST NOT be used again), or the session MUST be terminated.
176                // https://www.rfc-editor.org/rfc/rfc3711#section-9.2
177                return Err(Error::ErrExceededMaxPackets);
178            }
179
180            // Each packet index is protected at most once (RFC 3711 Section 3.3.1, RFC 7714
181            // Section 8.1).
182            let index = ((roc as u64) << 16) | header.sequence_number as u64;
183            let sent = state.sent_indexes.get_or_insert_with(SentIndexes::new);
184            let is_new = match sent.check(index, digest) {
185                SendIndexUse::New => true,
186                SendIndexUse::SamePacket => false,
187                SendIndexUse::Refused => {
188                    return Err(Error::SrtpIndexReused(header.ssrc, header.sequence_number));
189                }
190            };
191            (roc, diff, index, is_new)
192        };
193
194        let cryptex_packet = self
195            .cryptex
196            .send
197            .then(|| cryptex::sender_packet(plaintext))
198            .flatten();
199        if cryptex_packet.is_none()
200            && self.cryptex.require
201            && cryptex::carries_csrcs_or_extension(plaintext)
202        {
203            // RFC 9335 section 5.1 applies Cryptex to RFC 8285 extensions only, and the peer,
204            // under the same policy, discards anything else that has CSRCs or an extension.
205            return Err(Error::Other(format!(
206                "RTP packet (SSRC {}, sequence number {}) has CSRCs or a header extension that \
207                 Cryptex, which is required, cannot protect",
208                header.ssrc, header.sequence_number
209            )));
210        }
211
212        let master_key = &mut self.keys[key];
213        let options = PacketOptions {
214            mki: &master_key.mki,
215            header_extensions: &self.encrypted_header_extensions,
216        };
217        let dst = match cryptex_packet {
218            Some((packet, layout)) => master_key
219                .cipher
220                .encrypt_rtp_cryptex(&packet, header, roc, layout, options)?,
221            None => master_key
222                .cipher
223                .encrypt_rtp(plaintext, header, roc, options)?,
224        };
225
226        if is_new {
227            let state = self.get_srtp_ssrc_state(header.ssrc)?;
228            if let Some(sent) = state.sent_indexes.as_mut() {
229                sent.record(index, digest);
230            }
231            state.update_rollover_count(header.sequence_number, diff);
232        }
233        // Protecting the same packet again counts too: the count is of packets secured with the
234        // key, and it only ever errs on the side of re-keying early.
235        self.count_packet(key, PacketKind::Rtp);
236
237        Ok(dst)
238    }
239
240    /// EncryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
241    /// If the dst buffer does not have the capacity to hold `len(plaintext) + 10` bytes, a new one will be allocated and returned.
242    pub fn encrypt_rtp(&mut self, plaintext: &[u8]) -> Result<BytesMut> {
243        let mut buf = plaintext;
244        let header = rtp::Header::unmarshal(&mut buf)?;
245        self.encrypt_rtp_with_header(plaintext, &header)
246    }
247}