wacore 0.7.0

Core WhatsApp protocol implementation without runtime dependencies
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
//! E2E 1:1 SRTP, the primary working path. Keys derive from `callKey` (32B) +
//! participant LID via HKDF-SHA256, then an AES-CM PRF; payloads use AES-128-CTR
//! with a 4-byte WARP MESSAGE-INTEGRITY tag (HMAC-SHA1), verified on recv before
//! the rollover counter is advanced (see `session::unprotect_audio`).
//!
//! wacrg spec: srtp-e2e (CRY-05), srtp-master-key (CRY-02), call-key (CRY-01).

use aes::Aes128;
use ctr::Ctr128BE;
use ctr::cipher::{KeyIvInit, StreamCipher};

use crate::voip::hkdf_sha256;
pub use crate::voip::warp::{
    WARP_MI_TAG_LEN, append_warp_mi_tag, compute_warp_mi_tag, verify_warp_mi_tag,
};

type AesCtr = Ctr128BE<Aes128>;

/// Session keys for the E2E 1:1 SRTP cipher. Doc-hidden: an internal primitive, surfaced only so
/// the in-tree benchmark crate can drive `crypt_payload`/`derive_e2e_keys`.
#[doc(hidden)]
#[derive(Clone)]
pub struct E2eSrtpKeys {
    pub cipher_key: [u8; 16],
    pub salt: [u8; 14],
    pub auth_key: [u8; 20],
}

// Manual Debug so a stray `{:?}` can't leak the session keys.
impl core::fmt::Debug for E2eSrtpKeys {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("E2eSrtpKeys([redacted])")
    }
}

/// AES-CM PRF (libsrtp KDF): IV = master_salt (14B) with `label` XORed into byte 7,
/// zero-padded to 16, then AES-128-CTR keystream over `len` zero bytes.
fn aes_cm_kdf(master_key: &[u8], master_salt: &[u8], label: u8, len: usize) -> Vec<u8> {
    let mut iv = [0u8; 16];
    iv[..14].copy_from_slice(&master_salt[..14]);
    iv[7] ^= label;
    let mut out = vec![0u8; len];
    let mut cipher = AesCtr::new_from_slices(master_key, &iv).expect("16-byte key/iv");
    cipher.apply_keystream(&mut out);
    out
}

fn derive_session_keys_from_master(master: &[u8]) -> E2eSrtpKeys {
    let master_key = &master[0..16];
    let master_salt = &master[16..30];
    let mut keys = E2eSrtpKeys {
        cipher_key: [0u8; 16],
        salt: [0u8; 14],
        auth_key: [0u8; 20],
    };
    keys.cipher_key
        .copy_from_slice(&aes_cm_kdf(master_key, master_salt, 0x00, 16));
    keys.auth_key
        .copy_from_slice(&aes_cm_kdf(master_key, master_salt, 0x01, 20));
    keys.salt
        .copy_from_slice(&aes_cm_kdf(master_key, master_salt, 0x02, 14));
    keys
}

/// E2E 1:1 keys from `call_key` (>= 32B) and a participant LID (HKDF `info`).
/// The `info` is the *sender's* own participant id, so a caller derives the send keys from the
/// self LID and the recv keys from the peer LID (note SFrame uses the opposite convention).
/// Returns `None` when `call_key` is shorter than 32 bytes (a malformed peer callKey).
#[doc(hidden)]
pub fn derive_e2e_keys(call_key: &[u8], participant_lid: &str) -> Option<E2eSrtpKeys> {
    if call_key.len() < 32 {
        return None;
    }
    let master = hkdf_sha256(&[0u8; 32], &call_key[..32], participant_lid.as_bytes(), 46);
    Some(derive_session_keys_from_master(&master))
}

/// SRTP keys from one decrypted keygen-v2 group epoch.
///
/// The epoch is transaction-wide: callers derive local send keys with the
/// local participant id and one receive key set per remote participant id.
#[doc(hidden)]
pub fn derive_e2e_keys_from_raw(raw_epoch: &[u8], participant_lid: &str) -> Option<E2eSrtpKeys> {
    derive_e2e_keys(raw_epoch, participant_lid)
}

