Skip to main content

rtci_srtp/
cryptex.rs

1//! Cryptex ([RFC 9335]): encryption of the CSRCs and RTP header extensions.
2//!
3//! When both ends signalled `a=cryptex`, a sender may protect a packet's CSRC list and its
4//! [RFC 8285] header extensions (all but the 4-byte extension header) together with the
5//! payload. Such a packet is marked by the extension's "defined by profile" field: `0xC0DE`
6//! instead of `0xBEDE` (one-byte extensions) and `0xC2DE` instead of `0x1000` (two-byte
7//! extensions). A [`Context`](crate::context::Context) applies it once its [`Cryptex`]
8//! settings say so; a receiving context always decrypts a packet so marked.
9//!
10//! [RFC 9335]: https://www.rfc-editor.org/rfc/rfc9335
11//! [RFC 8285]: https://www.rfc-editor.org/rfc/rfc8285
12
13/// The fixed part of an RTP header (RFC 3550 section 5.1).
14pub(crate) const RTP_FIXED_HEADER_LEN: usize = 12;
15/// RFC 8285 one-byte header extensions.
16pub(crate) const PROFILE_ONE_BYTE: u16 = 0xBEDE;
17/// RFC 8285 two-byte header extensions (with zero "appbits").
18pub(crate) const PROFILE_TWO_BYTE: u16 = 0x1000;
19/// RFC 9335 section 5: encrypted one-byte header extensions.
20pub(crate) const PROFILE_CRYPTEX_ONE_BYTE: u16 = 0xC0DE;
21/// RFC 9335 section 5: encrypted two-byte header extensions.
22pub(crate) const PROFILE_CRYPTEX_TWO_BYTE: u16 = 0xC2DE;
23
24/// How a [`Context`](crate::context::Context) uses Cryptex (RFC 9335).
25///
26/// The default uses none of it: packets are protected as RFC 3711 has it, and a received
27/// packet marked as Cryptex is still decrypted as one.
28#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
29pub struct Cryptex {
30    /// Protect outgoing packets that carry CSRCs or RFC 8285 header extensions with Cryptex.
31    /// Set it only once the peer has signalled that it receives Cryptex (`a=cryptex`).
32    pub send: bool,
33    /// Cryptex is mandatory (RFC 9335 section 5.2): refuse received packets that carry CSRCs
34    /// or header extensions without it, and refuse to protect a packet that has CSRCs or a
35    /// header extension and would leave without it (`send` unset, or an extension Cryptex
36    /// does not apply to).
37    pub require: bool,
38}
39
40/// Where the encrypted parts of an RTP packet are: the CSRC list runs from the fixed header
41/// to `csrc_end`, the 4-byte extension header starts at `csrc_end`, and the extension data
42/// and payload follow it.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub(crate) struct CryptexLayout {
45    pub(crate) csrc_end: usize,
46}
47
48impl CryptexLayout {
49    /// The length of the CSRC list.
50    pub(crate) fn csrc_len(&self) -> usize {
51        self.csrc_end - RTP_FIXED_HEADER_LEN
52    }
53
54    /// Where the extension data (the part after the 4-byte extension header) starts.
55    pub(crate) fn ext_data_start(&self) -> usize {
56        self.csrc_end + 4
57    }
58
59    /// The cipher's plaintext or ciphertext (RFC 9335 section 6.2): the CSRCs, then the
60    /// extension data, the payload and the padding, as one contiguous buffer.
61    pub(crate) fn gather(&self, packet: &[u8]) -> Vec<u8> {
62        let mut region = Vec::with_capacity(packet.len().saturating_sub(16));
63        region.extend_from_slice(&packet[RTP_FIXED_HEADER_LEN..self.csrc_end]);
64        region.extend_from_slice(&packet[self.ext_data_start()..]);
65        region
66    }
67
68    /// Puts a buffer [`gather`](Self::gather) made back into the packet's layout.
69    pub(crate) fn scatter(&self, packet: &mut [u8], region: &[u8]) {
70        let csrc_len = self.csrc_len();
71        packet[RTP_FIXED_HEADER_LEN..self.csrc_end].copy_from_slice(&region[..csrc_len]);
72        let start = self.ext_data_start();
73        packet[start..].copy_from_slice(&region[csrc_len..]);
74    }
75
76    /// The AEAD's associated data (RFC 9335 section 6.2): the fixed header and the
77    /// extension header, which aren't contiguous when there are CSRCs.
78    pub(crate) fn associated_data(&self, packet: &[u8]) -> [u8; 16] {
79        let mut aad = [0u8; 16];
80        aad[..RTP_FIXED_HEADER_LEN].copy_from_slice(&packet[..RTP_FIXED_HEADER_LEN]);
81        aad[RTP_FIXED_HEADER_LEN..].copy_from_slice(&packet[self.csrc_end..self.csrc_end + 4]);
82        aad
83    }
84}
85
86/// The CSRC count, the X bit and the end of the CSRC list of a raw RTP packet, or `None`
87/// when the packet is too short to hold them.
88fn csrc_end_of(packet: &[u8]) -> Option<(bool, usize)> {
89    let first = *packet.first()?;
90    let extension = first & 0x10 != 0;
91    let csrc_count = (first & 0x0F) as usize;
92    let csrc_end = RTP_FIXED_HEADER_LEN + 4 * csrc_count;
93    (packet.len() >= csrc_end).then_some((extension, csrc_end))
94}
95
96fn profile_at(packet: &[u8], at: usize) -> Option<u16> {
97    let bytes = packet.get(at..at + 2)?;
98    Some(u16::from_be_bytes([bytes[0], bytes[1]]))
99}
100
101/// RFC 9335 section 5.1: the packet a sender encrypts with Cryptex, or `None` when Cryptex
102/// doesn't apply to it (no CSRCs and no header extension, an extension other than RFC 8285's,
103/// two-byte extensions with non-zero "appbits", or a packet too short to parse). The
104/// extension's profile is replaced by its Cryptex counterpart, and a packet with CSRCs but
105/// no extension gets an empty `0xC0DE` one (the X bit set).
106pub(crate) fn sender_packet(packet: &[u8]) -> Option<(Vec<u8>, CryptexLayout)> {
107    let (extension, csrc_end) = csrc_end_of(packet)?;
108    let layout = CryptexLayout { csrc_end };
109    if extension {
110        let replacement = match profile_at(packet, csrc_end)? {
111            PROFILE_ONE_BYTE => PROFILE_CRYPTEX_ONE_BYTE,
112            PROFILE_TWO_BYTE => PROFILE_CRYPTEX_TWO_BYTE,
113            _ => return None,
114        };
115        if packet.len() < layout.ext_data_start() {
116            return None;
117        }
118        let mut out = packet.to_vec();
119        out[csrc_end..csrc_end + 2].copy_from_slice(&replacement.to_be_bytes());
120        Some((out, layout))
121    } else if csrc_end > RTP_FIXED_HEADER_LEN {
122        let mut out = Vec::with_capacity(packet.len() + 4);
123        out.extend_from_slice(&packet[..csrc_end]);
124        out.extend_from_slice(&PROFILE_CRYPTEX_ONE_BYTE.to_be_bytes());
125        out.extend_from_slice(&[0, 0]);
126        out.extend_from_slice(&packet[csrc_end..]);
127        out[0] |= 0x10;
128        Some((out, layout))
129    } else {
130        None
131    }
132}
133
134/// Whether a raw RTP packet has anything Cryptex is there to protect: a CSRC list or a header
135/// extension, of whatever kind.
136pub(crate) fn carries_csrcs_or_extension(packet: &[u8]) -> bool {
137    packet.first().is_some_and(|first| first & 0x1F != 0)
138}
139
140/// What a receiver makes of a protected packet's header (RFC 9335 section 5.2).
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub(crate) enum Received {
143    /// Marked as Cryptex: decrypt with this layout.
144    Cryptex(CryptexLayout),
145    /// Carries CSRCs or a header extension in the clear.
146    Clear,
147    /// Carries neither: Cryptex has nothing to protect.
148    Bare,
149}
150
151pub(crate) fn received(packet: &[u8]) -> Received {
152    let Some((extension, csrc_end)) = csrc_end_of(packet) else {
153        return Received::Bare;
154    };
155    if extension {
156        match profile_at(packet, csrc_end) {
157            Some(PROFILE_CRYPTEX_ONE_BYTE | PROFILE_CRYPTEX_TWO_BYTE)
158                if packet.len() >= csrc_end + 4 =>
159            {
160                Received::Cryptex(CryptexLayout { csrc_end })
161            }
162            _ => Received::Clear,
163        }
164    } else if csrc_end > RTP_FIXED_HEADER_LEN {
165        Received::Clear
166    } else {
167        Received::Bare
168    }
169}
170
171/// After decryption: the extension's profile back to its RFC 8285 value, so the header
172/// extensions parse as usual (RFC 9335 section 6.3).
173pub(crate) fn restore_profile(packet: &mut [u8], layout: CryptexLayout) {
174    let at = layout.csrc_end;
175    let restored = match profile_at(packet, at) {
176        Some(PROFILE_CRYPTEX_ONE_BYTE) => PROFILE_ONE_BYTE,
177        Some(PROFILE_CRYPTEX_TWO_BYTE) => PROFILE_TWO_BYTE,
178        _ => return,
179    };
180    packet[at..at + 2].copy_from_slice(&restored.to_be_bytes());
181}