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
#[cfg(test)]
mod handshake_cache_test;

use crate::cipher_suite::*;
use crate::handshake::*;

use std::collections::HashMap;
use std::io::BufReader;

/// Most messages the cache holds. A full DTLS 1.2 handshake caches about ten; the cap stops a
/// peer that sends handshake messages under ever new sequence numbers from growing it.
pub(crate) const MAX_HANDSHAKE_CACHE_ITEMS: usize = 64;

#[derive(Clone, Debug)]
pub(crate) struct HandshakeCacheItem {
    typ: HandshakeType,
    is_client: bool,
    epoch: u16,
    message_sequence: u16,
    data: Vec<u8>,
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct HandshakeCachePullRule {
    pub(crate) typ: HandshakeType,
    pub(crate) epoch: u16,
    pub(crate) is_client: bool,
    pub(crate) optional: bool,
}

/// Why [`HandshakeCache::full_pull_map`] could not hand out a flight.
#[derive(Debug, PartialEq)]
pub(crate) enum PullError {
    /// A message of the flight has not arrived yet.
    Incomplete,
    /// The place of a message of the flight is taken by another message of the peer's.
    OutOfOrder,
    /// A cached message no longer decodes (it did when it was cached).
    Decode(Error),
}

#[derive(Clone)]
pub(crate) struct HandshakeCache {
    cache: Vec<HandshakeCacheItem>,
}

impl HandshakeCache {
    pub(crate) fn new() -> Self {
        HandshakeCache { cache: vec![] }
    }

    pub(crate) fn push(
        &mut self,
        data: Vec<u8>,
        epoch: u16,
        message_sequence: u16,
        typ: HandshakeType,
        is_client: bool,
    ) -> bool {
        for i in &self.cache {
            if i.message_sequence == message_sequence && i.is_client == is_client {
                return false;
            }
        }
        if self.cache.len() >= MAX_HANDSHAKE_CACHE_ITEMS {
            return false;
        }

        self.cache.push(HandshakeCacheItem {
            typ,
            is_client,
            epoch,
            message_sequence,
            data,
        });

        true
    }

    // The caller authenticates the record first. Recognize the complete Finished or
    // its final fragment without buffering a new post-handshake transcript. Only the
    // ending fragment triggers a reply, so fragmentation does not spend a retry per fragment.
    pub(crate) fn matches_received_finished(
        &self,
        mut data: &[u8],
        epoch: u16,
        is_client: bool,
    ) -> bool {
        while !data.is_empty() {
            let mut reader = data;
            let Ok(header) = HandshakeHeader::unmarshal(&mut reader) else {
                return false;
            };
            let fragment_length = header.fragment_length as usize;
            let Some(fragment) = reader.get(..fragment_length) else {
                return false;
            };
            let fragment_start = header.fragment_offset as usize;
            let fragment_end = fragment_start + fragment_length;
            if header.handshake_type == HandshakeType::Finished
                && fragment_length > 0
                && fragment_end == header.length as usize
                && self.cache.iter().any(|item| {
                    item.typ == HandshakeType::Finished
                        && item.epoch == epoch
                        && item.is_client == is_client
                        && item.message_sequence == header.message_sequence
                        && item.data.len() == HANDSHAKE_HEADER_LENGTH + header.length as usize
                        && item.data.get(
                            HANDSHAKE_HEADER_LENGTH + fragment_start
                                ..HANDSHAKE_HEADER_LENGTH + fragment_end,
                        ) == Some(fragment)
                })
            {
                return true;
            }
            data = &reader[fragment_length..];
        }
        false
    }

    // returns a list handshakes that match the requested rules
    // the list will contain null entries for rules that can't be satisfied
    // multiple entries may match a rule, but only the last match is returned (ie ClientHello with cookies)
    pub(crate) fn pull(&self, rules: &[HandshakeCachePullRule]) -> Vec<HandshakeCacheItem> {
        let mut out = vec![];
        for r in rules {
            let mut item: Option<HandshakeCacheItem> = None;
            for c in &self.cache {
                if c.typ == r.typ && c.is_client == r.is_client && c.epoch == r.epoch {
                    if let Some(x) = &item {
                        if x.message_sequence < c.message_sequence {
                            item = Some(c.clone());
                        }
                    } else {
                        item = Some(c.clone());
                    }
                }
            }

            if let Some(c) = item {
                out.push(c);
            }
        }

        out
    }

