rtci-srtp 0.1.0

Sans-I/O SRTP and SRTCP (RFC 3711, RFC 7714 AES-GCM, RFC 9335 Cryptex) for WebRTC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use super::*;
use crate::key_derivation::*;

/// The built-in provider, for tests only. Library code never resolves a default: every public
/// constructor takes the provider from its caller.
fn test_crypto_provider() -> std::sync::Arc<dyn crypto::RTCCryptoProvider> {
    crypto::default_provider().expect("a built-in crypto provider must be enabled for tests")
}

use bytes::{Buf, Bytes, BytesMut};
use lazy_static::lazy_static;

pub struct RTCPTestCase {
    ssrc: u32,
    index: usize,
    encrypted: Bytes,
    decrypted: Bytes,
}

lazy_static! {
    static ref RTCP_TEST_MASTER_KEY: Bytes = Bytes::from_static(&[
        0xfd, 0xa6, 0x25, 0x95, 0xd7, 0xf6, 0x92, 0x6f, 0x7d, 0x9c, 0x02, 0x4c, 0xc9, 0x20, 0x9f,
        0x34
    ]);

    static ref RTCP_TEST_MASTER_SALT: Bytes = Bytes::from_static(&[
        0xa9, 0x65, 0x19, 0x85, 0x54, 0x0b, 0x47, 0xbe, 0x2f, 0x27, 0xa8, 0xb8, 0x81, 0x23
    ]);

    static ref RTCP_TEST_CASES: Vec<RTCPTestCase> = vec![
        RTCPTestCase {
            ssrc:      0x66ef91ff,
            index:     0,
            encrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x00, 0x06, 0x66, 0xef, 0x91, 0xff, 0xcd, 0x34, 0xc5, 0x78, 0xb2, 0x8b,
                0xe1, 0x6b, 0xc5, 0x09, 0xd5, 0x77, 0xe4, 0xce, 0x5f, 0x20, 0x80, 0x21, 0xbd, 0x66,
                0x74, 0x65, 0xe9, 0x5f, 0x49, 0xe5, 0xf5, 0xc0, 0x68, 0x4e, 0xe5, 0x6a, 0x78, 0x07,
                0x75, 0x46, 0xed, 0x90, 0xf6, 0xdc, 0x9d, 0xef, 0x3b, 0xdf, 0xf2, 0x79, 0xa9, 0xd8,
                0x80, 0x00, 0x00, 0x01, 0x60, 0xc0, 0xae, 0xb5, 0x6f, 0x40, 0x88, 0x0e, 0x28, 0xba
            ]),
            decrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x00, 0x06, 0x66, 0xef, 0x91, 0xff, 0xdf, 0x48, 0x80, 0xdd, 0x61, 0xa6,
                0x2e, 0xd3, 0xd8, 0xbc, 0xde, 0xbe, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x16, 0x04,
                0x81, 0xca, 0x00, 0x06, 0x66, 0xef, 0x91, 0xff, 0x01, 0x10, 0x52, 0x6e, 0x54, 0x35,
                0x43, 0x6d, 0x4a, 0x68, 0x7a, 0x79, 0x65, 0x74, 0x41, 0x78, 0x77, 0x2b, 0x00, 0x00
            ]),
        },
        RTCPTestCase{
            ssrc:      0x11111111,
            index:     0,
            encrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x00, 0x06, 0x11, 0x11, 0x11, 0x11, 0x17, 0x8c, 0x15, 0xf1, 0x4b, 0x11,
                0xda, 0xf5, 0x74, 0x53, 0x86, 0x2b, 0xc9, 0x07, 0x29, 0x40, 0xbf, 0x22, 0xf6, 0x46,
                0x11, 0xa4, 0xc1, 0x3a, 0xff, 0x5a, 0xbd, 0xd0, 0xf8, 0x8b, 0x38, 0xe4, 0x95, 0x38,
                0x5d, 0xcf, 0x1b, 0xf5, 0x27, 0x77, 0xfb, 0xdb, 0x3f, 0x10, 0x68, 0x99, 0xd8, 0xad,
                0x80, 0x00, 0x00, 0x01, 0x34, 0x3c, 0x2e, 0x83, 0x17, 0x13, 0x93, 0x69, 0xcf, 0xc0
            ]),
            decrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x00, 0x06, 0x11, 0x11, 0x11, 0x11, 0xdf, 0x48, 0x80, 0xdd, 0x61, 0xa6,
                0x2e, 0xd3, 0xd8, 0xbc, 0xde, 0xbe, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x16, 0x04,
                0x81, 0xca, 0x00, 0x06, 0x66, 0xef, 0x91, 0xff, 0x01, 0x10, 0x52, 0x6e, 0x54, 0x35,
                0x43, 0x6d, 0x4a, 0x68, 0x7a, 0x79, 0x65, 0x74, 0x41, 0x78, 0x77, 0x2b, 0x00, 0x00
            ]),
        },
        RTCPTestCase{
            ssrc:      0x11111111,
            index:     0x7ffffffe, // Upper boundary of index
            encrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x00, 0x06, 0x11, 0x11, 0x11, 0x11, 0x17, 0x8c, 0x15, 0xf1, 0x4b, 0x11,
                0xda, 0xf5, 0x74, 0x53, 0x86, 0x2b, 0xc9, 0x07, 0x29, 0x40, 0xbf, 0x22, 0xf6, 0x46,
                0x11, 0xa4, 0xc1, 0x3a, 0xff, 0x5a, 0xbd, 0xd0, 0xf8, 0x8b, 0x38, 0xe4, 0x95, 0x38,
                0x5d, 0xcf, 0x1b, 0xf5, 0x27, 0x77, 0xfb, 0xdb, 0x3f, 0x10, 0x68, 0x99, 0xd8, 0xad,
                0xff, 0xff, 0xff, 0xff, 0x5a, 0x99, 0xce, 0xed, 0x9f, 0x2e, 0x4d, 0x9d, 0xfa, 0x97
            ]),
            decrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x0, 0x6, 0x11, 0x11, 0x11, 0x11, 0x4, 0x99, 0x47, 0x53, 0xc4, 0x1e,
                0xb9, 0xde, 0x52, 0xa3, 0x1d, 0x77, 0x2f, 0xff, 0xcc, 0x75, 0xbb, 0x6a, 0x29, 0xb8,
                0x1, 0xb7, 0x2e, 0x4b, 0x4e, 0xcb, 0xa4, 0x81, 0x2d, 0x46, 0x4, 0x5e, 0x86, 0x90,
                0x17, 0x4f, 0x4d, 0x78, 0x2f, 0x58, 0xb8, 0x67, 0x91, 0x89, 0xe3, 0x61, 0x1, 0x7d
            ]),
        },
        RTCPTestCase{
            ssrc:      0x11111111,
            index:     0x7fffffff, // Will be wrapped to 0
            encrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x00, 0x06, 0x11, 0x11, 0x11, 0x11, 0x17, 0x8c, 0x15, 0xf1, 0x4b, 0x11,
                0xda, 0xf5, 0x74, 0x53, 0x86, 0x2b, 0xc9, 0x07, 0x29, 0x40, 0xbf, 0x22, 0xf6, 0x46,
                0x11, 0xa4, 0xc1, 0x3a, 0xff, 0x5a, 0xbd, 0xd0, 0xf8, 0x8b, 0x38, 0xe4, 0x95, 0x38,
                0x5d, 0xcf, 0x1b, 0xf5, 0x27, 0x77, 0xfb, 0xdb, 0x3f, 0x10, 0x68, 0x99, 0xd8, 0xad,
                0x80, 0x00, 0x00, 0x00, 0x7d, 0x51, 0xf8, 0x0e, 0x56, 0x40, 0x72, 0x7b, 0x9e, 0x02
            ]),
            decrypted: Bytes::from_static(&[
                0x80, 0xc8, 0x0, 0x6, 0x11, 0x11, 0x11, 0x11, 0xda, 0xb5, 0xe0, 0x56, 0x9a, 0x4a,
                0x74, 0xed, 0x8a, 0x54, 0xc, 0xcf, 0xd5, 0x9, 0xb1, 0x40, 0x1, 0x42, 0xc3, 0x9a,
                0x76, 0x0, 0xa9, 0xd4, 0xf7, 0x29, 0x9e, 0x51, 0xfb, 0x3c, 0xc1, 0x74, 0x72, 0xf9,
                0x52, 0xb1, 0x92, 0x31, 0xca, 0x22, 0xab, 0x3e, 0xc5, 0x5f, 0x83, 0x34, 0xf0, 0x28
            ]),
        },
    ];
}

