rtci-srtp 0.5.0

Sans-I/O SRTP and SRTCP (RFC 3711, RFC 7714 AES-GCM, RFC 9335 Cryptex) for WebRTC
Documentation
//! Long-run soak: the SRTP rollover counter (RFC 3711 section 3.3.1, Appendix A) and the SRTCP
//! index (section 3.4) across their boundaries, with loss, reordering, late packets from the
//! previous rollover count and replays at the boundary. Deterministic; nothing is timed.

use super::test_support::*;
use super::*;
use bytes::BytesMut;

const SSRC: u32 = 0x5157_0001;

/// The order a receiver gets packets `0..count` in: packet `wrap` is the first after the
/// boundary. Every 53rd is lost; every 37th pair is swapped and every 500th run of ten is
/// reversed; the last 30 before the boundary arrive after the first 30 after it (59 behind the
/// newest at most, inside the 64-packet window); now and then a packet is held back 100
/// places, outside the window.
enum Delivery {
    /// The packet is new: it decrypts, to the packet sent.
    Fresh(usize),
    /// The packet was accepted before, or is older than the window: it is refused.
    Refused(usize),
}

fn schedule(count: usize, wrap: usize) -> Vec<Delivery> {
    let lost = |k: usize| k % 53 == 7;
    let held_back = |k: usize| k % 997 == 500 && !(wrap - 40..wrap + 40).contains(&k);
    let mut order: Vec<usize> = (0..count).collect();
    for start in (0..count - 10).step_by(500).skip(1) {
        order[start..start + 10].reverse();
    }
    for k in (0..count - 1).step_by(37).skip(1) {
        order.swap(k, k + 1);
    }
    // The last 30 before the boundary after the first 30 past it.
    let late: Vec<usize> = (wrap - 30..wrap).collect();
    order.retain(|k| !late.contains(k));
    let at = order.iter().position(|&k| k == wrap + 29).unwrap() + 1;
    order.splice(at..at, late);

    let mut deliveries = vec![];
    let mut held = vec![];
    for (position, &k) in order.iter().enumerate() {
        if lost(k) {
            continue;
        }
        if held_back(k) {
            held.push((position + 100, k));
            continue;
        }
        deliveries.push(Delivery::Fresh(k));
        // A replay of a packet delivered a few places before.
        if position % 211 == 0 && position >= 5 && !lost(order[position - 5]) {
            let earlier = order[position - 5];
            if !held_back(earlier) {
                deliveries.push(Delivery::Refused(earlier));
            }
        }
        while let Some(&(due, k)) = held.first() {
            if due > position {
                break;
            }
            held.remove(0);
            deliveries.push(Delivery::Refused(k));
        }
    }
    // Just after the boundary, a replay of a packet from before it.
    let replay_at = deliveries
        .iter()
        .position(|delivery| matches!(delivery, Delivery::Fresh(k) if *k == wrap + 35))
        .unwrap();
    deliveries.insert(replay_at + 1, Delivery::Refused(wrap - 10));
    deliveries
}