    /// The peer's flight as `rules` lists it, in that order, from message sequence `start_seq`
    /// on: each rule's message (the latest of its type, side and epoch) must sit at the next
    /// sequence number, and an optional one that is not there is skipped.
    ///
    /// When a rule's message is not at the sequence number it should hold, what holds that
    /// number decides. Nothing yet: the flight is still arriving ([`PullError::Incomplete`]).
    /// A message of the peer's: it is in the wrong place, a later message sent first, a
    /// message sent twice, or a required one left out (RFC 5246 7.4: handshake messages in an
    /// unexpected order are a fatal error), and waiting cannot mend that: the place is taken
    /// ([`PullError::OutOfOrder`]).
    pub(crate) fn full_pull_map(
        &self,
        start_seq: isize,
        rules: &[HandshakeCachePullRule],
    ) -> std::result::Result<(isize, HashMap<HandshakeType, HandshakeMessage>), PullError> {
        let mut out = HashMap::new();
        let mut seq = start_seq;
        for r in rules {
            let item = self
                .cache
                .iter()
                .filter(|c| c.typ == r.typ && c.is_client == r.is_client && c.epoch == r.epoch)
                .max_by_key(|c| c.message_sequence);
            let expected = seq as u16;
            match item {
                Some(c) if c.message_sequence == expected => {
                    let mut reader = BufReader::new(c.data.as_slice());
                    let raw_handshake =
                        Handshake::unmarshal(&mut reader).map_err(PullError::Decode)?;
                    seq += 1;
                    out.insert(r.typ, raw_handshake.handshake_message);
                }
                // An optional message that is absent, or is only one from an earlier flight.
                None if r.optional => {}
                Some(c) if r.optional && c.message_sequence < expected => {}
                _ => return Err(self.why_not_at(expected, r.is_client)),
            }
        }

        Ok((seq, out))
    }

    /// Why the message a flight needs at `message_sequence` is not there: nothing of the peer's
    /// holds that number yet, or something else does.
    fn why_not_at(&self, message_sequence: u16, is_client: bool) -> PullError {
        if self.holds_message_at(message_sequence, is_client) {
            PullError::OutOfOrder
        } else {
            PullError::Incomplete
        }
    }

    /// Whether a message of the peer (`is_client`) under `message_sequence`, of any type and
    /// epoch, has been received.
    pub(crate) fn holds_message_at(&self, message_sequence: u16, is_client: bool) -> bool {
        self.cache
            .iter()
            .any(|c| c.message_sequence == message_sequence && c.is_client == is_client)
    }

    // pull_and_merge calls pull and then merges the results, ignoring any null entries
    pub(crate) fn pull_and_merge(&self, rules: &[HandshakeCachePullRule]) -> Vec<u8> {
        let mut merged = vec![];

        for p in &self.pull(rules) {
            merged.extend_from_slice(&p.data);
        }

        merged
    }

    // session_hash returns the session hash for Extended Master Secret support
    // https://tools.ietf.org/html/draft-ietf-tls-session-hash-06#section-4
    pub(crate) fn session_hash(
        &self,
        crypto: &dyn crypto::RTCCrypto,
        hf: CipherSuiteHash,
        epoch: u16,
        additional: &[u8],
    ) -> Result<Vec<u8>> {
        let mut merged = vec![];

        // Order defined by https://tools.ietf.org/html/rfc5246#section-7.3
        let handshake_buffer = self.pull(&[
            HandshakeCachePullRule {
                typ: HandshakeType::ClientHello,
                epoch,
                is_client: true,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::ServerHello,
                epoch,
                is_client: false,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::Certificate,
                epoch,
                is_client: false,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::ServerKeyExchange,
                epoch,
                is_client: false,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::CertificateRequest,
                epoch,
                is_client: false,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::ServerHelloDone,
                epoch,
                is_client: false,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::Certificate,
                epoch,
                is_client: true,
                optional: false,
            },
            HandshakeCachePullRule {
                typ: HandshakeType::ClientKeyExchange,
                epoch,
                is_client: true,
                optional: false,
            },
        ]);

        for p in &handshake_buffer {
            merged.extend_from_slice(&p.data);
        }

        merged.extend_from_slice(additional);

        crypto
            .hash(hf.hash_algorithm(), &merged)
            .map_err(|error| Error::Crypto(error.to_string()))
    }

    /// Whether `data`, one complete handshake message with its header, is byte for byte the
    /// message cached under its sequence number for `epoch` and `is_client`: a repeat of a
    /// message already received, not a different one under a reused sequence number.
    pub(crate) fn contains_message(&self, data: &[u8], epoch: u16, is_client: bool) -> bool {
        let mut reader = data;
        let Ok(header) = HandshakeHeader::unmarshal(&mut reader) else {
            return false;
        };
        self.cache.iter().any(|item| {
            item.message_sequence == header.message_sequence
                && item.is_client == is_client
                && item.epoch == epoch
                && item.data == data
        })
    }
}