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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Cryptex (RFC 9335) against the RFC's test vectors (Appendix A).

use super::*;

fn test_crypto_provider() -> std::sync::Arc<dyn crypto::RTCCryptoProvider> {
    crypto::default_provider().expect("a built-in crypto provider must be enabled for tests")
}

type Vector = (&'static str, &'static [u8], &'static [u8]);

/// Appendix A.1: AES_CM_128_HMAC_SHA1_80.
const AES_CM_KEY: [u8; 16] = [
    0xe1, 0xf9, 0x7a, 0x0d, 0x3e, 0x01, 0x8b, 0xe0, 0xd6, 0x4f, 0xa3, 0x2c, 0x06, 0xde, 0x41, 0x39,
];
const AES_CM_SALT: [u8; 14] = [
    0x0e, 0xc6, 0x75, 0xad, 0x49, 0x8a, 0xfe, 0xeb, 0xb6, 0x96, 0x0b, 0x3a, 0xab, 0xe6,
];

/// Appendix A.2: AEAD_AES_128_GCM.
const GCM_KEY: [u8; 16] = [
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
];
const GCM_SALT: [u8; 12] = [
    0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab,
];

const AES_CM_VECTORS: &[Vector] = &[
    // RFC 9335 A.1.1: RTP Packet with One-Byte Header Extension.
    (
        "A.1.1",
        &[
            0x90, 0x0f, 0x12, 0x35, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xbe, 0xde,
            0x00, 0x01, 0x51, 0x00, 0x02, 0x00, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x90, 0x0f, 0x12, 0x35, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xc0, 0xde,
            0x00, 0x01, 0xeb, 0x92, 0x36, 0x52, 0x51, 0xc3, 0xe0, 0x36, 0xf8, 0xde, 0x27, 0xe9,
            0xc2, 0x7e, 0xe3, 0xe0, 0xb4, 0x65, 0x1d, 0x9f, 0xbc, 0x42, 0x18, 0xa7, 0x02, 0x44,
            0x52, 0x2f, 0x34, 0xa5,
        ],
    ),
    // RFC 9335 A.1.2: RTP Packet with Two-Byte Header Extension.
    (
        "A.1.2",
        &[
            0x90, 0x0f, 0x12, 0x36, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x10, 0x00,
            0x00, 0x01, 0x05, 0x02, 0x00, 0x02, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x90, 0x0f, 0x12, 0x36, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xc2, 0xde,
            0x00, 0x01, 0x4e, 0xd9, 0xcc, 0x4e, 0x6a, 0x71, 0x2b, 0x30, 0x96, 0xc5, 0xca, 0x77,
            0x33, 0x9d, 0x42, 0x04, 0xce, 0x0d, 0x77, 0x39, 0x6c, 0xab, 0x69, 0x58, 0x5f, 0xbc,
            0xe3, 0x81, 0x94, 0xa5,
        ],
    ),
    // RFC 9335 A.1.3: RTP Packet with One-Byte Header Extension and CSRC Fields.
    (
        "A.1.3",
        &[
            0x92, 0x0f, 0x12, 0x38, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0xbe, 0xde, 0x00, 0x01, 0x51, 0x00, 0x02, 0x00,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x38, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x8b, 0xb6,
            0xe1, 0x2b, 0x5c, 0xff, 0x16, 0xdd, 0xc0, 0xde, 0x00, 0x01, 0x92, 0x83, 0x8c, 0x8c,
            0x09, 0xe5, 0x83, 0x93, 0xe1, 0xde, 0x3a, 0x9a, 0x74, 0x73, 0x4d, 0x67, 0x45, 0x67,
            0x13, 0x38, 0xc3, 0xac, 0xf1, 0x1d, 0xa2, 0xdf, 0x84, 0x23, 0xbe, 0xe0,
        ],
    ),
    // RFC 9335 A.1.4: RTP Packet with Two-Byte Header Extension and CSRC Fields.
    (
        "A.1.4",
        &[
            0x92, 0x0f, 0x12, 0x39, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0x10, 0x00, 0x00, 0x01, 0x05, 0x02, 0x00, 0x02,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x39, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xf7, 0x0e,
            0x51, 0x3e, 0xb9, 0x0b, 0x9b, 0x25, 0xc2, 0xde, 0x00, 0x01, 0xbb, 0xed, 0x48, 0x48,
            0xfa, 0xa6, 0x44, 0x66, 0x5f, 0x3d, 0x7f, 0x34, 0x12, 0x59, 0x14, 0xe9, 0xf4, 0xd0,
            0xae, 0x92, 0x3c, 0x6f, 0x47, 0x9b, 0x95, 0xa0, 0xf7, 0xb5, 0x31, 0x33,
        ],
    ),
    // RFC 9335 A.1.5: RTP Packet with Empty One-Byte Header Extension and CSRC Fields.
    (
        "A.1.5",
        &[
            0x92, 0x0f, 0x12, 0x3a, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0xbe, 0xde, 0x00, 0x00, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x3a, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x71, 0x30,
            0xb6, 0xab, 0xfe, 0x2a, 0xb0, 0xe3, 0xc0, 0xde, 0x00, 0x00, 0xe3, 0xd9, 0xf6, 0x4b,
            0x25, 0xc9, 0xe7, 0x4c, 0xb4, 0xcf, 0x8e, 0x43, 0xfb, 0x92, 0xe3, 0x78, 0x1c, 0x2c,
            0x0c, 0xea, 0xb6, 0xb3, 0xa4, 0x99, 0xa1, 0x4c,
        ],
    ),
    // RFC 9335 A.1.6: RTP Packet with Empty Two-Byte Header Extension and CSRC Fields.
    (
        "A.1.6",
        &[
            0x92, 0x0f, 0x12, 0x3b, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0x10, 0x00, 0x00, 0x00, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x3b, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xcb, 0xf2,
            0x4c, 0x12, 0x43, 0x30, 0xe1, 0xc8, 0xc2, 0xde, 0x00, 0x00, 0x59, 0x9d, 0xd4, 0x5b,
            0xc9, 0xd6, 0x87, 0xb6, 0x03, 0xe8, 0xb5, 0x9d, 0x77, 0x1f, 0xd3, 0x8e, 0x88, 0xb1,
            0x70, 0xe0, 0xcd, 0x31, 0xe1, 0x25, 0xea, 0xbe,
        ],
    ),
];

const GCM_VECTORS: &[Vector] = &[
    // RFC 9335 A.2.1: RTP Packet with One-Byte Header Extension.
    (
        "A.2.1",
        &[
            0x90, 0x0f, 0x12, 0x35, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xbe, 0xde,
            0x00, 0x01, 0x51, 0x00, 0x02, 0x00, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x90, 0x0f, 0x12, 0x35, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xc0, 0xde,
            0x00, 0x01, 0x39, 0x97, 0x2d, 0xc9, 0x57, 0x2c, 0x4d, 0x99, 0xe8, 0xfc, 0x35, 0x5d,
            0xe7, 0x43, 0xfb, 0x2e, 0x94, 0xf9, 0xd8, 0xff, 0x54, 0xe7, 0x2f, 0x41, 0x93, 0xbb,
            0xc5, 0xc7, 0x4f, 0xfa, 0xb0, 0xfa, 0x9f, 0xa0, 0xfb, 0xeb,
        ],
    ),
    // RFC 9335 A.2.2: RTP Packet with Two-Byte Header Extension.
    (
        "A.2.2",
        &[
            0x90, 0x0f, 0x12, 0x36, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x10, 0x00,
            0x00, 0x01, 0x05, 0x02, 0x00, 0x02, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x90, 0x0f, 0x12, 0x36, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xc2, 0xde,
            0x00, 0x01, 0xbb, 0x75, 0xa4, 0xc5, 0x45, 0xcd, 0x1f, 0x41, 0x3b, 0xdb, 0x7d, 0xaa,
            0x2b, 0x1e, 0x32, 0x63, 0xde, 0x31, 0x36, 0x67, 0xc9, 0x63, 0x24, 0x90, 0x81, 0xb3,
            0x5a, 0x65, 0xf5, 0xcb, 0x6c, 0x88, 0xb3, 0x94, 0x23, 0x5f,
        ],
    ),
    // RFC 9335 A.2.3: RTP Packet with One-Byte Header Extension and CSRC Fields.
    (
        "A.2.3",
        &[
            0x92, 0x0f, 0x12, 0x38, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0xbe, 0xde, 0x00, 0x01, 0x51, 0x00, 0x02, 0x00,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x38, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x63, 0xbb,
            0xcc, 0xc4, 0xa7, 0xf6, 0x95, 0xc4, 0xc0, 0xde, 0x00, 0x01, 0x8a, 0xd7, 0xc7, 0x1f,
            0xac, 0x70, 0xa8, 0x0c, 0x92, 0x86, 0x6b, 0x4c, 0x6b, 0xa9, 0x85, 0x46, 0xef, 0x91,
            0x35, 0x86, 0xe9, 0x5f, 0xfa, 0xaf, 0xfe, 0x95, 0x68, 0x85, 0xbb, 0x06, 0x47, 0xa8,
            0xbc, 0x09, 0x4a, 0xc8,
        ],
    ),
    // RFC 9335 A.2.4: RTP Packet with Two-Byte Header Extension and CSRC Fields.
    (
        "A.2.4",
        &[
            0x92, 0x0f, 0x12, 0x39, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0x10, 0x00, 0x00, 0x01, 0x05, 0x02, 0x00, 0x02,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x39, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x36, 0x80,
            0x52, 0x4f, 0x8d, 0x31, 0x2b, 0x00, 0xc2, 0xde, 0x00, 0x01, 0xc7, 0x8d, 0x12, 0x00,
            0x38, 0x42, 0x2b, 0xc1, 0x11, 0xa7, 0x18, 0x7a, 0x18, 0x24, 0x6f, 0x98, 0x0c, 0x05,
            0x9c, 0xc6, 0xbc, 0x9d, 0xf8, 0xb6, 0x26, 0x39, 0x4e, 0xca, 0x34, 0x4e, 0x4b, 0x05,
            0xd8, 0x0f, 0xea, 0x83,
        ],
    ),
    // RFC 9335 A.2.5: RTP Packet with Empty One-Byte Header Extension and CSRC Fields.
    (
        "A.2.5",
        &[
            0x92, 0x0f, 0x12, 0x3a, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0xbe, 0xde, 0x00, 0x00, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x3a, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x15, 0xb6,
            0xbb, 0x43, 0x37, 0x90, 0x6f, 0xff, 0xc0, 0xde, 0x00, 0x00, 0xb7, 0xb9, 0x64, 0x53,
            0x7a, 0x2b, 0x03, 0xab, 0x7b, 0xa5, 0x38, 0x9c, 0xe9, 0x33, 0x17, 0x12, 0x6b, 0x5d,
            0x97, 0x4d, 0xf3, 0x0c, 0x68, 0x84, 0xdc, 0xb6, 0x51, 0xc5, 0xe1, 0x20, 0xc1, 0xda,
        ],
    ),
    // RFC 9335 A.2.6: RTP Packet with Empty Two-Byte Header Extension and CSRC Fields.
    (
        "A.2.6",
        &[
            0x92, 0x0f, 0x12, 0x3b, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01,
            0xe2, 0x40, 0x00, 0x00, 0xb2, 0x6e, 0x10, 0x00, 0x00, 0x00, 0xab, 0xab, 0xab, 0xab,
            0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
        ],
        &[
            0x92, 0x0f, 0x12, 0x3b, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xdc, 0xb3,
            0x8c, 0x9e, 0x48, 0xbf, 0x95, 0xf4, 0xc2, 0xde, 0x00, 0x00, 0x61, 0xee, 0x43, 0x2c,
            0xf9, 0x20, 0x31, 0x70, 0x76, 0x61, 0x32, 0x58, 0xd3, 0xce, 0x42, 0x36, 0xc0, 0x6a,
            0xc4, 0x29, 0x68, 0x1a, 0xd0, 0x84, 0x13, 0x51, 0x2d, 0xc9, 0x8b, 0x52, 0x07, 0xd8,
        ],
    ),
];

fn context(profile: ProtectionProfile, cryptex: Cryptex) -> Context {
    let (key, salt): (&[u8], &[u8]) = match profile {
        ProtectionProfile::AeadAes128Gcm => (&GCM_KEY, &GCM_SALT),
        _ => (&AES_CM_KEY, &AES_CM_SALT),
    };
    let mut context = Context::new(
        key,
        salt,
        profile,
        None,
        None,
        test_crypto_provider().crypto(),
    )
    .expect("context");
    context.set_cryptex(cryptex);
    context
}

const SEND: Cryptex = Cryptex {
    send: true,
    require: false,
};

fn check(profile: ProtectionProfile, vectors: &[Vector]) {
    for (name, plain, encrypted) in vectors {
        let out = context(profile, SEND)
            .encrypt_rtp(plain)
            .unwrap_or_else(|e| panic!("{name}: encrypt: {e}"));
        assert_eq!(&out[..], *encrypted, "{name}: encrypt");

        let out = context(profile, Cryptex::default())
            .decrypt_rtp(encrypted)
            .unwrap_or_else(|e| panic!("{name}: decrypt: {e}"));
        assert_eq!(&out[..], *plain, "{name}: decrypt");
    }
}

#[test]
fn cryptex_aes_cm_test_vectors() {
    check(ProtectionProfile::Aes128CmHmacSha1_80, AES_CM_VECTORS);
}

#[test]
fn cryptex_aead_aes_gcm_test_vectors() {
    check(ProtectionProfile::AeadAes128Gcm, GCM_VECTORS);
}

/// A packet with neither CSRCs nor header extensions is protected as RFC 3711 has it, with
/// Cryptex on or off.
#[test]
fn cryptex_leaves_a_bare_packet_alone() {
    let plain: &[u8] = &[
        0x80, 0x0f, 0x12, 0x35, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0xab, 0xab, 0xab,
        0xab,
    ];
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        let with = context(profile, SEND).encrypt_rtp(plain).unwrap();
        let without = context(profile, Cryptex::default())
            .encrypt_rtp(plain)
            .unwrap();
        assert_eq!(with, without);
    }
}

