srt-runtime 0.13.0

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs, sans-IO HSv5 handshakes, a one-connection link engine, ARQ, TSBPD, LiveCC/FileCC congestion control, optional payload crypto and an optional tokio UDP adapter; no_std core.
Documentation
//! The SYN Cookie and the Listener's stateless identifiers โ€” `draft-sharabayko-srt-01` ยง4.3.1.1
//! ("a cookie that is crafted based on host, port and current time with 1 minute accuracy";
//! `private/specs-verified/rules/srt-rules.md`).
//!
//! The draft names the cookie's inputs, not an algorithm. Here the cookie is a keyed MAC โ€”
//! HMAC-SHA-256 under the listener's secret โ€” over the peer's full address (family, IP, port),
//! the Caller's Socket ID and a coarse time bucket, so a cookie obtained from one source proves
//! nothing for another, and it expires once its bucket is two old. This crate never reads a
//! clock: the caller supplies the bucket (UNIX time / 60) and the secret (from a CSPRNG, replaced
//! periodically).

use core::net::{IpAddr, SocketAddr};

use hmac::digest::Key;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use subtle::ConstantTimeEq;

const COOKIE_DOMAIN: u8 = 0;
const SOCKET_ID_DOMAIN: u8 = 1;
const ISN_DOMAIN: u8 = 2;
const FAMILY_V4: u8 = 4;
const FAMILY_V6: u8 = 6;
const SECRET_LEN: usize = core::mem::size_of::<u128>();
const WORD_LEN: usize = core::mem::size_of::<u32>();

/// The key and the bucket a validated cookie was issued under.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct CookieOrigin {
    /// The time bucket the cookie was derived for.
    pub time_bucket: u32,
    /// The secret it was derived under.
    pub secret: u128,
}

impl core::fmt::Debug for CookieOrigin {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CookieOrigin")
            .field("time_bucket", &self.time_bucket)
            .finish_non_exhaustive()
    }
}

fn tag(
    domain: u8,
    peer: &SocketAddr,
    caller_socket_id: u32,
    time_bucket: u32,
    secret: u128,
) -> u32 {
    let mut key = Key::<Hmac<Sha256>>::default();
    key[..SECRET_LEN].copy_from_slice(&secret.to_le_bytes());
    let mut mac = Hmac::<Sha256>::new(&key);
    mac.update(&[domain]);
    match peer.ip() {
        IpAddr::V4(ip) => {
            mac.update(&[FAMILY_V4]);
            mac.update(&ip.octets());
        }
        IpAddr::V6(ip) => {
            mac.update(&[FAMILY_V6]);
            mac.update(&ip.octets());
        }
    }
    mac.update(&peer.port().to_be_bytes());
    mac.update(&caller_socket_id.to_be_bytes());
    mac.update(&time_bucket.to_be_bytes());
    let digest = mac.finalize().into_bytes();
    let mut word = [0u8; WORD_LEN];
    word.copy_from_slice(&digest[..WORD_LEN]);
    u32::from_be_bytes(word)
}

/// The SYN Cookie for `peer` and the Caller's `caller_socket_id` in `time_bucket`, under
/// `secret`. Never `0` (that value means "no cookie yet").
#[must_use]
pub fn derive_cookie(
    peer: &SocketAddr,
    caller_socket_id: u32,
    time_bucket: u32,
    secret: u128,
) -> u32 {
    tag(COOKIE_DOMAIN, peer, caller_socket_id, time_bucket, secret) | 1
}

/// Whether `cookie` was issued to `peer` and `caller_socket_id` under one of `secrets`, in
/// `now_bucket` or the bucket before it, compared in constant time. A cookie two buckets old is
/// refused.
#[must_use]
pub fn validate_cookie(
    peer: &SocketAddr,
    caller_socket_id: u32,
    cookie: u32,
    now_bucket: u32,
    secrets: impl IntoIterator<Item = u128> + Clone,
) -> Option<CookieOrigin> {
    let mut found = None;
    for time_bucket in [now_bucket, now_bucket.wrapping_sub(1)] {
        for secret in secrets.clone() {
            let derived = derive_cookie(peer, caller_socket_id, time_bucket, secret);
            if bool::from(derived.ct_eq(&cookie)) && found.is_none() {
                found = Some(CookieOrigin {
                    time_bucket,
                    secret,
                });
            }
        }
    }
    found
}