#[test]
fn test_rtcp_lifecycle() -> Result<()> {
    let mut encrypt_context = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        None,
        test_crypto_provider().crypto(),
    )?;
    let mut decrypt_context = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        None,
        test_crypto_provider().crypto(),
    )?;

    for test_case in &*RTCP_TEST_CASES {
        let decrypt_result = decrypt_context.decrypt_rtcp(&test_case.encrypted)?;
        assert_eq!(
            decrypt_result, test_case.decrypted,
            "RTCP failed to decrypt"
        );

        // The known answers were made with SRTCP index 1.
        encrypt_context.set_index(test_case.ssrc, test_case.index + 1);
        let encrypt_result = encrypt_context.encrypt_rtcp(&test_case.decrypted)?;
        assert_eq!(
            encrypt_result, test_case.encrypted,
            "RTCP failed to encrypt"
        );
    }

    Ok(())
}

#[test]
fn test_rtcp_invalid_auth_tag() -> Result<()> {
    let auth_tag_len = ProtectionProfile::Aes128CmHmacSha1_80.rtcp_auth_tag_len();

    let mut decrypt_context = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        None,
        test_crypto_provider().crypto(),
    )?;

    let decrypt_result = decrypt_context.decrypt_rtcp(&RTCP_TEST_CASES[0].encrypted)?;
    assert_eq!(
        decrypt_result, RTCP_TEST_CASES[0].decrypted,
        "RTCP failed to decrypt"
    );

    // Zero out auth tag
    let mut rtcp_packet = BytesMut::new();
    rtcp_packet.extend_from_slice(&RTCP_TEST_CASES[0].encrypted);
    let rtcp_packet_len = rtcp_packet.len();
    rtcp_packet[rtcp_packet_len - auth_tag_len..].copy_from_slice(&vec![0; auth_tag_len]);
    let rtcp_packet = rtcp_packet.freeze();
    let decrypt_result = decrypt_context.decrypt_rtcp(&rtcp_packet);
    assert!(
        decrypt_result.is_err(),
        "Was able to decrypt RTCP packet with invalid Auth Tag"
    );

    Ok(())
}

