Skip to main content

rtci_srtp/
header_extension.rs

1//! Encryption of selected RTP header extension elements ([RFC 6904]).
2//!
3//! Where Cryptex ([RFC 9335]) encrypts the whole extension block and the CSRCs, RFC 6904
4//! encrypts the payload of the extension elements whose ids were negotiated as encrypted
5//! (`a=extmap:<id> urn:ietf:params:rtp-hdrext:encrypt <uri>`), and leaves the element headers,
6//! the other elements and the padding readable. A [`Context`](crate::context::Context) applies
7//! it to the ids given to
8//! [`set_encrypted_header_extensions`](crate::context::Context::set_encrypted_header_extensions).
9//! A packet protected with Cryptex is never also processed this way (RFC 9335 section 5).
10//!
11//! [RFC 6904]: https://www.rfc-editor.org/rfc/rfc6904
12//! [RFC 9335]: https://www.rfc-editor.org/rfc/rfc9335
13
14use std::ops::Range;
15
16use crypto::{RTCCrypto, SecretVec, StreamCipher};
17use shared::error::{Error, Result};
18
19use crate::cipher::{crypto_error, new_aes_cm};
20use crate::cryptex::RTP_FIXED_HEADER_LEN;
21use crate::key_derivation::{
22    LABEL_SRTP_HEADER_ENCRYPTION, LABEL_SRTP_HEADER_SALT, Prf, derive, generate_counter,
23};
24
25/// RFC 8285 one-byte header extensions.
26const PROFILE_ONE_BYTE: u16 = 0xBEDE;
27/// RFC 8285 two-byte header extensions: `0x100` and four "appbits".
28const PROFILE_TWO_BYTE: u16 = 0x1000;
29const PROFILE_TWO_BYTE_MASK: u16 = 0xFFF0;
30
31/// The header extension element ids whose payload is encrypted (RFC 6904 section 4).
32///
33/// The ids are the `extmap` ids of the session, 1 to 255 (1 to 14 can appear in one-byte
34/// headers). The empty set, the default, encrypts nothing.
35#[derive(Clone, Copy, PartialEq, Eq, Default)]
36pub struct EncryptedHeaderExtensions {
37    ids: [u64; 4],
38}
39
40impl EncryptedHeaderExtensions {
41    /// The empty set: nothing is encrypted.
42    pub const NONE: Self = Self { ids: [0; 4] };
43
44    /// The set of `ids`.
45    ///
46    /// # Errors
47    ///
48    /// Id 0 is refused: it marks padding in RFC 8285, which is never encrypted (RFC 6904
49    /// section 3).
50    pub fn new(ids: &[u8]) -> Result<Self> {
51        let mut set = Self::default();
52        for &id in ids {
53            if id == 0 {
54                return Err(Error::Other(
55                    "header extension id 0 is padding and cannot be encrypted".to_owned(),
56                ));
57            }
58            set.ids[(id >> 6) as usize] |= 1 << (id & 63);
59        }
60        Ok(set)
61    }
62
63    /// Whether the payload of elements with this id is encrypted.
64    pub fn contains(&self, id: u8) -> bool {
65        self.ids[(id >> 6) as usize] & (1 << (id & 63)) != 0
66    }
67
68    /// Whether no id is encrypted.
69    pub fn is_empty(&self) -> bool {
70        self.ids == [0; 4]
71    }
72
73    /// The ids, in ascending order.
74    pub fn ids(&self) -> impl Iterator<Item = u8> + '_ {
75        (1..=u8::MAX).filter(|id| self.contains(*id))
76    }
77}
78
79impl std::fmt::Debug for EncryptedHeaderExtensions {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_set().entries(self.ids()).finish()
82    }
83}
84
85/// The "defined by profile" field and where the extension data (RFC 3550 section 5.3.1's
86/// "header extension" proper, after the profile and length) lies in a raw RTP packet, or `None`
87/// when the packet has no extension or is too short to hold the one it announces.
88pub(crate) fn extension_data(packet: &[u8]) -> Option<(u16, Range<usize>)> {
89    let first = *packet.first()?;
90    if first & 0x10 == 0 {
91        return None;
92    }
93    let start = RTP_FIXED_HEADER_LEN + 4 * (first & 0x0F) as usize;
94    let header = packet.get(start..start + 4)?;
95    let profile = u16::from_be_bytes([header[0], header[1]]);
96    let len = 4 * u16::from_be_bytes([header[2], header[3]]) as usize;
97    let data = start + 4..start + 4 + len;
98    (packet.len() >= data.end).then_some((profile, data))
99}
100
101/// The encryption mask of RFC 6904 section 3: for each octet of the extension data, whether
102/// it is the payload of an element whose id is in `ids`. Element headers, the other elements
103/// and padding are never in it. Empty for any profile but RFC 8285's.
104///
105/// The receiver computes the same mask from the packet as it arrives, since the element
106/// headers are not encrypted. Parsing stops at the first thing that is not a well-formed
107/// element (as RFC 8285 section 4.2 has a receiver stop), leaving the rest unencrypted.
108pub(crate) fn encryption_mask(
109    profile: u16,
110    data: &[u8],
111    ids: &EncryptedHeaderExtensions,
112) -> Vec<Range<usize>> {
113    let mut mask = Vec::new();
114    let mut at = 0;
115    if profile == PROFILE_ONE_BYTE {
116        while at < data.len() {
117            let head = data[at];
118            if head == 0 {
119                // Padding.
120                at += 1;
121                continue;
122            }
123            let id = head >> 4;
124            if id == 15 {
125                // Reserved: processing stops (RFC 8285 section 4.2).
126                break;
127            }
128            let len = (head & 0x0F) as usize + 1;
129            let payload = at + 1..at + 1 + len;
130            if payload.end > data.len() {
131                break;
132            }
133            at = payload.end;
134            if ids.contains(id) {
135                mask.push(payload);
136            }
137        }
138    } else if profile & PROFILE_TWO_BYTE_MASK == PROFILE_TWO_BYTE {
139        while at < data.len() {
140            let id = data[at];
141            if id == 0 {
142                // Padding.
143                at += 1;
144                continue;
145            }
146            let Some(&len) = data.get(at + 1) else {
147                break;
148            };
149            let payload = at + 2..at + 2 + len as usize;
150            if payload.end > data.len() {
151                break;
152            }
153            at = payload.end;
154            if ids.contains(id) && !payload.is_empty() {
155                mask.push(payload);
156            }
157        }
158    }
159    mask
160}
161
162/// The header encryption key k_he and salting key k_hs of one master key (RFC 6904 section 3).
163pub(crate) struct HeaderExtensionKeys {
164    /// AES-CM keyed with k_he; `None` for the NULL cipher, whose header keystream is all zero
165    /// (RFC 6904 section 3.2).
166    cipher: Option<Box<dyn StreamCipher>>,
167    /// k_hs.
168    salt: SecretVec,
169}
170
171impl HeaderExtensionKeys {
172    /// Derives k_he (label 0x06, the length of the payload encryption key) and k_hs (label
173    /// 0x07, the length of the session salt) with the session's PRF, master key, master salt
174    /// and `index DIV kdr`.
175    ///
176    /// The keystream transform is the payload's for the AES-CM profiles. The AEAD profiles use
177    /// AES-CM of their key size (RFC 7714 section 8.3), with their 96-bit k_hs padded with zeros
178    /// on the right as their master salt is in the key derivation.
179    pub(crate) fn derive(
180        crypto: &dyn RTCCrypto,
181        prf: Prf,
182        null_cipher: bool,
183        master_key: &[u8],
184        master_salt: &[u8],
185        index_over_kdr: u64,
186    ) -> Result<Self> {
187        let cipher = if null_cipher {
188            None
189        } else {
190            let key = derive(
191                crypto,
192                prf,
193                LABEL_SRTP_HEADER_ENCRYPTION,
194                master_key,
195                master_salt,
196                index_over_kdr,
197                prf.key_len(),
198            )?;
199            Some(new_aes_cm(crypto, prf.stream_cipher(), key.as_ref())?)
200        };
201        let salt = derive(
202            crypto,
203            prf,
204            LABEL_SRTP_HEADER_SALT,
205            master_key,
206            master_salt,
207            index_over_kdr,
208            master_salt.len(),
209        )?;
210        Ok(Self { cipher, salt })
211    }
212
213    /// No keys: nothing is encrypted. For ciphers built from session keys in tests.
214    #[cfg(test)]
215    pub(crate) fn none() -> Self {
216        Self {
217            cipher: None,
218            salt: SecretVec::new(Vec::new()),
219        }
220    }
221
222    /// Encrypts, or decrypts, the payload of the extension elements of `packet` whose ids are
223    /// in `ids`, in place. The keystream uses the IV of the packet's payload (RFC 3711 section
224    /// 4.1.1) with k_hs in place of k_s, and starts at the first octet of the extension data.
225    ///
226    /// `header_len` is where the payload starts for the caller. An extension block that does
227    /// not end there is left alone: the header the caller parsed is then not this packet's, and
228    /// the keystream must never reach octets the payload transform also covers.
229    pub(crate) fn apply(
230        &mut self,
231        packet: &mut [u8],
232        header_len: usize,
233        sequence_number: u16,
234        roc: u32,
235        ssrc: u32,
236        ids: &EncryptedHeaderExtensions,
237    ) -> Result<()> {
238        if ids.is_empty() {
239            return Ok(());
240        }
241        let Some(cipher) = self.cipher.as_mut() else {
242            return Ok(());
243        };
244        let Some((profile, range)) = extension_data(packet) else {
245            return Ok(());
246        };
247        if range.end != header_len {
248            return Ok(());
249        }
250        let data = &mut packet[range];
251        let mask = encryption_mask(profile, data, ids);
252        let Some(end) = mask.last().map(|range| range.end) else {
253            return Ok(());
254        };
255
256        // The keystream up to the last encrypted octet; the mask picks the octets it applies to.
257        let mut keystream = vec![0u8; end];
258        let counter = generate_counter(sequence_number, roc, ssrc, self.salt.as_ref());
259        cipher
260            .apply_keystream(&counter, &mut keystream)
261            .map_err(crypto_error)?;
262        for range in mask {
263            for at in range {
264                data[at] ^= keystream[at];
265            }
266        }
267        Ok(())
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::test_util::hex;
275
276    fn mask_bytes(profile: u16, data: &[u8], ids: &[u8]) -> Vec<u8> {
277        let ids = EncryptedHeaderExtensions::new(ids).unwrap();
278        let mut out = vec![0u8; data.len()];
279        for range in encryption_mask(profile, data, &ids) {
280            out[range].fill(0xFF);
281        }
282        out
283    }
284
285    /// RFC 6904 section 3.1 (figure 2) and Appendix A.2: the mask covers the payloads of
286    /// elements 1, 3 and 4 and nothing else.
287    #[test]
288    fn one_byte_mask_matches_the_rfc_6904_example() {
289        let data = hex("17 414273A475262748 22 0000C8 30 8E 46 55996386B395FB 00");
290        assert_eq!(
291            mask_bytes(0xBEDE, &data, &[1, 3, 4]),
292            hex("00 FFFFFFFFFFFFFFFF 00 000000 00 FF 00 FFFFFFFFFFFFFF 00")
293        );
294        assert_eq!(mask_bytes(0xBEDE, &data, &[]), vec![0; data.len()]);
295        assert_eq!(
296            mask_bytes(0xBEDE, &data, &[2]),
297            hex("00 0000000000000000 00 FFFFFF 00 00 00 00000000000000 00")
298        );
299    }
300
301    /// RFC 6904 section 3: the mask is built for two-byte headers too; element headers, a
302    /// zero-length element and padding are not in it.
303    #[test]
304    fn two_byte_mask_covers_only_the_selected_payloads() {
305        // id 1 len 2 | padding | id 200 len 3 | id 7 len 0 | id 2 len 1 | padding
306        let data = hex("01 02 AABB 00 C8 03 CCDDEE 07 00 02 01 FF 00 00 00");
307        assert_eq!(
308            mask_bytes(0x1000, &data, &[1, 200, 7]),
309            hex("00 00 FFFF 00 00 00 FFFFFF 00 00 00 00 00 00 00 00")
310        );
311        // The appbits do not change the format.
312        assert_eq!(
313            mask_bytes(0x100F, &data, &[2]),
314            hex("00 00 0000 00 00 00 000000 00 00 00 00 FF 00 00 00")
315        );
316    }
317
318    /// Only RFC 8285 extensions have elements; a profile-specific extension is left alone, and
319    /// so is everything from a malformed or reserved element on.
320    #[test]
321    fn mask_is_empty_for_other_profiles_and_stops_at_malformed_elements() {
322        let data = hex("17 414273A475262748 22 0000C8");
323        assert_eq!(mask_bytes(0xABCD, &data, &[1, 2]), vec![0; data.len()]);
324        // Element 2 announces 16 octets and has 3: nothing from there on.
325        let data = hex("10 AA 2F 010203");
326        assert_eq!(mask_bytes(0xBEDE, &data, &[1, 2]), hex("00 FF 00 000000"));
327        // Id 15 stops the parsing.
328        let data = hex("F0 AA 10 BB");
329        assert_eq!(mask_bytes(0xBEDE, &data, &[1, 15]), hex("00 00 00 00"));
330        // A two-byte element running past the end.
331        let data = hex("01 01 AA 02 09 BB");
332        assert_eq!(mask_bytes(0x1000, &data, &[1, 2]), hex("00 00 FF 00 00 00"));
333    }
334
335    #[test]
336    fn id_zero_cannot_be_encrypted() {
337        assert!(EncryptedHeaderExtensions::new(&[1, 0]).is_err());
338        let set = EncryptedHeaderExtensions::new(&[255, 1, 64, 1]).unwrap();
339        assert_eq!(set.ids().collect::<Vec<_>>(), vec![1, 64, 255]);
340        assert!(!set.is_empty());
341        assert!(EncryptedHeaderExtensions::default().is_empty());
342    }
343
344    #[test]
345    fn extension_data_is_found_after_the_csrcs() {
346        // V=2, X, CC=1.
347        let mut packet = vec![0x91, 96, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 9, 9, 9, 9];
348        packet.extend_from_slice(&[0xBE, 0xDE, 0x00, 0x01, 0x10, 0xAA, 0x00, 0x00, 0x55]);
349        assert_eq!(extension_data(&packet), Some((0xBEDE, 20..24)));
350        // No X bit.
351        packet[0] = 0x81;
352        assert_eq!(extension_data(&packet), None);
353        // The announced length runs past the packet.
354        packet[0] = 0x91;
355        packet[19] = 9;
356        assert_eq!(extension_data(&packet), None);
357    }
358}