/// RFC 9335 section 5.2: with Cryptex required, a packet whose header extensions are in the
/// clear is refused; one protected with Cryptex, or one with nothing to protect, is not.
#[test]
fn cryptex_required_refuses_clear_header_extensions() {
    let require = Cryptex {
        send: false,
        require: true,
    };
    for (profile, vectors) in [
        (ProtectionProfile::Aes128CmHmacSha1_80, AES_CM_VECTORS),
        (ProtectionProfile::AeadAes128Gcm, GCM_VECTORS),
    ] {
        let (_, plain, encrypted) = vectors[0];
        let clear = context(profile, Cryptex::default())
            .encrypt_rtp(plain)
            .unwrap();
        assert!(context(profile, require).decrypt_rtp(&clear).is_err());
        assert_eq!(
            &context(profile, require).decrypt_rtp(encrypted).unwrap()[..],
            plain
        );
    }
}

/// A packet with CSRCs and no extension gets an empty 0xC0DE extension (RFC 9335 section
/// 5.1), which survives decryption as an empty 0xBEDE one.
#[test]
fn cryptex_adds_an_empty_extension_for_csrcs() {
    let plain: &[u8] = &[
        0x81, 0x0f, 0x12, 0x35, 0xde, 0xca, 0xfb, 0xad, 0xca, 0xfe, 0xba, 0xbe, 0x00, 0x01, 0xe2,
        0x40, 0xab, 0xab, 0xab, 0xab,
    ];
    let encrypted = context(ProtectionProfile::Aes128CmHmacSha1_80, SEND)
        .encrypt_rtp(plain)
        .unwrap();
    assert_eq!(encrypted[0], 0x91);
    assert_eq!(&encrypted[16..20], &[0xc0, 0xde, 0x00, 0x00]);
    let decrypted = context(ProtectionProfile::Aes128CmHmacSha1_80, Cryptex::default())
        .decrypt_rtp(&encrypted)
        .unwrap();
    let mut header: Vec<u8> = plain[..16].to_vec();
    header[0] = 0x91;
    assert_eq!(&decrypted[..16], &header[..]);
    assert_eq!(&decrypted[16..20], &[0xbe, 0xde, 0x00, 0x00]);
    assert_eq!(&decrypted[20..], &plain[16..]);
}