#[test]
fn test_rtcp_replay_detector_separation() -> Result<()> {
    let mut decrypt_context = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        Some(srtcp_replay_protection(64)?),
        test_crypto_provider().crypto(),
    )?;

    let rtcp_packet1 = RTCP_TEST_CASES[0].encrypted.clone();
    let decrypt_result1 = decrypt_context.decrypt_rtcp(&rtcp_packet1)?;
    assert_eq!(
        decrypt_result1, RTCP_TEST_CASES[0].decrypted,
        "RTCP failed to decrypt"
    );

    let rtcp_packet2 = RTCP_TEST_CASES[1].encrypted.clone();
    let decrypt_result2 = decrypt_context.decrypt_rtcp(&rtcp_packet2)?;
    assert_eq!(
        decrypt_result2, RTCP_TEST_CASES[1].decrypted,
        "RTCP failed to decrypt"
    );

    let result = decrypt_context.decrypt_rtcp(&rtcp_packet1);
    assert!(
        result.is_err(),
        "Was able to decrypt duplicated RTCP packet"
    );

    let result = decrypt_context.decrypt_rtcp(&rtcp_packet2);
    assert!(
        result.is_err(),
        "Was able to decrypt duplicated RTCP packet"
    );

    Ok(())
}

fn get_rtcp_index(encrypted: &Bytes, auth_tag_len: usize) -> u32 {
    let tail_offset = encrypted.len() - (auth_tag_len + SRTCP_INDEX_SIZE);
    let reader = &mut encrypted.slice(tail_offset..tail_offset + SRTCP_INDEX_SIZE);
    //^(1 << 31)
    reader.get_u32() & 0x7FFFFFFF
}