/// E2E RTP IV: salt right-aligned into 16 bytes, then SSRC XORed at bytes 4-7 and the
/// 48-bit packet index (ROC<<16 | seq) XORed at bytes 8-13.
pub fn build_e2e_rtp_iv(salt: &[u8], ssrc: u32, roc: u32, seq: u16) -> [u8; 16] {
    let mut iv = [0u8; 16];
    // Salt right-aligns into bytes [0..14]. Clamp so an oversized salt can't underflow `off` or panic
    // the slice; the only production caller passes the 14-byte E2eSrtpKeys.salt (n = 14, off = 0).
    let n = salt.len().min(14);
    let off = 14 - n;
    iv[off..off + n].copy_from_slice(&salt[..n]);
    iv[4] ^= (ssrc >> 24) as u8;
    iv[5] ^= (ssrc >> 16) as u8;
    iv[6] ^= (ssrc >> 8) as u8;
    iv[7] ^= ssrc as u8;
    let packet_index = (roc as u64) * 0x1_0000 + (seq as u64);
    let hi16 = ((packet_index >> 32) & 0xffff) as u16;
    let lo32 = (packet_index & 0xffff_ffff) as u32;
    iv[8] ^= (hi16 >> 8) as u8;
    iv[9] ^= hi16 as u8;
    iv[10] ^= (lo32 >> 24) as u8;
    iv[11] ^= (lo32 >> 16) as u8;
    iv[12] ^= (lo32 >> 8) as u8;
    iv[13] ^= lo32 as u8;
    iv
}

/// AES-128-CTR encrypt/decrypt of an RTP payload (the cipher is symmetric).
#[doc(hidden)]
pub fn crypt_payload(keys: &E2eSrtpKeys, ssrc: u32, seq: u16, roc: u32, payload: &[u8]) -> Vec<u8> {
    let iv = build_e2e_rtp_iv(&keys.salt, ssrc, roc, seq);
    let mut out = payload.to_vec();
    let mut cipher = AesCtr::new_from_slices(&keys.cipher_key, &iv).expect("16-byte key/iv");
    cipher.apply_keystream(&mut out);
    out
}

/// SRTCP auth-tag length (HMAC-SHA1-80). With the 4-byte E-flag+index word this is the 14-byte
/// SRTCP trailer.
pub const SRTCP_AUTH_TAG_LEN: usize = 10;
/// First 8 bytes of an RTCP packet (V/P/RC, PT, length, sender SSRC) are left in the clear; only the
/// body is encrypted (RFC 3711 §3.4).
const RTCP_HEADER_LEN: usize = 8;

fn hmac_sha1_20(key: &[u8], data: &[u8]) -> [u8; 20] {
    use hmac::{Hmac, KeyInit, Mac};
    use sha1::Sha1;
    let mut mac = Hmac::<Sha1>::new_from_slice(key).expect("HMAC accepts any key length");
    mac.update(data);
    let mut tag = [0u8; 20];
    tag.copy_from_slice(&mac.finalize().into_bytes());
    tag
}

/// SRTCP session keys derived with the RFC 3711 labels used by the native client.
#[doc(hidden)]
pub fn derive_srtcp_keys(call_key: &[u8], participant_lid: &str) -> Option<E2eSrtpKeys> {
    if call_key.len() < 32 {
        return None;
    }
    let master = hkdf_sha256(&[0u8; 32], &call_key[..32], participant_lid.as_bytes(), 46);
    let master_key = &master[0..16];
    let master_salt = &master[16..30];
    let mut keys = E2eSrtpKeys {
        cipher_key: [0u8; 16],
        salt: [0u8; 14],
        auth_key: [0u8; 20],
    };
    keys.cipher_key
        .copy_from_slice(&aes_cm_kdf(master_key, master_salt, 0x03, 16));
    keys.auth_key
        .copy_from_slice(&aes_cm_kdf(master_key, master_salt, 0x04, 20));
    keys.salt
        .copy_from_slice(&aes_cm_kdf(master_key, master_salt, 0x05, 14));
    Some(keys)
}

/// SRTCP sibling of [`derive_e2e_keys_from_raw`], using the native RTCP labels.
#[doc(hidden)]
pub fn derive_srtcp_keys_from_raw(raw_epoch: &[u8], participant_lid: &str) -> Option<E2eSrtpKeys> {
    derive_srtcp_keys(raw_epoch, participant_lid)
}