/// An RTP packet with `csrcs` CSRCs and, with `profile`, a 4-octet header extension of it.
fn shaped(csrcs: u8, profile: Option<u16>, seq: u16) -> Vec<u8> {
    let mut packet = vec![0x80 | csrcs | if profile.is_some() { 0x10 } else { 0 }, 96];
    packet.extend_from_slice(&seq.to_be_bytes());
    packet.extend_from_slice(&[0, 0, 0, 1, 0, 0, 0, 7]);
    for csrc in 0..csrcs {
        packet.extend_from_slice(&[0xC0, 0, 0, csrc]);
    }
    if let Some(profile) = profile {
        packet.extend_from_slice(&profile.to_be_bytes());
        packet.extend_from_slice(&[0, 1]);
        // Element 1 with one octet, in the two-byte or the one-byte form.
        packet.extend_from_slice(if profile & 0xFFF0 == 0x1000 {
            &[0x01, 0x01, 0xAA, 0]
        } else {
            &[0x10, 0xAA, 0, 0]
        });
    }
    packet.extend_from_slice(b"payload");
    packet
}

/// RFC 7941 section 6: the SDES header extensions (MID, RID) get protection "of commensurate
/// strength" with RTCP's. Under Cryptex the CSRC list and the extension elements are encrypted
/// by the SRTP transform of the payload (RFC 9335 section 6) and are under its authentication
/// tag: they do not leave in the clear, and a changed octet of either fails authentication,
/// with the HMAC and with the AEAD.
#[test]
fn cryptex_extensions_are_encrypted_and_authenticated_like_the_payload() {
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        // 12 octets of fixed header, one CSRC (12..16), the extension header (16..20), its
        // element (20..24), the payload.
        let plain = shaped(1, Some(0xBEDE), 1);
        let protected = context(profile, SEND).encrypt_rtp(&plain).unwrap();
        assert_eq!(
            &protected[16..18],
            &[0xc0, 0xde],
            "{profile:?}: marked Cryptex"
        );
        assert_ne!(
            &protected[12..16],
            &plain[12..16],
            "{profile:?}: CSRC in clear"
        );
        assert_ne!(
            &protected[20..24],
            &plain[20..24],
            "{profile:?}: element in clear"
        );
        for at in [13, 21] {
            let mut forged = protected.to_vec();
            forged[at] ^= 0x01;
            assert!(
                context(profile, Cryptex::default())
                    .decrypt_rtp(&forged)
                    .is_err(),
                "{profile:?}: octet {at} changed and still read"
            );
        }
        assert_eq!(
            &context(profile, Cryptex::default())
                .decrypt_rtp(&protected)
                .unwrap()[..20],
            &plain[..20]
        );
    }
}

