rtci-dtls 0.5.0

Sans-I/O DTLS 1.2 and 1.3 (RFC 6347, RFC 9147) with DTLS-SRTP key export, for WebRTC
Documentation
//! The DTLS 1.2 PRF (RFC 5246 section 5, which DTLS 1.2 keeps) against the NIST CAVP vectors
//! for SP 800-135 (`tls.zip`, CAVS 12.0, `tls.rsp`, unmodified in `testdata/`; a work of the US
//! government, public domain): the master secret from the pre-master secret and the hello
//! randoms, and the key block from the master secret, through `prf_master_secret` and
//! `prf_encryption_keys` as the handshake calls them. The file has four sections of ten cases:
//! TLS 1.2 with SHA-256 and with SHA-384 are the PRFs of the DTLS 1.2 suites and are run; TLS
//! 1.0/1.1 (MD5 and SHA-1) and TLS 1.2 with SHA-512 are PRFs no DTLS 1.2 suite uses, counted
//! and not run.

use super::*;

/// The cases in `tls.rsp`, and how many of them have a PRF of the DTLS 1.2 suites.
const CAVP_TLS_CASES: usize = 40;
const CAVP_TLS_CASES_RUN: usize = 20;

#[test]
fn the_tls_1_2_prf_matches_the_nist_cavp_tls_kdf_vectors() -> Result<()> {
    let provider = crypto::default_provider().unwrap();
    let crypto = provider.crypto();
    let hex = |s: &str| -> Vec<u8> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex"))
            .collect()
    };
    let mut hash: Option<CipherSuiteHash> = None;
    let mut key_block_bits = 0usize;
    let mut fields: Vec<(String, Vec<u8>)> = Vec::new();
    let (mut cases, mut run) = (0usize, 0usize);
    let mut check = |hash: Option<CipherSuiteHash>,
                     key_block_bits: usize,
                     fields: &mut Vec<(String, Vec<u8>)>|
     -> Result<()> {
        if fields.is_empty() {
            return Ok(());
        }
        cases += 1;
        let get = |key: &str| -> &[u8] {
            &fields
                .iter()
                .find(|(k, _)| k == key)
                .unwrap_or_else(|| panic!("missing {key}"))
                .1
        };
        if let Some(h) = hash {
            let master = prf_master_secret(
                crypto,
                get("pre_master_secret"),
                get("clientHello_random"),
                get("serverHello_random"),
                h,
            )?;
            assert_eq!(master.as_ref(), get("master_secret"), "case {cases}");
            assert_eq!(key_block_bits % 64, 0);
            let length = key_block_bits / 8;
            let keys = prf_encryption_keys(
                crypto,
                master.as_ref(),
                get("client_random"),
                get("server_random"),
                EncryptionKeyLengths {
                    mac: length / 4,
                    key: length / 8,
                    iv: length / 8,
                },
                h,
            )?;
            let block = [
                keys.client_mac_key.as_slice(),
                &keys.server_mac_key,
                &keys.client_write_key,
                &keys.server_write_key,
                &keys.client_write_iv,
                &keys.server_write_iv,
            ]
            .concat();
            assert_eq!(block, get("key_block"), "case {cases}");
            run += 1;
        }
        fields.clear();
        Ok(())
    };
    for line in include_str!("testdata/nist_cavp_tls_kdf.rsp").lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
            check(hash, key_block_bits, &mut fields)?;
            if let Some(bits) = section.strip_prefix("key block length = ") {
                key_block_bits = bits.parse().expect("a length");
            } else if section.starts_with("TLS") {
                hash = match section {
                    "TLS 1.2, SHA-256" => Some(CipherSuiteHash::Sha256),
                    "TLS 1.2, SHA-384" => Some(CipherSuiteHash::Sha384),
                    "TLS 1.0/1.1" | "TLS 1.2, SHA-512" => None,
                    other => panic!("unknown section {other}"),
                };
            }
            continue;
        }
        let (key, value) = line.split_once(" = ").expect("key = value");
        if key == "COUNT" {
            check(hash, key_block_bits, &mut fields)?;
            continue;
        }
        fields.push((key.to_owned(), hex(value)));
    }
    check(hash, key_block_bits, &mut fields)?;
    assert_eq!((cases, run), (CAVP_TLS_CASES, CAVP_TLS_CASES_RUN));
    Ok(())
}