/// Protect one RTCP packet as SRTCP (RFC 3711 §3.4): AES-CTR the body, append the 4-byte
/// E-flag+index word, then an HMAC-SHA1-80 tag over the whole thing. `sender_ssrc` is the SR's
/// own SSRC (bytes 4..8) and `index` the per-SSRC SRTCP counter.
pub fn protect_srtcp(keys: &E2eSrtpKeys, sender_ssrc: u32, index: u32, rtcp: &[u8]) -> Vec<u8> {
    let split = rtcp.len().min(RTCP_HEADER_LEN);
    let iv = build_e2e_rtp_iv(
        &keys.salt,
        sender_ssrc,
        index >> 16,
        (index & 0xffff) as u16,
    );
    let mut out = Vec::with_capacity(rtcp.len() + 4 + SRTCP_AUTH_TAG_LEN);
    out.extend_from_slice(&rtcp[..split]);
    let mut body = rtcp[split..].to_vec();
    let mut cipher = AesCtr::new_from_slices(&keys.cipher_key, &iv).expect("16-byte key/iv");
    cipher.apply_keystream(&mut body);
    out.extend_from_slice(&body);
    out.extend_from_slice(&(0x8000_0000u32 | (index & 0x7fff_ffff)).to_be_bytes());
    let tag = hmac_sha1_20(&keys.auth_key, &out);
    out.extend_from_slice(&tag[..SRTCP_AUTH_TAG_LEN]);
    out
}

/// Inverse of [`protect_srtcp`]: verify the tag, then decrypt the body and return its authenticated
/// 31-bit index. `None` on a bad tag or a too-short packet.
pub fn unprotect_srtcp(
    keys: &E2eSrtpKeys,
    sender_ssrc: u32,
    packet: &[u8],
) -> Option<(Vec<u8>, u32)> {
    if packet.len() < RTCP_HEADER_LEN + 4 + SRTCP_AUTH_TAG_LEN {
        return None;
    }
    let tag_start = packet.len() - SRTCP_AUTH_TAG_LEN;
    let expected = hmac_sha1_20(&keys.auth_key, &packet[..tag_start]);
    if !bool::from(subtle::ConstantTimeEq::ct_eq(
        &packet[tag_start..],
        &expected[..SRTCP_AUTH_TAG_LEN],
    )) {
        return None;
    }
    let idx_start = tag_start - 4;
    let index = u32::from_be_bytes(packet[idx_start..tag_start].try_into().ok()?) & 0x7fff_ffff;
    let iv = build_e2e_rtp_iv(
        &keys.salt,
        sender_ssrc,
        index >> 16,
        (index & 0xffff) as u16,
    );
    let mut out = packet[..RTCP_HEADER_LEN].to_vec();
    let mut body = packet[RTCP_HEADER_LEN..idx_start].to_vec();
    let mut cipher = AesCtr::new_from_slices(&keys.cipher_key, &iv).expect("16-byte key/iv");
    cipher.apply_keystream(&mut body);
    out.extend_from_slice(&body);
    Some((out, index))
}

/// Send-side ROC tracker for monotonic 16-bit sequence numbers.
#[derive(Default)]
pub(crate) struct RocTracker {
    roc: u32,
    last_seq: u16,
    initialized: bool,
}

impl RocTracker {
    pub fn advance(&mut self, seq: u16) -> u32 {
        if !self.initialized {
            self.last_seq = seq;
            self.initialized = true;
            return self.roc;
        }
        // A signed 16-bit gap below -32768 is the wrap (seq jumped backward past the half-range).
        if (seq as i32 - self.last_seq as i32) < -32768 {
            self.roc = self.roc.wrapping_add(1);
        }
        self.last_seq = seq;
        self.roc
    }
}

/// Recv-side ROC estimator (RFC 3711 §3.3.1 guess-index). Unlike the monotonic send tracker it
/// tolerates reorder/loss: each packet's ROC is guessed from the highest seq seen, so a late
/// packet straddling a wrap decrypts under the right (lower) ROC without poisoning the state.
#[derive(Default)]
pub(crate) struct RecvRocTracker {
    roc: u32,
    s_l: u16,
    initialized: bool,
}

impl RecvRocTracker {
    /// Estimate the ROC for `seq` WITHOUT mutating state (RFC 3711 guess-index).
    /// Use this to build the IV / verify a packet; only [`Self::commit_roc`] after
    /// the packet authenticates, so an unauthenticated packet can't desync state.
    pub fn estimate_roc(&self, seq: u16) -> u32 {
        if !self.initialized {
            return self.roc;
        }
        // Pick v in {roc-1, roc, roc+1} so 2^16*v+seq is closest to 2^16*roc+s_l. The signed 16-bit
        // gap (not a modular wrapping_sub) is what distinguishes "next-but-reordered" from "wrapped".
        if self.s_l < 0x8000 {
            if (seq as i32 - self.s_l as i32) > 0x8000 {
                self.roc.wrapping_sub(1) // old packet from before the origin (roc-1)
            } else {
                self.roc
            }
        } else if (self.s_l as i32 - seq as i32) > 0x8000 {
            self.roc.wrapping_add(1) // forward wrap into roc+1
        } else {
            self.roc
        }
    }