#[test]
fn test_encrypt_rtcp_separation() -> Result<()> {
    let mut encrypt_context = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        None,
        test_crypto_provider().crypto(),
    )?;

    let auth_tag_len = ProtectionProfile::Aes128CmHmacSha1_80.rtcp_auth_tag_len();

    let mut decrypt_context = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        Some(srtcp_replay_protection(64)?),
        test_crypto_provider().crypto(),
    )?;

    let inputs = vec![
        RTCP_TEST_CASES[0].decrypted.clone(),
        RTCP_TEST_CASES[1].decrypted.clone(),
        RTCP_TEST_CASES[0].decrypted.clone(),
        RTCP_TEST_CASES[1].decrypted.clone(),
    ];
    let mut encrypted_rctps = vec![];

    for input in &inputs {
        let encrypted = encrypt_context.encrypt_rtcp(input)?;
        encrypted_rctps.push(encrypted);
    }

    // RFC 3711 section 3.4: the index is zero before the first packet of an SSRC, and one more
    // after each packet.
    for (i, expected_index) in [0, 0, 1, 1].iter().enumerate() {
        assert_eq!(
            *expected_index,
            get_rtcp_index(&encrypted_rctps[i].clone().freeze(), auth_tag_len),
            "RTCP index does not match"
        );
    }

    for (i, output) in encrypted_rctps.iter().enumerate() {
        let decrypted = decrypt_context.decrypt_rtcp(output)?;
        assert_eq!(inputs[i], decrypted);
    }

    Ok(())
}

/// Short SRTCP packets — anything below the minimum size (RTCP header through
/// the SSRC + trailing SRTCP index + auth tag) — must error, not panic. Before
/// the length guard, `get_rtcp_index` and the `encrypted[4..8]` SSRC read
/// indexed unconditionally, so a short packet from the network triggered an
/// index-out-of-bounds panic (a remotely triggerable DoS on the media path).
#[test]
fn test_rtcp_short_packet_errors() -> Result<()> {
    // Cover both cipher families end-to-end through `Context::decrypt_rtcp`.
    // AEAD-128-GCM takes a 12-byte salt vs 14 for AES-CM.
    let cases: [(ProtectionProfile, &[u8]); 2] = [
        (
            ProtectionProfile::Aes128CmHmacSha1_80,
            &RTCP_TEST_MASTER_SALT[..],
        ),
        (
            ProtectionProfile::AeadAes128Gcm,
            &RTCP_TEST_MASTER_SALT[..12],
        ),
    ];

    for (profile, salt) in cases {
        let mut ctx = Context::new(
            &RTCP_TEST_MASTER_KEY,
            salt,
            profile,
            None,
            None,
            test_crypto_provider().crypto(),
        )?;

        // Slices of a real packet (its first 4 bytes are a valid RTCP header, so
        // the header parse succeeds and pre-fix execution reached the
        // out-of-bounds indexing). Every length below the minimum valid SRTCP
        // size for the profile must be rejected, not panic.
        let min_len =
            8 + SRTCP_INDEX_SIZE + profile.rtcp_auth_tag_len() + profile.aead_auth_tag_len();
        for len in 0..min_len {
            let short = RTCP_TEST_CASES[0].encrypted.slice(0..len);
            assert!(
                ctx.decrypt_rtcp(&short).is_err(),
                "decrypt_rtcp must reject a {len}-byte packet (profile min {min_len}), not panic"
            );
        }
    }

    Ok(())
}

