rtci-srtp 0.5.0

Sans-I/O SRTP and SRTCP (RFC 3711, RFC 7714 AES-GCM, RFC 9335 Cryptex) for WebRTC
Documentation
//! The SRTP key derivation function against the NIST CAVP vectors for SP 800-135 (`srtp.zip`,
//! CAVS 12.0, `srtp.rsp`, unmodified in `testdata/`; a work of the US government, public
//! domain): 30 cases, ten for each of AES-128, AES-192 and AES-256, with key derivation rates
//! from 0 to 256, each giving the three SRTP and the three SRTCP session keys.
//!
//! The SRTP keys are checked as they are. The SRTCP keys are not the engine's, on purpose:
//! CAVP builds the SRTCP `key_id` from the 32-bit index of RFC 3711 section 4.3.2 as printed
//! (`label || r` 40 bits wide, the label at octet 9 of the salt), while erratum 3712 (Held for
//! Document Update) widens the index to 48 bits as for SRTP (the label at octet 7), which is
//! what libsrtp and every WebRTC stack derive and so what the engine derives. The second test
//! pins that: the engine's SRTCP keys differ from CAVP's, and CAVP's are exactly what the same
//! PRF gives with the label moved to octet 9 (`docs/conformance/spec-issues.md`).

use crate::key_derivation::*;
use crate::test_util::{hex, provider};

/// The number of cases in `srtp.rsp`.
const CAVP_SRTP_CASES: usize = 30;

struct CavpCase {
    prf: Prf,
    master_key: Vec<u8>,
    master_salt: Vec<u8>,
    kdr: u64,
    index: u64,
    srtcp_index: u64,
    /// (label, expected session key), SRTP then SRTCP.
    keys: Vec<(u8, Vec<u8>)>,
}

fn cases() -> Vec<CavpCase> {
    let mut cases = Vec::new();
    let mut prf = None;
    let mut fields: Vec<(String, String)> = Vec::new();
    let mut flush = |prf: Option<Prf>, fields: &mut Vec<(String, String)>| {
        if fields.is_empty() {
            return;
        }
        let get = |key: &str| {
            fields
                .iter()
                .find(|(k, _)| k == key)
                .map(|(_, v)| v.clone())
                .unwrap_or_else(|| panic!("missing {key}"))
        };
        let number = |key: &str| u64::from_str_radix(&get(key), 16).expect("hex number");
        let keys = [
            ("SRTP k_e", LABEL_SRTP_ENCRYPTION),
            ("SRTP k_a", LABEL_SRTP_AUTHENTICATION_TAG),
            ("SRTP k_s", LABEL_SRTP_SALT),
            ("SRTCP k_e", LABEL_SRTCP_ENCRYPTION),
            ("SRTCP k_a", LABEL_SRTCP_AUTHENTICATION_TAG),
            ("SRTCP k_s", LABEL_SRTCP_SALT),
        ]
        .into_iter()
        .map(|(key, label)| (label, hex(&get(key))))
        .collect();
        cases.push(CavpCase {
            prf: prf.expect("a [AES-n] section"),
            master_key: hex(&get("k_master")),
            master_salt: hex(&get("master_salt")),
            kdr: number("kdr"),
            index: number("index"),
            srtcp_index: number("index (SRTCP)"),
            keys,
        });
        fields.clear();
    };
    for line in include_str!("testdata/nist_cavp_srtp_kdf.rsp").lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with('[') {
            flush(prf, &mut fields);
            prf = Some(match line {
                "[AES-128]" => Prf::Aes128,
                "[AES-192]" => Prf::Aes192,
                "[AES-256]" => Prf::Aes256,
                other => panic!("unknown section {other}"),
            });
            continue;
        }
        let (key, value) = line.split_once(" = ").expect("key = value");
        if key == "COUNT" {
            flush(prf, &mut fields);
            continue;
        }
        fields.push((key.to_owned(), value.to_owned()));
    }
    flush(prf, &mut fields);
    cases
}

/// `index DIV kdr`, with `a DIV 0 = 0` (RFC 3711 section 4.3.1).
fn div(index: u64, kdr: u64) -> u64 {
    index.checked_div(kdr).unwrap_or(0)
}

#[test]
fn srtp_session_keys_match_the_nist_cavp_srtp_kdf_vectors() {
    let provider = provider();
    let cases = cases();
    assert_eq!(cases.len(), CAVP_SRTP_CASES);
    let mut checked = 0;
    for (n, case) in cases.iter().enumerate() {
        for (label, expected) in &case.keys[..3] {
            let derived = derive(
                provider.crypto(),
                case.prf,
                *label,
                &case.master_key,
                &case.master_salt,
                div(case.index, case.kdr),
                expected.len(),
            )
            .unwrap();
            assert_eq!(
                derived.as_ref(),
                expected.as_slice(),
                "case {n} ({:?}, kdr {}), label {label}",
                case.prf,
                case.kdr
            );
            checked += 1;
        }
    }
    assert_eq!(checked, CAVP_SRTP_CASES * 3);
    // The rates reach past zero, so `index DIV kdr` is exercised.
    assert!(cases.iter().any(|case| case.kdr > 1));
}

#[test]
fn srtcp_session_keys_follow_erratum_3712_and_not_the_cavp_reading() {
    let provider = provider();
    let cases = cases();
    assert_eq!(cases.len(), CAVP_SRTP_CASES);
    for (n, case) in cases.iter().enumerate() {
        let r = div(case.srtcp_index, case.kdr);
        for (label, cavp) in &case.keys[3..] {
            let engine = derive(
                provider.crypto(),
                case.prf,
                *label,
                &case.master_key,
                &case.master_salt,
                r,
                cavp.len(),
            )
            .unwrap();
            assert_ne!(engine.as_ref(), cavp.as_slice(), "case {n}, label {label}");
            // CAVP's key_id: the label at octet 9, then the 32-bit r (octets 10 to 13).
            let mut salt = case.master_salt.clone();
            salt[9] ^= label;
            let pre_erratum = derive(
                provider.crypto(),
                case.prf,
                0,
                &case.master_key,
                &salt,
                r,
                cavp.len(),
            )
            .unwrap();
            assert_eq!(
                pre_erratum.as_ref(),
                cavp.as_slice(),
                "case {n}, label {label}"
            );
        }
    }
}