/// SRTP across five rollover boundaries: ROC 0 to 1 (packet index 2^16), 1 to 2, 0xFFFF to
/// 0x1_0000 (index 2^32), 0x1_0000 to 0x1_0001 and 0xFFFF_FFFD to 0xFFFF_FFFE, alternating
/// AES-CM/HMAC-SHA1 and AES-GCM. 6000 packets around each boundary, delivered as
/// [`schedule`] says: every fresh packet decrypts to what was sent (the late ones from the
/// previous rollover count included), every replay and every packet older than the window is
/// refused, and the receiver's rollover counter ends one past where it began.
#[test]
fn srtp_decrypts_across_rollovers_with_reordering_and_replays_at_the_boundary() {
    let boundaries = [0u32, 1, 0xFFFF, 0x1_0000, 0xFFFF_FFFD];
    for (n, &roc) in boundaries.iter().enumerate() {
        let profile = if n % 2 == 0 {
            ProtectionProfile::Aes128CmHmacSha1_80
        } else {
            ProtectionProfile::AeadAes128Gcm
        };
        const COUNT: usize = 6_000;
        const WRAP: usize = 3_000;
        let first_sequence = (65_536 - WRAP) as u16;
        let mut sender = context(profile);
        sender.set_roc(SSRC, roc);
        let mut sent = vec![];
        for k in 0..COUNT {
            let sequence_number = first_sequence.wrapping_add(k as u16);
            let payload = (k as u32).to_be_bytes();
            let plaintext = rtp(SSRC, sequence_number, &payload);
            let protected = sender.encrypt_rtp(&plaintext).unwrap();
            sent.push((plaintext, protected));
        }
        assert_eq!(
            Some(roc + 1),
            sender.get_roc(SSRC),
            "the sender crossed the boundary at ROC {roc:#x}"
        );

        let mut receiver = context(profile);
        receiver.set_roc(SSRC, roc);
        let (mut fresh, mut refused) = (0, 0);
        for delivery in schedule(COUNT, WRAP) {
            match delivery {
                Delivery::Fresh(k) => {
                    let decrypted = receiver.decrypt_rtp(&sent[k].1).unwrap_or_else(|e| {
                        panic!("ROC {roc:#x}, {profile:?}: packet {k} refused: {e}")
                    });
                    assert_eq!(&sent[k].0[..], &decrypted[..], "ROC {roc:#x}: packet {k}");
                    fresh += 1;
                }
                Delivery::Refused(k) => {
                    assert!(
                        receiver.decrypt_rtp(&sent[k].1).is_err(),
                        "ROC {roc:#x}, {profile:?}: packet {k} accepted again or too late"
                    );
                    refused += 1;
                }
            }
        }
        assert!(fresh > COUNT * 9 / 10, "{fresh} decrypted");
        assert!(refused >= 10, "{refused} refused");
        assert_eq!(Some(roc + 1), receiver.get_roc(SSRC), "ROC {roc:#x}");
    }
}

/// SRTCP: the index is 31 bits and goes up by one, modulo 2^31, per packet (RFC 3711 section
/// 3.4). 4000 packets from 2000 before the wrap, delivered as [`schedule`] says, decrypt across
/// it; replays and packets older than the window are refused there as anywhere.
#[test]
fn srtcp_decrypts_across_the_index_wrap_with_reordering_and_replays() {
    const COUNT: usize = 4_000;
    const WRAP: usize = 2_000;
    for profile in [
        ProtectionProfile::Aes128CmHmacSha1_80,
        ProtectionProfile::AeadAes128Gcm,
    ] {
        let mut sender = context(profile);
        sender.set_index(RTCP_SSRC, (1 << 31) - WRAP);
        let plaintext = rtcp();
        let sent: Vec<BytesMut> = (0..COUNT)
            .map(|_| sender.encrypt_rtcp(&plaintext).unwrap())
            .collect();
        assert_eq!(
            0x7FFF_FFFF,
            srtcp_index(profile, &sent[WRAP - 1], 0),
            "the last index before the wrap"
        );
        assert_eq!(
            0,
            srtcp_index(profile, &sent[WRAP], 0),
            "and the first after it"
        );

        let mut receiver = context(profile);
        let (mut fresh, mut refused) = (0, 0);
        for delivery in schedule(COUNT, WRAP) {
            match delivery {
                Delivery::Fresh(k) => {
                    let decrypted = receiver
                        .decrypt_rtcp(&sent[k])
                        .unwrap_or_else(|e| panic!("{profile:?}: SRTCP packet {k} refused: {e}"));
                    assert_eq!(&plaintext[..], &decrypted[..], "{profile:?}: packet {k}");
                    fresh += 1;
                }
                Delivery::Refused(k) => {
                    assert!(
                        receiver.decrypt_rtcp(&sent[k]).is_err(),
                        "{profile:?}: SRTCP packet {k} accepted again or too late"
                    );
                    refused += 1;
                }
            }
        }
        assert!(fresh > COUNT * 9 / 10, "{fresh} decrypted");
        assert!(refused >= 5, "{refused} refused");
    }
}