rtci 0.5.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
//! Which DTLS association a datagram that arrived on the replaced association's own path
//! belongs to, while both are alive (RFC 8842 section 5.5: "each endpoint needs to be prepared
//! to receive data on both the new and old DTLS associations as long as both are alive").
//!
//! RFC 8842 section 5.1 gives the two ways to tell them apart: "In the case of an ordered
//! transport (e.g., SCTP), this can be done simply by sending packets for the new DTLS
//! association after all packets associated with a previously established DTLS association
//! have been sent. In the case of an unordered transport, such as UDP, ... The only way to
//! demultiplex packets associated with a previously established DTLS association and the new
//! DTLS association is on the basis of the 5-tuple."
//!
//! - The default allocates a new 3-tuple on both sides, and a datagram on one of the replaced
//!   association's local UDP addresses is that association's (`IceHandler`, before this).
//! - On an ICE-TCP connection the replaced association ran on, the order decides: what arrives
//!   before the new association's first record on that connection is the replaced
//!   association's, everything from that record on is the new one's (RFC 4571 framing keeps
//!   the record boundaries). The sender side keeps the same order: the replaced association
//!   sends nothing more on the connection once this side has sent a record of the new one on
//!   it ([`PreviousAssociationPath::may_send_previous`]).
//! - On a UDP 5-tuple both associations may use (a peer that allocated nothing:
//!   `with_dtls_new_association_on_previous_addresses(true)` on both sides, or a new
//!   association without an ICE restart, `with_dtls_new_association_without_ice_restart`),
//!   the 5-tuple cannot tell them apart, so the records themselves do: a record in the clear
//!   (DTLSPlaintext with epoch 0: RFC 6347 section 4.1, RFC 9147 section 4) only begins a
//!   handshake, which is the new association's (the replaced one is established: its records
//!   are protected); a protected record authenticates under the keys of one association only,
//!   so it is tried with the replaced association first, and given to the new one when the
//!   replaced one takes nothing from it. This trial costs one authentication attempt per
//!   datagram, only on that 5-tuple and only while the replaced association is kept (at most
//!   `PREVIOUS_ASSOCIATION_MAX`).

use ice::agent::MediaPath;
use shared::{TransportContext, TransportProtocol};

/// How a DTLS datagram on the replaced association's path is read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PreviousPathRoute {
    /// By the current association (the start of a handshake, or, on a TCP connection, any
    /// record from the new association's first one on).
    Current,
    /// By the replaced association (on a TCP connection, before the new association's first
    /// record).
    Previous,
    /// By the replaced association if it takes it, else by the current one (UDP, a 5-tuple
    /// both may use).
    Either,
}

/// The path the replaced association ran on when a new one replaced it, while it is kept.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PreviousAssociationPath {
    path: MediaPath,
    /// TCP: the new association's first record arrived on the connection.
    new_received: bool,
    /// TCP: this side sent a record of the new association on the connection.
    new_sent: bool,
}

impl PreviousAssociationPath {
    pub(crate) fn new(path: MediaPath) -> Self {
        Self {
            path,
            new_received: false,
            new_sent: false,
        }
    }

    fn ordered(&self) -> bool {
        self.path.transport_protocol == TransportProtocol::TCP
    }

    fn is(
        &self,
        local_addr: std::net::SocketAddr,
        peer_addr: std::net::SocketAddr,
        protocol: TransportProtocol,
    ) -> bool {
        self.path.local_addr == local_addr
            && self.path.peer_addr == peer_addr
            && self.path.transport_protocol == protocol
    }

    /// How the DTLS datagram that arrived on `transport` is read; `None` when it did not
    /// arrive on this path.
    pub(crate) fn route_read(
        &mut self,
        transport: &TransportContext,
        datagram: &[u8],
    ) -> Option<PreviousPathRoute> {
        if !self.is(
            transport.local_addr,
            transport.peer_addr,
            transport.transport_protocol,
        ) {
            return None;
        }
        let begins_handshake = plaintext_epoch_zero(datagram);
        if self.ordered() {
            if self.new_received || begins_handshake {
                self.new_received = true;
                return Some(PreviousPathRoute::Current);
            }
            return Some(PreviousPathRoute::Previous);
        }
        Some(if begins_handshake {
            PreviousPathRoute::Current
        } else {
            PreviousPathRoute::Either
        })
    }

    /// The current association sent a datagram on `path`.
    pub(crate) fn sent_current(&mut self, path: &MediaPath) {
        if self.ordered() && *path == self.path {
            self.new_sent = true;
        }
    }

    /// Whether the replaced association may still send on `path` (its `close_notify`): its own
    /// path, and on a TCP connection only while this side has sent nothing of the new
    /// association on it (RFC 8842 section 5.1: the new association's packets go "after all
    /// packets associated with a previously established DTLS association have been sent").
    pub(crate) fn may_send_previous(&self, path: &MediaPath) -> bool {
        *path == self.path && !(self.ordered() && self.new_sent)
    }
}

