rtci-dtls 0.2.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_message_client_hello_test;

use super::handshake_random::*;
use super::*;
use crate::cipher_suite::*;
use crate::compression_methods::*;
use crate::extension::*;
use crate::record_layer::record_layer_header::*;

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::fmt;
use std::io::BufWriter;

/*
When a client first connects to a server it is required to send
the client hello as its first message.  The client can also send a
client hello in response to a hello request or on its own
initiative in order to renegotiate the security parameters in an
existing connection.
*/
#[derive(Clone)]
/// The client's opening message: its random, cookie, offered cipher suites and extensions.
pub struct HandshakeMessageClientHello {
    pub(crate) version: ProtocolVersion,
    pub(crate) random: HandshakeRandom,
    /// The session the client asks to resume (RFC 5246 7.4.1.2), empty for none.
    pub(crate) session_id: Vec<u8>,
    pub(crate) cookie: Vec<u8>,

    pub(crate) cipher_suites: Vec<CipherSuiteId>,
    pub(crate) compression_methods: CompressionMethods,
    pub(crate) extensions: Vec<Extension>,
}

impl PartialEq for HandshakeMessageClientHello {
    fn eq(&self, other: &Self) -> bool {
        if !(self.version == other.version
            && self.random == other.random
            && self.session_id == other.session_id
            && self.cookie == other.cookie
            && self.compression_methods == other.compression_methods
            && self.extensions == other.extensions
            && self.cipher_suites.len() == other.cipher_suites.len())
        {
            return false;
        }

        for i in 0..self.cipher_suites.len() {
            if self.cipher_suites[i] != other.cipher_suites[i] {
                return false;
            }
        }

        true
    }
}

impl fmt::Debug for HandshakeMessageClientHello {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut cipher_suites_str = String::new();
        for cipher_suite in &self.cipher_suites {
            cipher_suites_str += &cipher_suite.to_string();
            cipher_suites_str += " ";
        }
        let s = [
            format!("version: {:?} random: {:?}", self.version, self.random),
            format!("session_id: {:?}", self.session_id),
            format!("cookie: {:?}", self.cookie),
            format!("cipher_suites: {cipher_suites_str:?}"),
            format!("compression_methods: {:?}", self.compression_methods),
            format!("extensions: {:?}", self.extensions),
        ];
        write!(f, "{}", s.join(" "))
    }
}

const HANDSHAKE_MESSAGE_CLIENT_HELLO_VARIABLE_WIDTH_START: usize = 34;

/// The longest session id a hello carries (RFC 5246 7.4.1.2).
pub(crate) const MAX_SESSION_ID_LENGTH: usize = 32;

impl HandshakeMessageClientHello {
    /// The handshake type that identifies this message on the wire.
    pub fn handshake_type(&self) -> HandshakeType {
        HandshakeType::ClientHello
    }

    /// The encoded size of this message in bytes.
    pub fn size(&self) -> usize {
        let mut len = 0;

        len += 2; // version.major+minor
        len += self.random.size();

        // SessionID
        len += 1 + self.session_id.len();

        len += 1 + self.cookie.len();

        len += 2 + 2 * self.cipher_suites.len();

        len += self.compression_methods.size();

        len += 2;
        for extension in &self.extensions {
            len += extension.size();
        }

        len
    }

    /// Encodes this message to `writer`.
    ///
    /// # Errors
    ///
    /// Fails on a write error, or if a field exceeds the length its wire format allows.
    pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
        if self.cookie.len() > 255 {
            return Err(Error::ErrCookieTooLong);
        }
        if self.session_id.len() > MAX_SESSION_ID_LENGTH {
            return Err(Error::ErrInvalidPacketLength);
        }

        writer.write_u8(self.version.major)?;
        writer.write_u8(self.version.minor)?;
        self.random.marshal(writer)?;

        // SessionID<0..32>
        writer.write_u8(self.session_id.len() as u8)?;
        writer.write_all(&self.session_id)?;

        writer.write_u8(self.cookie.len() as u8)?;
        writer.write_all(&self.cookie)?;

        writer.write_u16::<BigEndian>(2 * self.cipher_suites.len() as u16)?;
        for cipher_suite in &self.cipher_suites {
            writer.write_u16::<BigEndian>(*cipher_suite as u16)?;
        }

        self.compression_methods.marshal(writer)?;

        let mut extension_buffer = vec![];
        {
            let mut extension_writer = BufWriter::<&mut Vec<u8>>::new(extension_buffer.as_mut());
            for extension in &self.extensions {
                extension.marshal(&mut extension_writer)?;
            }
        }

        writer.write_u16::<BigEndian>(extension_buffer.len() as u16)?;
        writer.write_all(&extension_buffer)?;

        Ok(writer.flush()?)
    }

    /// Decodes one of these messages from `reader`.
    ///
    /// # Errors
    ///
    /// Fails if `reader` is truncated or its contents are not a valid encoding.
    pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self> {
        let major = reader.read_u8()?;
        let minor = reader.read_u8()?;
        let random = HandshakeRandom::unmarshal(reader)?;

        // SessionID<0..32> (RFC 5246 7.4.1.2): the session the client asks to resume.
        let session_id_len = reader.read_u8()? as usize;
        if session_id_len > MAX_SESSION_ID_LENGTH {
            return Err(Error::ErrInvalidPacketLength);
        }
        let mut session_id = vec![0u8; session_id_len];
        reader.read_exact(&mut session_id)?;

        let cookie_len = reader.read_u8()? as usize;
        let mut cookie = vec![0; cookie_len];
        reader.read_exact(&mut cookie)?;

        let cipher_suites_bytes = reader.read_u16::<BigEndian>()? as usize;
        if !cipher_suites_bytes.is_multiple_of(2) {
            return Err(Error::ErrInvalidPacketLength);
        }
        let mut cipher_suites = vec![];
        for _ in 0..cipher_suites_bytes / 2 {
            let id: CipherSuiteId = reader.read_u16::<BigEndian>()?.into();
            cipher_suites.push(id);
        }

        let compression_methods = CompressionMethods::unmarshal(reader)?;

        // The message may end here (RFC 5246 7.4.1.2); otherwise the extensions block follows
        // and ends the message.
        let extensions = unmarshal_hello_extensions(reader)?;

        Ok(HandshakeMessageClientHello {
            version: ProtocolVersion { major, minor },
            random,
            session_id,
            cookie,

            cipher_suites,
            compression_methods,
            extensions,
        })
    }
}