Skip to main content

rtc_dtls/handshake/
handshake_message_server_key_exchange.rs

1#[cfg(test)]
2mod handshake_message_server_key_exchange_test;
3
4use super::*;
5use crate::curve::named_curve::*;
6use crate::curve::*;
7use crate::signature_hash_algorithm::*;
8
9use byteorder::{BigEndian, WriteBytesExt};
10use std::io::{Read, Write};
11
12// Structure supports ECDH and PSK
13#[derive(Clone, Debug, PartialEq, Eq)]
14/// The server's half of the key agreement, signed so the client can authenticate it.
15pub struct HandshakeMessageServerKeyExchange {
16    pub(crate) identity_hint: Vec<u8>,
17
18    pub(crate) elliptic_curve_type: EllipticCurveType,
19    pub(crate) named_curve: NamedCurve,
20    pub(crate) public_key: Vec<u8>,
21    pub(crate) algorithm: SignatureHashAlgorithm,
22    pub(crate) signature: Vec<u8>,
23}
24
25impl HandshakeMessageServerKeyExchange {
26    /// The handshake type that identifies this message on the wire.
27    pub fn handshake_type(&self) -> HandshakeType {
28        HandshakeType::ServerKeyExchange
29    }
30
31    /// The encoded size of this message in bytes.
32    pub fn size(&self) -> usize {
33        if !self.identity_hint.is_empty() {
34            2 + self.identity_hint.len()
35        } else {
36            1 + 2 + 1 + self.public_key.len() + 2 + 2 + self.signature.len()
37        }
38    }
39
40    /// Encodes this message to `writer`.
41    ///
42    /// # Errors
43    ///
44    /// Fails on a write error, or if a field exceeds the length its wire format allows.
45    pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
46        if !self.identity_hint.is_empty() {
47            writer.write_u16::<BigEndian>(self.identity_hint.len() as u16)?;
48            writer.write_all(&self.identity_hint)?;
49            return Ok(writer.flush()?);
50        }
51
52        writer.write_u8(self.elliptic_curve_type as u8)?;
53        writer.write_u16::<BigEndian>(self.named_curve as u16)?;
54
55        writer.write_u8(self.public_key.len() as u8)?;
56        writer.write_all(&self.public_key)?;
57
58        writer.write_u8(self.algorithm.hash as u8)?;
59        writer.write_u8(self.algorithm.signature as u8)?;
60
61        writer.write_u16::<BigEndian>(self.signature.len() as u16)?;
62        writer.write_all(&self.signature)?;
63
64        Ok(writer.flush()?)
65    }
66
67    /// Decodes one of these messages from `reader`.
68    ///
69    /// # Errors
70    ///
71    /// Fails if `reader` is truncated or its contents are not a valid encoding.
72    pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self> {
73        let mut data = vec![];
74        reader.read_to_end(&mut data)?;
75
76        if data.len() < 2 {
77            return Err(Error::ErrBufferTooSmall);
78        }
79
80        // If parsed as PSK return early and only populate PSK Identity Hint
81        let psk_length = ((data[0] as u16) << 8) | data[1] as u16;
82        if data.len() == psk_length as usize + 2 {
83            return Ok(HandshakeMessageServerKeyExchange {
84                identity_hint: data[2..].to_vec(),
85
86                elliptic_curve_type: EllipticCurveType::Unsupported,
87                named_curve: NamedCurve::Unsupported,
88                public_key: vec![],
89                algorithm: SignatureHashAlgorithm {
90                    hash: HashAlgorithm::Unsupported,
91                    signature: SignatureAlgorithm::Unsupported,
92                },
93                signature: vec![],
94            });
95        }
96
97        let elliptic_curve_type = data[0].into();
98        if data[1..].len() < 2 {
99            return Err(Error::ErrBufferTooSmall);
100        }
101
102        let named_curve = (((data[1] as u16) << 8) | data[2] as u16).into();
103        if data.len() < 4 {
104            return Err(Error::ErrBufferTooSmall);
105        }
106
107        let public_key_length = data[3] as usize;
108        let mut offset = 4 + public_key_length;
109        if data.len() < offset {
110            return Err(Error::ErrBufferTooSmall);
111        }
112        let public_key = data[4..offset].to_vec();
113        if data.len() <= offset {
114            return Err(Error::ErrBufferTooSmall);
115        }
116
117        let hash_algorithm = data[offset].into();
118        offset += 1;
119        if data.len() <= offset {
120            return Err(Error::ErrBufferTooSmall);
121        }
122
123        let signature_algorithm = data[offset].into();
124        offset += 1;
125        if data.len() < offset + 2 {
126            return Err(Error::ErrBufferTooSmall);
127        }
128
129        let signature_length = (((data[offset] as u16) << 8) | data[offset + 1] as u16) as usize;
130        offset += 2;
131        if data.len() < offset + signature_length {
132            return Err(Error::ErrBufferTooSmall);
133        }
134        let signature = data[offset..offset + signature_length].to_vec();
135
136        Ok(HandshakeMessageServerKeyExchange {
137            identity_hint: vec![],
138
139            elliptic_curve_type,
140            named_curve,
141            public_key,
142            algorithm: SignatureHashAlgorithm {
143                hash: hash_algorithm,
144                signature: signature_algorithm,
145            },
146            signature,
147        })
148    }
149}