/// Whether the datagram's first record is in the clear: a DTLSPlaintext header (content type
/// 20 to 26, version major byte 254) with epoch 0 (RFC 6347 section 4.1, RFC 9147 section 4.1:
/// a protected DTLS 1.3 record has the unified header, first byte 0b001xxxxx, and a protected
/// DTLS 1.2 record an epoch above 0).
pub(crate) fn plaintext_epoch_zero(datagram: &[u8]) -> bool {
    datagram.len() >= 13
        && (20..=26).contains(&datagram[0])
        && datagram[1] == 0xfe
        && datagram[3] == 0
        && datagram[4] == 0
}

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

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

    fn path(protocol: TransportProtocol) -> MediaPath {
        MediaPath {
            local_addr: addr("10.0.0.1:5000"),
            peer_addr: addr("10.0.0.2:5000"),
            transport_protocol: protocol,
        }
    }

    fn on(path: &MediaPath) -> TransportContext {
        TransportContext {
            local_addr: path.local_addr,
            peer_addr: path.peer_addr,
            transport_protocol: path.transport_protocol,
            ecn: None,
        }
    }

    /// A DTLS 1.2 ClientHello record header (epoch 0), a DTLS 1.2 protected record (epoch 1)
    /// and a DTLS 1.3 protected record (unified header).
    const CLIENT_HELLO: [u8; 13] = [22, 0xfe, 0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40];
    const PROTECTED_12: [u8; 13] = [23, 0xfe, 0xfd, 0, 1, 0, 0, 0, 0, 0, 7, 0, 40];
    const PROTECTED_13: [u8; 13] = [0x2f, 0, 7, 0, 40, 1, 2, 3, 4, 5, 6, 7, 8];

    #[test]
    fn a_record_in_the_clear_is_told_from_a_protected_one() {
        assert!(plaintext_epoch_zero(&CLIENT_HELLO));
        assert!(plaintext_epoch_zero(&[
            20, 0xfe, 0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
        ]));
        assert!(!plaintext_epoch_zero(&PROTECTED_12));
        assert!(!plaintext_epoch_zero(&PROTECTED_13));
        assert!(!plaintext_epoch_zero(&CLIENT_HELLO[..12]));
    }

    /// RFC 8842 section 5.1, an ordered transport: on the replaced association's TCP
    /// connection, records before the new association's first one are the replaced
    /// association's, and every record from it on is the new one's (a protected record of the
    /// new handshake included). Another connection is not this path.
    #[test]
    fn on_a_tcp_connection_the_order_tells_the_associations_apart() {
        let tcp = path(TransportProtocol::TCP);
        let mut p = PreviousAssociationPath::new(tcp);
        assert_eq!(
            p.route_read(&on(&tcp), &PROTECTED_12),
            Some(PreviousPathRoute::Previous)
        );
        assert_eq!(
            p.route_read(&on(&tcp), &PROTECTED_13),
            Some(PreviousPathRoute::Previous)
        );
        assert_eq!(
            p.route_read(&on(&tcp), &CLIENT_HELLO),
            Some(PreviousPathRoute::Current),
            "the new association's first record"
        );
        assert_eq!(
            p.route_read(&on(&tcp), &PROTECTED_12),
            Some(PreviousPathRoute::Current),
            "after it, everything on the connection is the new association's"
        );
        let mut other = on(&tcp);
        other.peer_addr = addr("10.0.0.2:5001");
        assert_eq!(
            p.route_read(&other, &PROTECTED_12),
            None,
            "another connection"
        );
    }

    /// The sender side of the same rule: the replaced association's `close_notify` goes on its
    /// TCP connection only while this side has sent nothing of the new association on it.
    #[test]
    fn on_a_tcp_connection_the_replaced_association_sends_only_before_the_new_one() {
        let tcp = path(TransportProtocol::TCP);
        let mut p = PreviousAssociationPath::new(tcp);
        assert!(p.may_send_previous(&tcp));
        let mut elsewhere = tcp;
        elsewhere.peer_addr = addr("10.0.0.2:5001");
        p.sent_current(&elsewhere);
        assert!(
            p.may_send_previous(&tcp),
            "the new association on another connection"
        );
        assert!(
            !p.may_send_previous(&elsewhere),
            "not the replaced association's path"
        );
        p.sent_current(&tcp);
        assert!(
            !p.may_send_previous(&tcp),
            "the new association began on the connection"
        );
    }

    /// RFC 8842 section 5.1, an unordered transport on a 5-tuple both associations may use: a
    /// record in the clear begins the new association's handshake; a protected one is tried
    /// with the replaced association first. The replaced association always sends on its UDP
    /// path.
    #[test]
    fn on_a_shared_udp_five_tuple_the_records_tell_the_associations_apart() {
        let udp = path(TransportProtocol::UDP);
        let mut p = PreviousAssociationPath::new(udp);
        assert_eq!(
            p.route_read(&on(&udp), &CLIENT_HELLO),
            Some(PreviousPathRoute::Current)
        );
        assert_eq!(
            p.route_read(&on(&udp), &PROTECTED_12),
            Some(PreviousPathRoute::Either)
        );
        assert_eq!(
            p.route_read(&on(&udp), &PROTECTED_13),
            Some(PreviousPathRoute::Either),
            "no order on UDP: the clear record did not switch the path"
        );
        p.sent_current(&udp);
        assert!(p.may_send_previous(&udp));
    }
}