rtci-dtls 0.2.1

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,
}

#[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
    }

    // full_pull_map pulls all handshakes between rules[0] to rules[len(rules)-1] as map.
    pub(crate) fn full_pull_map(
        &self,
        start_seq: isize,
        rules: &[HandshakeCachePullRule],
    ) -> Result<(isize, HashMap<HandshakeType, HandshakeMessage>)> {
        let mut ci = HashMap::new();
        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 !r.optional && item.is_none() {
                // Missing mandatory message.
                return Err(Error::Other("Missing mandatory message".to_owned()));
            }

            if let Some(c) = item {
                ci.insert(r.typ, c);
            }
        }

        let mut out = HashMap::new();
        let mut seq = start_seq;
        for r in rules {
            let t = r.typ;
            if let Some(i) = ci.get(&t) {
                let mut reader = BufReader::new(i.data.as_slice());
                let raw_handshake = Handshake::unmarshal(&mut reader)?;
                if seq as u16 != raw_handshake.handshake_header.message_sequence {
                    // There is a gap. Some messages are not arrived.
                    return Err(Error::Other(
                        "There is a gap. Some messages are not arrived.".to_owned(),
                    ));
                }
                seq += 1;
                out.insert(t, raw_handshake.handshake_message);
            }
        }

        Ok((seq, out))
    }

    // 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
        })
    }
}