/// RFC 9335 sections 5 and 5.1: Cryptex applies to RFC 8285 extensions only, and not to
/// two-byte headers with non-zero "appbits". When Cryptex is mandatory such a packet must not
/// leave with its CSRCs or extension in the clear (the receiving side of the same policy
/// discards it, section 5.2): protecting it is an error. It used to go out unprotected.
#[test]
fn cryptex_required_never_sends_csrcs_or_extensions_in_the_clear() {
    let required = Cryptex {
        send: true,
        require: true,
    };
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        for (name, packet) in [
            ("two-byte with appbits", shaped(0, Some(0x1001), 1)),
            ("profile-specific extension", shaped(0, Some(0xABCD), 2)),
            ("the same with CSRCs", shaped(2, Some(0xABCD), 3)),
            ("already marked 0xC0DE", shaped(0, Some(0xC0DE), 4)),
            (
                "extension cut short",
                shaped(1, Some(0xBEDE), 5)[..17].to_vec(),
            ),
        ] {
            let mut sender = context(profile, required);
            assert!(sender.encrypt_rtp(&packet).is_err(), "{profile:?}: {name}");
            // Nothing was consumed: the index is still free for a packet that can be sent.
            assert!(sender.get_roc(7).is_none_or(|roc| roc == 0));
        }

        // What Cryptex can protect is sent, protected; a bare packet has nothing to protect.
        let mut sender = context(profile, required);
        for (packet, marker) in [
            (shaped(0, Some(0xBEDE), 10), Some([0xC0, 0xDE])),
            (shaped(0, Some(0x1000), 11), Some([0xC2, 0xDE])),
            (shaped(3, None, 12), Some([0xC0, 0xDE])),
            (shaped(0, None, 13), None),
        ] {
            let protected = sender.encrypt_rtp(&packet).unwrap();
            let csrc_end = 12 + 4 * (packet[0] & 0x0F) as usize;
            if let Some(marker) = marker {
                assert_eq!(&protected[csrc_end..csrc_end + 2], &marker);
            }
            let mut receiver = context(profile, required);
            let received = receiver.decrypt_rtp(&protected).unwrap();
            assert_eq!(&received[received.len() - 7..], b"payload");
        }

        // Mandatory without the peer's support (`send` unset) sends nothing that would need it.
        let mut sender = context(
            profile,
            Cryptex {
                send: false,
                require: true,
            },
        );
        assert!(sender.encrypt_rtp(&shaped(0, Some(0xBEDE), 20)).is_err());
        assert!(sender.encrypt_rtp(&shaped(1, None, 21)).is_err());
        sender.encrypt_rtp(&shaped(0, None, 22)).unwrap();

        // Without the requirement those packets go out as RFC 3711 has them (RFC 9335 section
        // 5.1: "MUST NOT be applied" to other extensions).
        let mut sender = context(profile, SEND);
        let packet = shaped(0, Some(0xABCD), 30);
        let protected = sender.encrypt_rtp(&packet).unwrap();
        assert_eq!(&protected[..20], &packet[..20]);
        assert_eq!(
            &context(profile, Cryptex::default())
                .decrypt_rtp(&protected)
                .unwrap()[..],
            &packet[..]
        );
    }
}