/// The Listener's per-connection Socket ID and Initial Sequence Number for a cookie issued over
/// the same inputs: a stateless Listener has nowhere to keep what its INDUCTION answer carried,
/// so the CONCLUSION recomputes it. Domain-separated from the cookie, so a Caller that has seen
/// its cookie cannot compute them. The Socket ID is never `0` (no socket assigned).
#[must_use]
pub fn derive_listener_ids(
    peer: &SocketAddr,
    caller_socket_id: u32,
    time_bucket: u32,
    secret: u128,
) -> (u32, u32) {
    let socket_id = tag(
        SOCKET_ID_DOMAIN,
        peer,
        caller_socket_id,
        time_bucket,
        secret,
    ) | 1;
    let initial_seq = tag(ISN_DOMAIN, peer, caller_socket_id, time_bucket, secret)
        & crate::packet::SEQ_NUMBER_MASK;
    (socket_id, initial_seq)
}

#[cfg(test)]
mod tests {
    use super::*;

    const SECRET: u128 = 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210;
    const BUCKET: u32 = 29_000_000;

    fn addr(s: &str) -> SocketAddr {
        s.parse().unwrap()
    }

    #[test]
    fn a_cookie_is_refused_from_another_address_port_or_socket_id() {
        let a = addr("198.51.100.1:4000");
        let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
        let ok = |p: &SocketAddr, id| validate_cookie(p, id, cookie, BUCKET, [SECRET]).is_some();
        assert!(ok(&a, 7));
        assert!(!ok(&addr("198.51.100.2:4000"), 7));
        assert!(!ok(&addr("198.51.100.1:4001"), 7));
        assert!(!ok(&a, 8));
        assert!(!ok(&addr("[::ffff:198.51.100.1]:4000"), 7));
    }

    #[test]
    fn a_cookie_older_than_two_buckets_is_refused_and_one_rolls_over() {
        let a = addr("198.51.100.1:4000");
        let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
        let at = |now| validate_cookie(&a, 7, cookie, now, [SECRET]);
        assert!(at(BUCKET).is_some());
        assert_eq!(at(BUCKET + 1).map(|o| o.time_bucket), Some(BUCKET));
        assert!(at(BUCKET + 2).is_none());
        assert!(at(BUCKET - 1).is_none());
    }

    #[test]
    fn a_cookie_under_another_secret_is_refused() {
        let a = addr("198.51.100.1:4000");
        let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
        assert!(validate_cookie(&a, 7, cookie, BUCKET, [SECRET ^ 1]).is_none());
        assert_eq!(
            validate_cookie(&a, 7, cookie, BUCKET, [SECRET ^ 1, SECRET]).map(|o| o.secret),
            Some(SECRET)
        );
    }

    /// The old peer key folded the address hash with the Socket ID by XOR, so two sources
    /// could be made to share a cookie by choosing Socket IDs; no such pair collides now.
    #[test]
    fn distinct_sources_never_share_a_cookie_by_choice_of_socket_id() {
        let a = addr("198.51.100.1:4000");
        let b = addr("198.51.100.1:4001");
        let wanted = derive_cookie(&a, 0, BUCKET, SECRET);
        let collides = (0..=u16::MAX)
            .map(u32::from)
            .any(|id| derive_cookie(&b, id, BUCKET, SECRET) == wanted);
        assert!(!collides);
    }

    #[test]
    fn identifiers_are_stable_in_range_and_not_the_cookie() {
        let a = addr("198.51.100.1:4000");
        let first = derive_listener_ids(&a, 7, BUCKET, SECRET);
        assert_eq!(first, derive_listener_ids(&a, 7, BUCKET, SECRET));
        assert_ne!(first.0, 0);
        assert!(first.1 <= crate::packet::SEQ_NUMBER_MASK);
        assert_ne!(first.0, derive_cookie(&a, 7, BUCKET, SECRET));
        assert_ne!(first, derive_listener_ids(&a, 7, BUCKET + 1, SECRET));
        assert_ne!(first, derive_listener_ids(&a, 7, BUCKET, SECRET ^ 1));
    }

    /// Pinned against an independent HMAC-SHA-256 (Python `hmac`): fixes the message layout
    /// and the key placement.
    #[test]
    fn the_cookie_matches_an_independent_hmac() {
        let a = addr("198.51.100.1:4000");
        assert_eq!(derive_cookie(&a, 7, BUCKET, SECRET), 0x131f_6c61);
    }

    #[test]
    fn both_halves_of_the_secret_feed_the_cookie_and_the_identifiers() {
        let a = addr("198.51.100.1:4000");
        let high = SECRET ^ (1u128 << 100);
        let low = SECRET ^ 1;
        for other in [high, low] {
            assert_ne!(
                derive_cookie(&a, 7, BUCKET, SECRET),
                derive_cookie(&a, 7, BUCKET, other)
            );
            assert_ne!(
                derive_listener_ids(&a, 7, BUCKET, SECRET),
                derive_listener_ids(&a, 7, BUCKET, other)
            );
        }
    }

    #[test]
    fn the_cookie_is_never_zero() {
        let a = addr("198.51.100.1:4000");
        assert!((0..1000).all(|id| derive_cookie(&a, id, BUCKET, SECRET) != 0));
    }
}