/// SRTCP packets that fail authentication must not create per-SSRC state.
#[test]
fn test_unauthenticated_srtcp_packets_do_not_create_ssrc_state() -> Result<()> {
    let mut ctx = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        None,
        test_crypto_provider().crypto(),
    )?;
    for ssrc in 0..1000u32 {
        // RTCP receiver report header (V=2, PT=201, length=1) + SSRC + E|index + bogus tag.
        let mut raw = vec![0x80, 0xc9, 0x00, 0x01];
        raw.extend_from_slice(&ssrc.to_be_bytes());
        raw.extend_from_slice(&[0x80, 0x00, 0x00, 0x01]);
        raw.extend_from_slice(&[0u8; 10]);
        assert!(ctx.decrypt_rtcp(&raw).is_err());
    }
    assert!(
        ctx.srtcp_ssrc_states.is_empty(),
        "{} SSRC states were created by unauthenticated packets",
        ctx.srtcp_ssrc_states.len()
    );
    Ok(())
}

/// An SRTCP packet with the E flag clear is authenticated like any other: a forged one creates
/// no per-SSRC state and is not accepted. It used to be returned as plaintext unchecked.
#[test]
fn test_unencrypted_srtcp_with_a_forged_tag_is_rejected() -> Result<()> {
    let mut ctx = Context::new(
        &RTCP_TEST_MASTER_KEY,
        &RTCP_TEST_MASTER_SALT,
        ProtectionProfile::Aes128CmHmacSha1_80,
        None,
        Some(srtcp_replay_protection(64)?),
        test_crypto_provider().crypto(),
    )?;
    // BYE for SSRC 0x11111111, E=0, index 0x7ffffff0 (far ahead), bogus tag.
    let mut raw = vec![0x81, 0xcb, 0x00, 0x01, 0x11, 0x11, 0x11, 0x11];
    raw.extend_from_slice(&[0x7f, 0xff, 0xff, 0xf0]);
    raw.extend_from_slice(&[0u8; 10]);
    assert!(ctx.decrypt_rtcp(&raw).is_err());
    assert!(ctx.srtcp_ssrc_states.is_empty());
    Ok(())
}

/// One context keeps SRTCP state for at most `MAX_SSRC_STATES` SSRCs: a further SSRC is
/// refused (before decryption on the receiving side) and existing SSRCs keep working.
#[test]
fn test_srtcp_ssrc_states_are_capped() -> Result<()> {
    let new_context = || {
        Context::new(
            &RTCP_TEST_MASTER_KEY,
            &RTCP_TEST_MASTER_SALT,
            ProtectionProfile::Aes128CmHmacSha1_80,
            None,
            Some(srtcp_replay_protection(64)?),
            test_crypto_provider().crypto(),
        )
    };
    // RTCP receiver report header (V=2, PT=201, length=1) + SSRC.
    let report = |ssrc: u32| -> Vec<u8> {
        let mut raw = vec![0x80, 0xc9, 0x00, 0x01];
        raw.extend_from_slice(&ssrc.to_be_bytes());
        raw
    };

    let mut sender = new_context()?;
    let mut receiver = new_context()?;
    for ssrc in 0..MAX_SSRC_STATES as u32 {
        let protected = sender.encrypt_rtcp(&report(ssrc))?;
        receiver.decrypt_rtcp(&protected)?;
    }
    assert_eq!(sender.srtcp_ssrc_states.len(), MAX_SSRC_STATES);
    assert_eq!(receiver.srtcp_ssrc_states.len(), MAX_SSRC_STATES);

    let extra = MAX_SSRC_STATES as u32;
    let err = sender
        .encrypt_rtcp(&report(extra))
        .expect_err("the sender took one SSRC too many");
    assert!(
        matches!(err, Error::SrtpTooManySsrcs(s, _) if s == extra),
        "{err:?}"
    );

    let protected = new_context()?.encrypt_rtcp(&report(extra))?;
    let err = receiver
        .decrypt_rtcp(&protected)
        .expect_err("the receiver took one SSRC too many");
    assert!(
        matches!(err, Error::SrtpTooManySsrcs(s, _) if s == extra),
        "{err:?}"
    );
    assert_eq!(receiver.srtcp_ssrc_states.len(), MAX_SSRC_STATES);

    let protected = sender.encrypt_rtcp(&report(7))?;
    assert_eq!(receiver.decrypt_rtcp(&protected)?.to_vec(), report(7));
    Ok(())
}