/// RFC 9335 section 5.2: when Cryptex is mandatory and a packet arrives without it, the
/// receiver stops processing it and reports an error for the stream. The report comes only for
/// a packet that authenticates, so the peer really sent it, and once until the settings change.
#[test]
fn cryptex_required_reports_an_authentic_violation_once() {
    let required = Cryptex {
        send: true,
        require: true,
    };
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        let mut sender = context(profile, Cryptex::default());
        let mut receiver = context(profile, required);

        // A forged packet in the clear is refused as a forgery: reported as one (RFC 3711
        // section 3.3), not as a Cryptex violation.
        let mut forged = sender
            .encrypt_rtp(&shaped(1, Some(0xBEDE), 1))
            .unwrap()
            .to_vec();
        let last = forged.len() - 1;
        forged[last] ^= 1;
        assert!(receiver.decrypt_rtp(&forged).is_err());
        assert!(matches!(
            receiver.poll_event(),
            Some(ContextEvent::PacketDiscarded {
                reason: DiscardReason::AuthenticationFailed,
                ..
            })
        ));
        assert_eq!(receiver.poll_event(), None);

        for seq in 2..5 {
            let clear = sender.encrypt_rtp(&shaped(0, Some(0xBEDE), seq)).unwrap();
            assert!(receiver.decrypt_rtp(&clear).is_err());
        }
        assert_eq!(
            receiver.poll_event(),
            Some(ContextEvent::CryptexRequiredViolation { ssrc: 7 })
        );
        assert_eq!(receiver.poll_event(), None);
        // The discarded packets left no state: nothing was accepted for the stream.
        assert_eq!(receiver.get_roc(7), None);
        assert_eq!(receiver.key_usage().srtp_packets, 0);

        receiver.set_cryptex(required);
        let clear = sender.encrypt_rtp(&shaped(0, Some(0xBEDE), 9)).unwrap();
        assert!(receiver.decrypt_rtp(&clear).is_err());
        assert!(
            receiver.poll_event().is_some(),
            "reported again after a change"
        );
    }
}