    /// Fold an AUTHENTICATED packet's `(v, seq)` into the state; `v` must come from
    /// a prior [`Self::estimate_roc`] whose MI tag verified. Seeds from the first
    /// packet (roc stays 0).
    pub fn commit_roc(&mut self, v: u32, seq: u16) {
        if !self.initialized {
            self.s_l = seq;
            self.initialized = true;
            return;
        }
        if v == self.roc {
            if seq > self.s_l {
                self.s_l = seq;
            }
        } else if v == self.roc.wrapping_add(1) {
            self.roc = v;
            self.s_l = seq;
        }
        // v == roc-1 (reordered late packet): leave state untouched.
    }

    /// Estimate + commit in one step. Test-only: production authenticates the WARP
    /// MI tag against `estimate_roc` first and only `commit_roc` on success, so an
    /// unauthenticated packet can't fold state. Kept for the wrap-tracking tests.
    #[cfg(test)]
    pub fn guess_roc(&mut self, seq: u16) -> u32 {
        let v = self.estimate_roc(seq);
        self.commit_roc(v, seq);
        v
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::voip::testkat::{hexd, kats};

    fn keys_from(k: &serde_json::Value, who: &str) -> E2eSrtpKeys {
        let mut keys = E2eSrtpKeys {
            cipher_key: [0u8; 16],
            salt: [0u8; 14],
            auth_key: [0u8; 20],
        };
        keys.cipher_key
            .copy_from_slice(&hexd(k, &["e2e_srtp", &format!("{who}_cipherKey")]));
        keys.salt
            .copy_from_slice(&hexd(k, &["e2e_srtp", &format!("{who}_salt")]));
        keys.auth_key
            .copy_from_slice(&hexd(k, &["e2e_srtp", &format!("{who}_authKey")]));
        keys
    }

    #[test]
    fn srtcp_round_trips_and_authenticates() {
        // SRTCP keys must be distinct from the SRTP keys (different KDF labels).
        let call_key: Vec<u8> = (0u8..40).collect();
        let lid = "12345:0@lid";
        let srtp = derive_e2e_keys(&call_key, lid).unwrap();
        let srtcp = derive_srtcp_keys(&call_key, lid).unwrap();
        assert_ne!(
            srtp.cipher_key, srtcp.cipher_key,
            "SRTCP must use its own key"
        );
        assert_ne!(srtp.salt, srtcp.salt);

        // A 28-byte Sender Report (header 8 + body 20).
        let ssrc: u32 = 0x0a0b_0c0d;
        let mut sr = vec![0x80, 200, 0x00, 0x06];
        sr.extend_from_slice(&ssrc.to_be_bytes());
        sr.extend_from_slice(&[0x11; 20]);

        let protected = protect_srtcp(&srtcp, ssrc, 0, &sr);
        // header stays clear, body is encrypted, +4 index +10 tag.
        assert_eq!(protected.len(), sr.len() + 4 + SRTCP_AUTH_TAG_LEN);
        assert_eq!(&protected[..8], &sr[..8], "header/SSRC left in the clear");
        assert_ne!(&protected[8..28], &sr[8..28], "body must be encrypted");
        // E-flag set on the index word.
        assert_eq!(
            protected[protected.len() - SRTCP_AUTH_TAG_LEN - 4] & 0x80,
            0x80
        );

        let (plain, index) = unprotect_srtcp(&srtcp, ssrc, &protected).unwrap();
        assert_eq!(plain, sr);
        assert_eq!(index, 0);
        // A flipped tag byte must fail authentication.
        let mut forged = protected.clone();
        *forged.last_mut().unwrap() ^= 1;
        assert_eq!(unprotect_srtcp(&srtcp, ssrc, &forged), None);
        // The index increments per packet, changing the keystream.
        let p1 = protect_srtcp(&srtcp, ssrc, 1, &sr);
        assert_ne!(
            protected[8..28],
            p1[8..28],
            "a new index must change the ciphertext"
        );
        let (plain, index) = unprotect_srtcp(&srtcp, ssrc, &p1).unwrap();
        assert_eq!(plain, sr);
        assert_eq!(index, 1);
    }

    #[test]
    fn derive_e2e_keys_matches_kat() {
        let k = kats();
        let call_key = hexd(&k, &["inputs", "callKey"]);
        let peer = derive_e2e_keys(&call_key, k["inputs"]["peerLid"].as_str().unwrap()).unwrap();
        let expect = keys_from(&k, "peer");
        assert_eq!(peer.cipher_key, expect.cipher_key, "peer cipher_key");
        assert_eq!(peer.salt, expect.salt, "peer salt");
        assert_eq!(peer.auth_key, expect.auth_key, "peer auth_key");

        let self_keys =
            derive_e2e_keys(&call_key, k["inputs"]["selfLid"].as_str().unwrap()).unwrap();
        let expect_self = keys_from(&k, "self");
        assert_eq!(
            self_keys.cipher_key, expect_self.cipher_key,
            "self cipher_key"
        );
        assert_eq!(self_keys.auth_key, expect_self.auth_key, "self auth_key");
    }

    #[test]
    fn rtp_iv_matches_kat() {
        let k = kats();
        let peer = keys_from(&k, "peer");
        let ssrc = k["inputs"]["ssrc"].as_u64().unwrap() as u32;
        let seq = k["inputs"]["seq"].as_u64().unwrap() as u16;
        let roc = k["inputs"]["roc"].as_u64().unwrap() as u32;
        let iv = build_e2e_rtp_iv(&peer.salt, ssrc, roc, seq);
        assert_eq!(hex::encode(iv), k["e2e_srtp"]["rtpIv"].as_str().unwrap());
    }

    #[test]
    fn roc_tracker_wraps() {
        // --- send-side monotonic tracker ---
        let mut tx = RocTracker::default();
        assert_eq!(tx.advance(0xFFFE), 0); // seed
        assert_eq!(tx.advance(0xFFFF), 0);
        assert_eq!(tx.advance(0x0000), 1, "0xFFFF→0x0000 bumps ROC");
        assert_eq!(tx.advance(0x0001), 1);
        // Small out-of-order dip must NOT bump.
        assert_eq!(tx.advance(0x0000), 1, "a backward dip does not bump ROC");
        assert_eq!(tx.advance(0x0001), 1);
        // Walk to a second wrap → ROC=2.
        for s in [0x7000u16, 0xE000, 0xFFFF] {
            tx.advance(s);
        }
        assert_eq!(tx.advance(0x0000), 2, "second wrap gives ROC=2");

        // --- recv-side guess tracker ---
        let mut rx = RecvRocTracker::default();
        assert_eq!(rx.guess_roc(0xFFFE), 0); // seed (roc=0, s_l=0xFFFE)
        assert_eq!(rx.guess_roc(0xFFFF), 0);
        assert_eq!(rx.guess_roc(0x0000), 1, "0xFFFF→0x0000 bumps ROC");
        assert_eq!(rx.guess_roc(0x0001), 1);
        // Reordered small dip in the same ROC must NOT bump, and must not corrupt s_l.
        assert_eq!(
            rx.guess_roc(0x0000),
            1,
            "a reordered dip stays in the same ROC"
        );
        assert_eq!(rx.guess_roc(0x0002), 1, "state intact after the dip");
        // Walk forward (< 2^15 steps) to the high range, then wrap again → ROC=2.
        for s in [0x7000u16, 0xE000, 0xFFFF] {
            assert_eq!(rx.guess_roc(s), 1);
        }
        assert_eq!(rx.guess_roc(0x0000), 2, "second wrap gives ROC=2");
        // A late packet from just before the last wrap returns the LOWER ROC without corrupting
        // state: the next in-order packet still guesses ROC=2.
        assert_eq!(
            rx.guess_roc(0xFFF0),
            1,
            "reordered late packet returns the lower ROC"
        );
        assert_eq!(
            rx.guess_roc(0x0001),
            2,
            "state not corrupted by the late packet"
        );
    }

    /// The exact rollover-desync the auth fix prevents. `unprotect_audio` only
    /// `commit_roc`s after the MI tag verifies, so a rejected (unauthenticated)
    /// packet stays on the pure `estimate_roc` path and can't fold state — while the
    /// attacker's 2-packet staircase, if committed, advances the ROC by one.
    #[test]
    fn unauthenticated_staircase_cannot_advance_roc_without_commit() {
        let mut rx = RecvRocTracker::default();
        rx.guess_roc(0x7FFE); // seed s_l into the high half (the exploit's start)
        assert_eq!(rx.roc, 0);

        // A rejected packet only reaches estimate_roc (never commit_roc): the
        // attacker's staircase seqs leave the state untouched.
        let _ = rx.estimate_roc(0xFFFE);
        let _ = rx.estimate_roc(0x7FFD);
        assert_eq!(rx.roc, 0, "estimate alone must not advance the ROC");
        assert_eq!(
            rx.estimate_roc(0x7FFF),
            0,
            "a legit in-window seq still maps to roc=0"
        );

        // Contrast: committing that same staircase (the pre-fix path) advances the
        // ROC by one — the desync authentication now blocks.
        rx.commit_roc(rx.estimate_roc(0xFFFE), 0xFFFE);
        rx.commit_roc(rx.estimate_roc(0x7FFD), 0x7FFD);
        assert_eq!(
            rx.roc, 1,
            "committing the staircase advances the ROC (the pre-fix desync)"
        );
    }

    #[test]
    fn crypt_payload_matches_kat() {
        let k = kats();
        let peer = keys_from(&k, "peer");
        let ssrc = k["inputs"]["ssrc"].as_u64().unwrap() as u32;
        let seq = k["inputs"]["seq"].as_u64().unwrap() as u16;
        let roc = k["inputs"]["roc"].as_u64().unwrap() as u32;
        let payload = hexd(&k, &["inputs", "payload"]);
        let ct = crypt_payload(&peer, ssrc, seq, roc, &payload);
        assert_eq!(
            hex::encode(&ct),
            k["e2e_srtp"]["cipher_out"].as_str().unwrap()
        );
        // Symmetric: decrypt round-trips.
        let pt = crypt_payload(&peer, ssrc, seq, roc, &ct);
        assert_eq!(pt, payload);
    }

    #[test]
    fn build_iv_tolerates_oversized_salt() {
        // Latent-panic guard: a salt longer than 14 bytes must not underflow `off` or panic the
        // slice. (The only production caller passes the 14-byte E2eSrtpKeys.salt.)
        let _ = build_e2e_rtp_iv(&[0u8; 16], 0x0102_0304, 0, 0);
        let _ = build_e2e_rtp_iv(&[0xABu8; 32], 0xdead_beef, 7, 0xFFFF);
        // The valid 14-byte path is unchanged: the salt lands left-aligned at bytes [0..14].
        let iv = build_e2e_rtp_iv(&[0x11u8; 14], 0, 0, 0);
        assert_eq!(&iv[0..14], &[0x11u8; 14]);
        assert_eq!(&iv[14..16], &[0u8; 2]);
    }

    #[test]
    fn crypt_payload_roundtrips_across_seq_wrap() {
        // The keystream stays aligned across a 16-bit sequence wrap: packets straddling 0xFFFF→0x0000
        // each decrypt under the ROC the recv estimator guesses, even with a small post-wrap reorder.
        // This is the send/recv ROC contract MediaPipeline depends on, exercised through the cipher.
        let keys = E2eSrtpKeys {
            cipher_key: [7u8; 16],
            salt: [9u8; 14],
            auth_key: [0u8; 20],
        };
        let ssrc = 0x5741_0001u32;
        let seqs = [0xFFFEu16, 0xFFFF, 0x0000, 0x0001];
        let plaintexts: Vec<Vec<u8>> = (0..4u8).map(|i| vec![i.wrapping_mul(37); 40]).collect();

        // Sender: monotonic seqs; the send ROC bumps at the wrap.
        let mut send_roc = RocTracker::default();
        let sent: Vec<(u16, Vec<u8>)> = seqs
            .iter()
            .zip(&plaintexts)
            .map(|(&seq, pt)| {
                let roc = send_roc.advance(seq);
                (seq, crypt_payload(&keys, ssrc, seq, roc, pt))
            })
            .collect();

        // Receiver sees a small post-wrap reorder (0x0000 and 0x0001 swapped); guess-index recovers
        // the right ROC for each, and the symmetric cipher must return the original plaintext.
        let mut recv_roc = RecvRocTracker::default();
        for &i in &[0usize, 1, 3, 2] {
            let (seq, ct) = &sent[i];
            let roc = recv_roc.guess_roc(*seq);
            let recovered = crypt_payload(&keys, ssrc, *seq, roc, ct);
            assert_eq!(
                &recovered, &plaintexts[i],
                "seq {seq:#06x} must decrypt across the wrap"
            );
        }
    }
}