/// RFC 9335 section 6.2: the plaintext runs on through the RTP padding and the padding count.
#[test]
fn cryptex_round_trips_a_padded_packet_with_csrcs() {
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        let mut packet = shaped(2, Some(0xBEDE), 40);
        packet[0] |= 0x20;
        packet.extend_from_slice(&[0, 0, 0, 0, 5]);
        let protected = context(profile, SEND).encrypt_rtp(&packet).unwrap();
        // Everything after the fixed header but the 4-octet extension header is encrypted.
        assert_ne!(&protected[12..20], &packet[12..20], "CSRCs");
        assert_eq!(&protected[20..24], &[0xC0, 0xDE, 0, 1]);
        assert_ne!(
            &protected[24..packet.len()],
            &packet[24..],
            "extension data to padding"
        );
        assert_eq!(
            &context(profile, Cryptex::default())
                .decrypt_rtp(&protected)
                .unwrap()[..],
            &packet[..]
        );
    }
}

/// RFC 7941 section 6: SDES items carried in header extensions (MID, RtpStreamId) are
/// protected "of commensurate strength" with RTCP's. Under Cryptex they are encrypted with
/// the payload by the stream's own SRTP transform (the same cipher, key and authentication as
/// the SRTCP of the session): the extension data on the wire is not the plaintext, and a
/// packet whose extension block was changed in transit fails authentication, for the counter
/// mode with HMAC-SHA1 and for AES-GCM.
#[test]
fn a_changed_cryptex_extension_block_fails_authentication() {
    // RFC 9335 A.1.1's packet: a one-byte header extension, element id 5, two octets.
    let plain = AES_CM_VECTORS[0].1;
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        let protected = context(profile, SEND).encrypt_rtp(plain).unwrap();
        assert_eq!(
            &protected[12..14],
            &[0xC0, 0xDE],
            "{profile:?}: Cryptex profile"
        );
        assert_ne!(
            &protected[16..20],
            &plain[16..20],
            "{profile:?}: the extension element is not in the clear"
        );
        assert_eq!(
            &context(profile, Cryptex::default())
                .decrypt_rtp(&protected)
                .unwrap()[..],
            plain
        );
        for offset in 16..20 {
            let mut changed = protected.to_vec();
            changed[offset] ^= 0x01;
            assert!(
                context(profile, Cryptex::default())
                    .decrypt_rtp(&changed)
                    .is_err(),
                "{profile:?}: a change at octet {offset} of the extension block is detected"
            );
        }
    }
}