/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rustls-0.23.35/src/msgs/handshake.rs
Line | Count | Source |
1 | | use alloc::boxed::Box; |
2 | | use alloc::collections::BTreeSet; |
3 | | #[cfg(feature = "logging")] |
4 | | use alloc::string::String; |
5 | | use alloc::vec; |
6 | | use alloc::vec::Vec; |
7 | | use core::ops::{Deref, DerefMut}; |
8 | | use core::{fmt, iter}; |
9 | | |
10 | | use pki_types::{CertificateDer, DnsName}; |
11 | | |
12 | | #[cfg(feature = "tls12")] |
13 | | use crate::crypto::ActiveKeyExchange; |
14 | | use crate::crypto::SecureRandom; |
15 | | use crate::enums::{ |
16 | | CertificateCompressionAlgorithm, CertificateType, CipherSuite, EchClientHelloType, |
17 | | HandshakeType, ProtocolVersion, SignatureScheme, |
18 | | }; |
19 | | use crate::error::InvalidMessage; |
20 | | #[cfg(feature = "tls12")] |
21 | | use crate::ffdhe_groups::FfdheGroup; |
22 | | use crate::log::warn; |
23 | | use crate::msgs::base::{MaybeEmpty, NonEmpty, Payload, PayloadU8, PayloadU16, PayloadU24}; |
24 | | use crate::msgs::codec::{ |
25 | | self, Codec, LengthPrefixedBuffer, ListLength, Reader, TlsListElement, TlsListIter, |
26 | | }; |
27 | | use crate::msgs::enums::{ |
28 | | CertificateStatusType, ClientCertificateType, Compression, ECCurveType, ECPointFormat, |
29 | | EchVersion, ExtensionType, HpkeAead, HpkeKdf, HpkeKem, KeyUpdateRequest, NamedGroup, |
30 | | PskKeyExchangeMode, ServerNameType, |
31 | | }; |
32 | | use crate::rand; |
33 | | use crate::sync::Arc; |
34 | | use crate::verify::DigitallySignedStruct; |
35 | | use crate::x509::wrap_in_sequence; |
36 | | |
37 | | /// Create a newtype wrapper around a given type. |
38 | | /// |
39 | | /// This is used to create newtypes for the various TLS message types which is used to wrap |
40 | | /// the `PayloadU8` or `PayloadU16` types. This is typically used for types where we don't need |
41 | | /// anything other than access to the underlying bytes. |
42 | | macro_rules! wrapped_payload( |
43 | | ($(#[$comment:meta])* $vis:vis struct $name:ident, $inner:ident$(<$inner_ty:ty>)?,) => { |
44 | | $(#[$comment])* |
45 | | #[derive(Clone, Debug)] |
46 | | $vis struct $name($inner$(<$inner_ty>)?); |
47 | | |
48 | | impl From<Vec<u8>> for $name { |
49 | 0 | fn from(v: Vec<u8>) -> Self { |
50 | 0 | Self($inner::new(v)) |
51 | 0 | } Unexecuted instantiation: <rustls::msgs::handshake::ResponderId as core::convert::From<alloc::vec::Vec<u8>>>::from Unexecuted instantiation: <rustls::msgs::handshake::ProtocolName as core::convert::From<alloc::vec::Vec<u8>>>::from Unexecuted instantiation: <rustls::msgs::handshake::PresharedKeyBinder as core::convert::From<alloc::vec::Vec<u8>>>::from Unexecuted instantiation: <rustls::msgs::handshake::DistinguishedName as core::convert::From<alloc::vec::Vec<u8>>>::from |
52 | | } |
53 | | |
54 | | impl AsRef<[u8]> for $name { |
55 | 0 | fn as_ref(&self) -> &[u8] { |
56 | 0 | self.0.0.as_slice() |
57 | 0 | } Unexecuted instantiation: <rustls::msgs::handshake::ResponderId as core::convert::AsRef<[u8]>>::as_ref Unexecuted instantiation: <rustls::msgs::handshake::ProtocolName as core::convert::AsRef<[u8]>>::as_ref Unexecuted instantiation: <rustls::msgs::handshake::PresharedKeyBinder as core::convert::AsRef<[u8]>>::as_ref Unexecuted instantiation: <rustls::msgs::handshake::DistinguishedName as core::convert::AsRef<[u8]>>::as_ref |
58 | | } |
59 | | |
60 | | impl Codec<'_> for $name { |
61 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
62 | 0 | self.0.encode(bytes); |
63 | 0 | } Unexecuted instantiation: <rustls::msgs::handshake::ResponderId as rustls::msgs::codec::Codec>::encode Unexecuted instantiation: <rustls::msgs::handshake::ProtocolName as rustls::msgs::codec::Codec>::encode Unexecuted instantiation: <rustls::msgs::handshake::PresharedKeyBinder as rustls::msgs::codec::Codec>::encode Unexecuted instantiation: <rustls::msgs::handshake::DistinguishedName as rustls::msgs::codec::Codec>::encode |
64 | | |
65 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
66 | 0 | Ok(Self($inner::read(r)?)) |
67 | 0 | } Unexecuted instantiation: <rustls::msgs::handshake::ResponderId as rustls::msgs::codec::Codec>::read Unexecuted instantiation: <rustls::msgs::handshake::ProtocolName as rustls::msgs::codec::Codec>::read Unexecuted instantiation: <rustls::msgs::handshake::PresharedKeyBinder as rustls::msgs::codec::Codec>::read Unexecuted instantiation: <rustls::msgs::handshake::DistinguishedName as rustls::msgs::codec::Codec>::read |
68 | | } |
69 | | } |
70 | | ); |
71 | | |
72 | | #[derive(Clone, Copy, Eq, PartialEq)] |
73 | | pub(crate) struct Random(pub(crate) [u8; 32]); |
74 | | |
75 | | impl fmt::Debug for Random { |
76 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
77 | 0 | super::base::hex(f, &self.0) |
78 | 0 | } |
79 | | } |
80 | | |
81 | | static HELLO_RETRY_REQUEST_RANDOM: Random = Random([ |
82 | | 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, |
83 | | 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c, |
84 | | ]); |
85 | | |
86 | | static ZERO_RANDOM: Random = Random([0u8; 32]); |
87 | | |
88 | | impl Codec<'_> for Random { |
89 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
90 | 0 | bytes.extend_from_slice(&self.0); |
91 | 0 | } |
92 | | |
93 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
94 | 0 | let Some(bytes) = r.take(32) else { |
95 | 0 | return Err(InvalidMessage::MissingData("Random")); |
96 | | }; |
97 | | |
98 | 0 | let mut opaque = [0; 32]; |
99 | 0 | opaque.clone_from_slice(bytes); |
100 | 0 | Ok(Self(opaque)) |
101 | 0 | } |
102 | | } |
103 | | |
104 | | impl Random { |
105 | 0 | pub(crate) fn new(secure_random: &dyn SecureRandom) -> Result<Self, rand::GetRandomFailed> { |
106 | 0 | let mut data = [0u8; 32]; |
107 | 0 | secure_random.fill(&mut data)?; |
108 | 0 | Ok(Self(data)) |
109 | 0 | } |
110 | | } |
111 | | |
112 | | impl From<[u8; 32]> for Random { |
113 | | #[inline] |
114 | 0 | fn from(bytes: [u8; 32]) -> Self { |
115 | 0 | Self(bytes) |
116 | 0 | } |
117 | | } |
118 | | |
119 | | #[derive(Copy, Clone)] |
120 | | pub(crate) struct SessionId { |
121 | | len: usize, |
122 | | data: [u8; 32], |
123 | | } |
124 | | |
125 | | impl fmt::Debug for SessionId { |
126 | 0 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
127 | 0 | super::base::hex(f, &self.data[..self.len]) |
128 | 0 | } |
129 | | } |
130 | | |
131 | | impl PartialEq for SessionId { |
132 | 0 | fn eq(&self, other: &Self) -> bool { |
133 | 0 | if self.len != other.len { |
134 | 0 | return false; |
135 | 0 | } |
136 | | |
137 | 0 | let mut diff = 0u8; |
138 | 0 | for i in 0..self.len { |
139 | 0 | diff |= self.data[i] ^ other.data[i]; |
140 | 0 | } |
141 | | |
142 | 0 | diff == 0u8 |
143 | 0 | } |
144 | | } |
145 | | |
146 | | impl Codec<'_> for SessionId { |
147 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
148 | 0 | debug_assert!(self.len <= 32); |
149 | 0 | bytes.push(self.len as u8); |
150 | 0 | bytes.extend_from_slice(self.as_ref()); |
151 | 0 | } |
152 | | |
153 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
154 | 0 | let len = u8::read(r)? as usize; |
155 | 0 | if len > 32 { |
156 | 0 | return Err(InvalidMessage::TrailingData("SessionID")); |
157 | 0 | } |
158 | | |
159 | 0 | let Some(bytes) = r.take(len) else { |
160 | 0 | return Err(InvalidMessage::MissingData("SessionID")); |
161 | | }; |
162 | | |
163 | 0 | let mut out = [0u8; 32]; |
164 | 0 | out[..len].clone_from_slice(&bytes[..len]); |
165 | 0 | Ok(Self { data: out, len }) |
166 | 0 | } |
167 | | } |
168 | | |
169 | | impl SessionId { |
170 | 0 | pub(crate) fn random(secure_random: &dyn SecureRandom) -> Result<Self, rand::GetRandomFailed> { |
171 | 0 | let mut data = [0u8; 32]; |
172 | 0 | secure_random.fill(&mut data)?; |
173 | 0 | Ok(Self { data, len: 32 }) |
174 | 0 | } |
175 | | |
176 | 0 | pub(crate) fn empty() -> Self { |
177 | 0 | Self { |
178 | 0 | data: [0u8; 32], |
179 | 0 | len: 0, |
180 | 0 | } |
181 | 0 | } |
182 | | |
183 | | #[cfg(feature = "tls12")] |
184 | 0 | pub(crate) fn is_empty(&self) -> bool { |
185 | 0 | self.len == 0 |
186 | 0 | } |
187 | | } |
188 | | |
189 | | impl AsRef<[u8]> for SessionId { |
190 | 0 | fn as_ref(&self) -> &[u8] { |
191 | 0 | &self.data[..self.len] |
192 | 0 | } |
193 | | } |
194 | | |
195 | | #[derive(Clone, Debug, PartialEq)] |
196 | | pub struct UnknownExtension { |
197 | | pub(crate) typ: ExtensionType, |
198 | | pub(crate) payload: Payload<'static>, |
199 | | } |
200 | | |
201 | | impl UnknownExtension { |
202 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
203 | 0 | self.payload.encode(bytes); |
204 | 0 | } |
205 | | |
206 | 0 | fn read(typ: ExtensionType, r: &mut Reader<'_>) -> Self { |
207 | 0 | let payload = Payload::read(r).into_owned(); |
208 | 0 | Self { typ, payload } |
209 | 0 | } |
210 | | } |
211 | | |
212 | | #[derive(Clone, Copy, Debug)] |
213 | | pub(crate) struct SupportedEcPointFormats { |
214 | | pub(crate) uncompressed: bool, |
215 | | } |
216 | | |
217 | | impl Codec<'_> for SupportedEcPointFormats { |
218 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
219 | 0 | let inner = LengthPrefixedBuffer::new(ECPointFormat::SIZE_LEN, bytes); |
220 | | |
221 | 0 | if self.uncompressed { |
222 | 0 | ECPointFormat::Uncompressed.encode(inner.buf); |
223 | 0 | } |
224 | 0 | } |
225 | | |
226 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
227 | 0 | let mut uncompressed = false; |
228 | | |
229 | 0 | for pf in TlsListIter::<ECPointFormat>::new(r)? { |
230 | 0 | if let ECPointFormat::Uncompressed = pf? { |
231 | 0 | uncompressed = true; |
232 | 0 | } |
233 | | } |
234 | | |
235 | 0 | Ok(Self { uncompressed }) |
236 | 0 | } |
237 | | } |
238 | | |
239 | | impl Default for SupportedEcPointFormats { |
240 | 0 | fn default() -> Self { |
241 | 0 | Self { uncompressed: true } |
242 | 0 | } |
243 | | } |
244 | | |
245 | | /// RFC8422: `ECPointFormat ec_point_format_list<1..2^8-1>` |
246 | | impl TlsListElement for ECPointFormat { |
247 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
248 | | empty_error: InvalidMessage::IllegalEmptyList("ECPointFormats"), |
249 | | }; |
250 | | } |
251 | | |
252 | | /// RFC8422: `NamedCurve named_curve_list<2..2^16-1>` |
253 | | impl TlsListElement for NamedGroup { |
254 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
255 | | empty_error: InvalidMessage::IllegalEmptyList("NamedGroups"), |
256 | | }; |
257 | | } |
258 | | |
259 | | /// RFC8446: `SignatureScheme supported_signature_algorithms<2..2^16-2>;` |
260 | | impl TlsListElement for SignatureScheme { |
261 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
262 | | empty_error: InvalidMessage::NoSignatureSchemes, |
263 | | }; |
264 | | } |
265 | | |
266 | | #[derive(Clone, Debug)] |
267 | | pub(crate) enum ServerNamePayload<'a> { |
268 | | /// A successfully decoded value: |
269 | | SingleDnsName(DnsName<'a>), |
270 | | |
271 | | /// A DNS name which was actually an IP address |
272 | | IpAddress, |
273 | | |
274 | | /// A successfully decoded, but syntactically-invalid value. |
275 | | Invalid, |
276 | | } |
277 | | |
278 | | impl ServerNamePayload<'_> { |
279 | 0 | fn into_owned(self) -> ServerNamePayload<'static> { |
280 | 0 | match self { |
281 | 0 | Self::SingleDnsName(d) => ServerNamePayload::SingleDnsName(d.to_owned()), |
282 | 0 | Self::IpAddress => ServerNamePayload::IpAddress, |
283 | 0 | Self::Invalid => ServerNamePayload::Invalid, |
284 | | } |
285 | 0 | } |
286 | | |
287 | | /// RFC6066: `ServerName server_name_list<1..2^16-1>` |
288 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
289 | | empty_error: InvalidMessage::IllegalEmptyList("ServerNames"), |
290 | | }; |
291 | | } |
292 | | |
293 | | /// Simplified encoding/decoding for a `ServerName` extension payload to/from `DnsName` |
294 | | /// |
295 | | /// This is possible because: |
296 | | /// |
297 | | /// - the spec (RFC6066) disallows multiple names for a given name type |
298 | | /// - name types other than ServerNameType::HostName are not defined, and they and |
299 | | /// any data that follows them cannot be skipped over. |
300 | | impl<'a> Codec<'a> for ServerNamePayload<'a> { |
301 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
302 | 0 | let server_name_list = LengthPrefixedBuffer::new(Self::SIZE_LEN, bytes); |
303 | | |
304 | 0 | let ServerNamePayload::SingleDnsName(dns_name) = self else { |
305 | 0 | return; |
306 | | }; |
307 | | |
308 | 0 | ServerNameType::HostName.encode(server_name_list.buf); |
309 | 0 | let name_slice = dns_name.as_ref().as_bytes(); |
310 | 0 | (name_slice.len() as u16).encode(server_name_list.buf); |
311 | 0 | server_name_list |
312 | 0 | .buf |
313 | 0 | .extend_from_slice(name_slice); |
314 | 0 | } |
315 | | |
316 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
317 | 0 | let mut found = None; |
318 | | |
319 | 0 | let len = Self::SIZE_LEN.read(r)?; |
320 | 0 | let mut sub = r.sub(len)?; |
321 | | |
322 | 0 | while sub.any_left() { |
323 | 0 | let typ = ServerNameType::read(&mut sub)?; |
324 | | |
325 | 0 | let payload = match typ { |
326 | 0 | ServerNameType::HostName => HostNamePayload::read(&mut sub)?, |
327 | | _ => { |
328 | | // Consume remainder of extension bytes. Since the length of the item |
329 | | // is an unknown encoding, we cannot continue. |
330 | 0 | sub.rest(); |
331 | 0 | break; |
332 | | } |
333 | | }; |
334 | | |
335 | | // "The ServerNameList MUST NOT contain more than one name of |
336 | | // the same name_type." - RFC6066 |
337 | 0 | if found.is_some() { |
338 | 0 | warn!("Illegal SNI extension: duplicate host_name received"); |
339 | 0 | return Err(InvalidMessage::InvalidServerName); |
340 | 0 | } |
341 | | |
342 | 0 | found = match payload { |
343 | 0 | HostNamePayload::HostName(dns_name) => { |
344 | 0 | Some(Self::SingleDnsName(dns_name.to_owned())) |
345 | | } |
346 | | |
347 | 0 | HostNamePayload::IpAddress(_invalid) => { |
348 | 0 | warn!( |
349 | | "Illegal SNI extension: ignoring IP address presented as hostname ({_invalid:?})" |
350 | | ); |
351 | 0 | Some(Self::IpAddress) |
352 | | } |
353 | | |
354 | 0 | HostNamePayload::Invalid(_invalid) => { |
355 | 0 | warn!( |
356 | | "Illegal SNI hostname received {:?}", |
357 | | String::from_utf8_lossy(&_invalid.0) |
358 | | ); |
359 | 0 | Some(Self::Invalid) |
360 | | } |
361 | | }; |
362 | | } |
363 | | |
364 | 0 | Ok(found.unwrap_or(Self::Invalid)) |
365 | 0 | } |
366 | | } |
367 | | |
368 | | impl<'a> From<&DnsName<'a>> for ServerNamePayload<'static> { |
369 | 0 | fn from(value: &DnsName<'a>) -> Self { |
370 | 0 | Self::SingleDnsName(trim_hostname_trailing_dot_for_sni(value)) |
371 | 0 | } |
372 | | } |
373 | | |
374 | | #[derive(Clone, Debug)] |
375 | | pub(crate) enum HostNamePayload { |
376 | | HostName(DnsName<'static>), |
377 | | IpAddress(PayloadU16<NonEmpty>), |
378 | | Invalid(PayloadU16<NonEmpty>), |
379 | | } |
380 | | |
381 | | impl HostNamePayload { |
382 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
383 | | use pki_types::ServerName; |
384 | 0 | let raw = PayloadU16::<NonEmpty>::read(r)?; |
385 | | |
386 | 0 | match ServerName::try_from(raw.0.as_slice()) { |
387 | 0 | Ok(ServerName::DnsName(d)) => Ok(Self::HostName(d.to_owned())), |
388 | 0 | Ok(ServerName::IpAddress(_)) => Ok(Self::IpAddress(raw)), |
389 | 0 | Ok(_) | Err(_) => Ok(Self::Invalid(raw)), |
390 | | } |
391 | 0 | } |
392 | | } |
393 | | |
394 | | wrapped_payload!( |
395 | | /// RFC7301: `opaque ProtocolName<1..2^8-1>;` |
396 | | pub(crate) struct ProtocolName, PayloadU8<NonEmpty>, |
397 | | ); |
398 | | |
399 | | impl PartialEq for ProtocolName { |
400 | 0 | fn eq(&self, other: &Self) -> bool { |
401 | 0 | self.0 == other.0 |
402 | 0 | } |
403 | | } |
404 | | |
405 | | impl Deref for ProtocolName { |
406 | | type Target = [u8]; |
407 | | |
408 | 0 | fn deref(&self) -> &Self::Target { |
409 | 0 | self.as_ref() |
410 | 0 | } |
411 | | } |
412 | | |
413 | | /// RFC7301: `ProtocolName protocol_name_list<2..2^16-1>` |
414 | | impl TlsListElement for ProtocolName { |
415 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
416 | | empty_error: InvalidMessage::IllegalEmptyList("ProtocolNames"), |
417 | | }; |
418 | | } |
419 | | |
420 | | /// RFC7301 encodes a single protocol name as `Vec<ProtocolName>` |
421 | | #[derive(Clone, Debug)] |
422 | | pub(crate) struct SingleProtocolName(ProtocolName); |
423 | | |
424 | | impl SingleProtocolName { |
425 | 0 | pub(crate) fn new(single: ProtocolName) -> Self { |
426 | 0 | Self(single) |
427 | 0 | } |
428 | | |
429 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
430 | | empty_error: InvalidMessage::IllegalEmptyList("ProtocolNames"), |
431 | | }; |
432 | | } |
433 | | |
434 | | impl Codec<'_> for SingleProtocolName { |
435 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
436 | 0 | let body = LengthPrefixedBuffer::new(Self::SIZE_LEN, bytes); |
437 | 0 | self.0.encode(body.buf); |
438 | 0 | } |
439 | | |
440 | 0 | fn read(reader: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
441 | 0 | let len = Self::SIZE_LEN.read(reader)?; |
442 | 0 | let mut sub = reader.sub(len)?; |
443 | | |
444 | 0 | let item = ProtocolName::read(&mut sub)?; |
445 | | |
446 | 0 | if sub.any_left() { |
447 | 0 | Err(InvalidMessage::TrailingData("SingleProtocolName")) |
448 | | } else { |
449 | 0 | Ok(Self(item)) |
450 | | } |
451 | 0 | } |
452 | | } |
453 | | |
454 | | impl AsRef<ProtocolName> for SingleProtocolName { |
455 | 0 | fn as_ref(&self) -> &ProtocolName { |
456 | 0 | &self.0 |
457 | 0 | } |
458 | | } |
459 | | |
460 | | // --- TLS 1.3 Key shares --- |
461 | | #[derive(Clone, Debug)] |
462 | | pub(crate) struct KeyShareEntry { |
463 | | pub(crate) group: NamedGroup, |
464 | | /// RFC8446: `opaque key_exchange<1..2^16-1>;` |
465 | | pub(crate) payload: PayloadU16<NonEmpty>, |
466 | | } |
467 | | |
468 | | impl KeyShareEntry { |
469 | 0 | pub(crate) fn new(group: NamedGroup, payload: impl Into<Vec<u8>>) -> Self { |
470 | 0 | Self { |
471 | 0 | group, |
472 | 0 | payload: PayloadU16::new(payload.into()), |
473 | 0 | } |
474 | 0 | } Unexecuted instantiation: <rustls::msgs::handshake::KeyShareEntry>::new::<alloc::vec::Vec<u8>> Unexecuted instantiation: <rustls::msgs::handshake::KeyShareEntry>::new::<&[u8]> |
475 | | } |
476 | | |
477 | | impl Codec<'_> for KeyShareEntry { |
478 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
479 | 0 | self.group.encode(bytes); |
480 | 0 | self.payload.encode(bytes); |
481 | 0 | } |
482 | | |
483 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
484 | 0 | let group = NamedGroup::read(r)?; |
485 | 0 | let payload = PayloadU16::read(r)?; |
486 | | |
487 | 0 | Ok(Self { group, payload }) |
488 | 0 | } |
489 | | } |
490 | | |
491 | | // --- TLS 1.3 PresharedKey offers --- |
492 | | #[derive(Clone, Debug)] |
493 | | pub(crate) struct PresharedKeyIdentity { |
494 | | /// RFC8446: `opaque identity<1..2^16-1>;` |
495 | | pub(crate) identity: PayloadU16<NonEmpty>, |
496 | | pub(crate) obfuscated_ticket_age: u32, |
497 | | } |
498 | | |
499 | | impl PresharedKeyIdentity { |
500 | 0 | pub(crate) fn new(id: Vec<u8>, age: u32) -> Self { |
501 | 0 | Self { |
502 | 0 | identity: PayloadU16::new(id), |
503 | 0 | obfuscated_ticket_age: age, |
504 | 0 | } |
505 | 0 | } |
506 | | } |
507 | | |
508 | | impl Codec<'_> for PresharedKeyIdentity { |
509 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
510 | 0 | self.identity.encode(bytes); |
511 | 0 | self.obfuscated_ticket_age.encode(bytes); |
512 | 0 | } |
513 | | |
514 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
515 | | Ok(Self { |
516 | 0 | identity: PayloadU16::read(r)?, |
517 | 0 | obfuscated_ticket_age: u32::read(r)?, |
518 | | }) |
519 | 0 | } |
520 | | } |
521 | | |
522 | | /// RFC8446: `PskIdentity identities<7..2^16-1>;` |
523 | | impl TlsListElement for PresharedKeyIdentity { |
524 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
525 | | empty_error: InvalidMessage::IllegalEmptyList("PskIdentities"), |
526 | | }; |
527 | | } |
528 | | |
529 | | wrapped_payload!( |
530 | | /// RFC8446: `opaque PskBinderEntry<32..255>;` |
531 | | pub(crate) struct PresharedKeyBinder, PayloadU8<NonEmpty>, |
532 | | ); |
533 | | |
534 | | /// RFC8446: `PskBinderEntry binders<33..2^16-1>;` |
535 | | impl TlsListElement for PresharedKeyBinder { |
536 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
537 | | empty_error: InvalidMessage::IllegalEmptyList("PskBinders"), |
538 | | }; |
539 | | } |
540 | | |
541 | | #[derive(Clone, Debug)] |
542 | | pub(crate) struct PresharedKeyOffer { |
543 | | pub(crate) identities: Vec<PresharedKeyIdentity>, |
544 | | pub(crate) binders: Vec<PresharedKeyBinder>, |
545 | | } |
546 | | |
547 | | impl PresharedKeyOffer { |
548 | | /// Make a new one with one entry. |
549 | 0 | pub(crate) fn new(id: PresharedKeyIdentity, binder: Vec<u8>) -> Self { |
550 | 0 | Self { |
551 | 0 | identities: vec![id], |
552 | 0 | binders: vec![PresharedKeyBinder::from(binder)], |
553 | 0 | } |
554 | 0 | } |
555 | | } |
556 | | |
557 | | impl Codec<'_> for PresharedKeyOffer { |
558 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
559 | 0 | self.identities.encode(bytes); |
560 | 0 | self.binders.encode(bytes); |
561 | 0 | } |
562 | | |
563 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
564 | | Ok(Self { |
565 | 0 | identities: Vec::read(r)?, |
566 | 0 | binders: Vec::read(r)?, |
567 | | }) |
568 | 0 | } |
569 | | } |
570 | | |
571 | | // --- RFC6066 certificate status request --- |
572 | | wrapped_payload!(pub(crate) struct ResponderId, PayloadU16,); |
573 | | |
574 | | /// RFC6066: `ResponderID responder_id_list<0..2^16-1>;` |
575 | | impl TlsListElement for ResponderId { |
576 | | const SIZE_LEN: ListLength = ListLength::U16; |
577 | | } |
578 | | |
579 | | #[derive(Clone, Debug)] |
580 | | pub(crate) struct OcspCertificateStatusRequest { |
581 | | pub(crate) responder_ids: Vec<ResponderId>, |
582 | | pub(crate) extensions: PayloadU16, |
583 | | } |
584 | | |
585 | | impl Codec<'_> for OcspCertificateStatusRequest { |
586 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
587 | 0 | CertificateStatusType::OCSP.encode(bytes); |
588 | 0 | self.responder_ids.encode(bytes); |
589 | 0 | self.extensions.encode(bytes); |
590 | 0 | } |
591 | | |
592 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
593 | | Ok(Self { |
594 | 0 | responder_ids: Vec::read(r)?, |
595 | 0 | extensions: PayloadU16::read(r)?, |
596 | | }) |
597 | 0 | } |
598 | | } |
599 | | |
600 | | #[derive(Clone, Debug)] |
601 | | pub(crate) enum CertificateStatusRequest { |
602 | | Ocsp(OcspCertificateStatusRequest), |
603 | | Unknown((CertificateStatusType, Payload<'static>)), |
604 | | } |
605 | | |
606 | | impl Codec<'_> for CertificateStatusRequest { |
607 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
608 | 0 | match self { |
609 | 0 | Self::Ocsp(r) => r.encode(bytes), |
610 | 0 | Self::Unknown((typ, payload)) => { |
611 | 0 | typ.encode(bytes); |
612 | 0 | payload.encode(bytes); |
613 | 0 | } |
614 | | } |
615 | 0 | } |
616 | | |
617 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
618 | 0 | let typ = CertificateStatusType::read(r)?; |
619 | | |
620 | 0 | match typ { |
621 | | CertificateStatusType::OCSP => { |
622 | 0 | let ocsp_req = OcspCertificateStatusRequest::read(r)?; |
623 | 0 | Ok(Self::Ocsp(ocsp_req)) |
624 | | } |
625 | | _ => { |
626 | 0 | let data = Payload::read(r).into_owned(); |
627 | 0 | Ok(Self::Unknown((typ, data))) |
628 | | } |
629 | | } |
630 | 0 | } |
631 | | } |
632 | | |
633 | | impl CertificateStatusRequest { |
634 | 0 | pub(crate) fn build_ocsp() -> Self { |
635 | 0 | let ocsp = OcspCertificateStatusRequest { |
636 | 0 | responder_ids: Vec::new(), |
637 | 0 | extensions: PayloadU16::empty(), |
638 | 0 | }; |
639 | 0 | Self::Ocsp(ocsp) |
640 | 0 | } |
641 | | } |
642 | | |
643 | | // --- |
644 | | |
645 | | /// RFC8446: `PskKeyExchangeMode ke_modes<1..255>;` |
646 | | #[derive(Clone, Copy, Debug, Default)] |
647 | | pub(crate) struct PskKeyExchangeModes { |
648 | | pub(crate) psk_dhe: bool, |
649 | | pub(crate) psk: bool, |
650 | | } |
651 | | |
652 | | impl Codec<'_> for PskKeyExchangeModes { |
653 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
654 | 0 | let inner = LengthPrefixedBuffer::new(PskKeyExchangeMode::SIZE_LEN, bytes); |
655 | 0 | if self.psk_dhe { |
656 | 0 | PskKeyExchangeMode::PSK_DHE_KE.encode(inner.buf); |
657 | 0 | } |
658 | 0 | if self.psk { |
659 | 0 | PskKeyExchangeMode::PSK_KE.encode(inner.buf); |
660 | 0 | } |
661 | 0 | } |
662 | | |
663 | 0 | fn read(reader: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
664 | 0 | let mut psk_dhe = false; |
665 | 0 | let mut psk = false; |
666 | | |
667 | 0 | for ke in TlsListIter::<PskKeyExchangeMode>::new(reader)? { |
668 | 0 | match ke? { |
669 | 0 | PskKeyExchangeMode::PSK_DHE_KE => psk_dhe = true, |
670 | 0 | PskKeyExchangeMode::PSK_KE => psk = true, |
671 | 0 | _ => continue, |
672 | | }; |
673 | | } |
674 | | |
675 | 0 | Ok(Self { psk_dhe, psk }) |
676 | 0 | } |
677 | | } |
678 | | |
679 | | impl TlsListElement for PskKeyExchangeMode { |
680 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
681 | | empty_error: InvalidMessage::IllegalEmptyList("PskKeyExchangeModes"), |
682 | | }; |
683 | | } |
684 | | |
685 | | /// RFC8446: `KeyShareEntry client_shares<0..2^16-1>;` |
686 | | impl TlsListElement for KeyShareEntry { |
687 | | const SIZE_LEN: ListLength = ListLength::U16; |
688 | | } |
689 | | |
690 | | /// The body of the `SupportedVersions` extension when it appears in a |
691 | | /// `ClientHello` |
692 | | /// |
693 | | /// This is documented as a preference-order vector, but we (as a server) |
694 | | /// ignore the preference of the client. |
695 | | /// |
696 | | /// RFC8446: `ProtocolVersion versions<2..254>;` |
697 | | #[derive(Clone, Copy, Debug, Default)] |
698 | | pub(crate) struct SupportedProtocolVersions { |
699 | | pub(crate) tls13: bool, |
700 | | pub(crate) tls12: bool, |
701 | | } |
702 | | |
703 | | impl SupportedProtocolVersions { |
704 | | /// Return true if `filter` returns true for any enabled version. |
705 | 0 | pub(crate) fn any(&self, filter: impl Fn(ProtocolVersion) -> bool) -> bool { |
706 | 0 | if self.tls13 && filter(ProtocolVersion::TLSv1_3) { |
707 | 0 | return true; |
708 | 0 | } |
709 | 0 | if self.tls12 && filter(ProtocolVersion::TLSv1_2) { |
710 | 0 | return true; |
711 | 0 | } |
712 | 0 | false |
713 | 0 | } Unexecuted instantiation: <rustls::msgs::handshake::SupportedProtocolVersions>::any::<rustls::client::hs::emit_client_hello_for_retry::{closure#0}::{closure#0}>Unexecuted instantiation: <rustls::msgs::handshake::SupportedProtocolVersions>::any::<rustls::client::hs::emit_client_hello_for_retry::{closure#11}> |
714 | | |
715 | | const LIST_LENGTH: ListLength = ListLength::NonZeroU8 { |
716 | | empty_error: InvalidMessage::IllegalEmptyList("ProtocolVersions"), |
717 | | }; |
718 | | } |
719 | | |
720 | | impl Codec<'_> for SupportedProtocolVersions { |
721 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
722 | 0 | let inner = LengthPrefixedBuffer::new(Self::LIST_LENGTH, bytes); |
723 | 0 | if self.tls13 { |
724 | 0 | ProtocolVersion::TLSv1_3.encode(inner.buf); |
725 | 0 | } |
726 | 0 | if self.tls12 { |
727 | 0 | ProtocolVersion::TLSv1_2.encode(inner.buf); |
728 | 0 | } |
729 | 0 | } |
730 | | |
731 | 0 | fn read(reader: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
732 | 0 | let mut tls12 = false; |
733 | 0 | let mut tls13 = false; |
734 | | |
735 | 0 | for pv in TlsListIter::<ProtocolVersion>::new(reader)? { |
736 | 0 | match pv? { |
737 | 0 | ProtocolVersion::TLSv1_3 => tls13 = true, |
738 | 0 | ProtocolVersion::TLSv1_2 => tls12 = true, |
739 | 0 | _ => continue, |
740 | | }; |
741 | | } |
742 | | |
743 | 0 | Ok(Self { tls13, tls12 }) |
744 | 0 | } |
745 | | } |
746 | | |
747 | | impl TlsListElement for ProtocolVersion { |
748 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
749 | | empty_error: InvalidMessage::IllegalEmptyList("ProtocolVersions"), |
750 | | }; |
751 | | } |
752 | | |
753 | | /// RFC7250: `CertificateType client_certificate_types<1..2^8-1>;` |
754 | | /// |
755 | | /// Ditto `CertificateType server_certificate_types<1..2^8-1>;` |
756 | | impl TlsListElement for CertificateType { |
757 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
758 | | empty_error: InvalidMessage::IllegalEmptyList("CertificateTypes"), |
759 | | }; |
760 | | } |
761 | | |
762 | | /// RFC8879: `CertificateCompressionAlgorithm algorithms<2..2^8-2>;` |
763 | | impl TlsListElement for CertificateCompressionAlgorithm { |
764 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
765 | | empty_error: InvalidMessage::IllegalEmptyList("CertificateCompressionAlgorithms"), |
766 | | }; |
767 | | } |
768 | | |
769 | | /// A precursor to `ClientExtensions`, allowing customisation. |
770 | | /// |
771 | | /// This is smaller than `ClientExtensions`, as it only contains the extensions |
772 | | /// we need to vary between different protocols (eg, TCP-TLS versus QUIC). |
773 | | #[derive(Clone, Default)] |
774 | | pub(crate) struct ClientExtensionsInput<'a> { |
775 | | /// QUIC transport parameters |
776 | | pub(crate) transport_parameters: Option<TransportParameters<'a>>, |
777 | | |
778 | | /// ALPN protocols |
779 | | pub(crate) protocols: Option<Vec<ProtocolName>>, |
780 | | } |
781 | | |
782 | | impl ClientExtensionsInput<'_> { |
783 | 0 | pub(crate) fn from_alpn(alpn_protocols: Vec<Vec<u8>>) -> ClientExtensionsInput<'static> { |
784 | 0 | let protocols = match alpn_protocols.is_empty() { |
785 | 0 | true => None, |
786 | 0 | false => Some( |
787 | 0 | alpn_protocols |
788 | 0 | .into_iter() |
789 | 0 | .map(ProtocolName::from) |
790 | 0 | .collect::<Vec<_>>(), |
791 | 0 | ), |
792 | | }; |
793 | | |
794 | 0 | ClientExtensionsInput { |
795 | 0 | transport_parameters: None, |
796 | 0 | protocols, |
797 | 0 | } |
798 | 0 | } |
799 | | |
800 | 0 | pub(crate) fn into_owned(self) -> ClientExtensionsInput<'static> { |
801 | 0 | let Self { |
802 | 0 | transport_parameters, |
803 | 0 | protocols, |
804 | 0 | } = self; |
805 | | ClientExtensionsInput { |
806 | 0 | transport_parameters: transport_parameters.map(|x| x.into_owned()), |
807 | 0 | protocols, |
808 | | } |
809 | 0 | } |
810 | | } |
811 | | |
812 | | #[derive(Clone)] |
813 | | pub(crate) enum TransportParameters<'a> { |
814 | | /// QUIC transport parameters (RFC9001 prior to draft 33) |
815 | | QuicDraft(Payload<'a>), |
816 | | |
817 | | /// QUIC transport parameters (RFC9001) |
818 | | Quic(Payload<'a>), |
819 | | } |
820 | | |
821 | | impl TransportParameters<'_> { |
822 | 0 | pub(crate) fn into_owned(self) -> TransportParameters<'static> { |
823 | 0 | match self { |
824 | 0 | Self::QuicDraft(v) => TransportParameters::QuicDraft(v.into_owned()), |
825 | 0 | Self::Quic(v) => TransportParameters::Quic(v.into_owned()), |
826 | | } |
827 | 0 | } |
828 | | } |
829 | | |
830 | | extension_struct! { |
831 | | /// A representation of extensions present in a `ClientHello` message |
832 | | /// |
833 | | /// All extensions are optional (by definition) so are represented with `Option<T>`. |
834 | | /// |
835 | | /// Some extensions have an empty value and are represented with Option<()>. |
836 | | /// |
837 | | /// Unknown extensions are dropped during parsing. |
838 | | pub(crate) struct ClientExtensions<'a> { |
839 | | /// Requested server name indication (RFC6066) |
840 | | ExtensionType::ServerName => |
841 | | pub(crate) server_name: Option<ServerNamePayload<'a>>, |
842 | | |
843 | | /// Certificate status is requested (RFC6066) |
844 | | ExtensionType::StatusRequest => |
845 | | pub(crate) certificate_status_request: Option<CertificateStatusRequest>, |
846 | | |
847 | | /// Supported groups (RFC4492/RFC8446) |
848 | | ExtensionType::EllipticCurves => |
849 | | pub(crate) named_groups: Option<Vec<NamedGroup>>, |
850 | | |
851 | | /// Supported EC point formats (RFC4492) |
852 | | ExtensionType::ECPointFormats => |
853 | | pub(crate) ec_point_formats: Option<SupportedEcPointFormats>, |
854 | | |
855 | | /// Supported signature schemes (RFC5246/RFC8446) |
856 | | ExtensionType::SignatureAlgorithms => |
857 | | pub(crate) signature_schemes: Option<Vec<SignatureScheme>>, |
858 | | |
859 | | /// Offered ALPN protocols (RFC6066) |
860 | | ExtensionType::ALProtocolNegotiation => |
861 | | pub(crate) protocols: Option<Vec<ProtocolName>>, |
862 | | |
863 | | /// Available client certificate types (RFC7250) |
864 | | ExtensionType::ClientCertificateType => |
865 | | pub(crate) client_certificate_types: Option<Vec<CertificateType>>, |
866 | | |
867 | | /// Acceptable server certificate types (RFC7250) |
868 | | ExtensionType::ServerCertificateType => |
869 | | pub(crate) server_certificate_types: Option<Vec<CertificateType>>, |
870 | | |
871 | | /// Extended master secret is requested (RFC7627) |
872 | | ExtensionType::ExtendedMasterSecret => |
873 | | pub(crate) extended_master_secret_request: Option<()>, |
874 | | |
875 | | /// Offered certificate compression methods (RFC8879) |
876 | | ExtensionType::CompressCertificate => |
877 | | pub(crate) certificate_compression_algorithms: Option<Vec<CertificateCompressionAlgorithm>>, |
878 | | |
879 | | /// Session ticket offer or request (RFC5077/RFC8446) |
880 | | ExtensionType::SessionTicket => |
881 | | pub(crate) session_ticket: Option<ClientSessionTicket>, |
882 | | |
883 | | /// Offered preshared keys (RFC8446) |
884 | | ExtensionType::PreSharedKey => |
885 | | pub(crate) preshared_key_offer: Option<PresharedKeyOffer>, |
886 | | |
887 | | /// Early data is requested (RFC8446) |
888 | | ExtensionType::EarlyData => |
889 | | pub(crate) early_data_request: Option<()>, |
890 | | |
891 | | /// Supported TLS versions (RFC8446) |
892 | | ExtensionType::SupportedVersions => |
893 | | pub(crate) supported_versions: Option<SupportedProtocolVersions>, |
894 | | |
895 | | /// Stateless HelloRetryRequest cookie (RFC8446) |
896 | | ExtensionType::Cookie => |
897 | | pub(crate) cookie: Option<PayloadU16<NonEmpty>>, |
898 | | |
899 | | /// Offered preshared key modes (RFC8446) |
900 | | ExtensionType::PSKKeyExchangeModes => |
901 | | pub(crate) preshared_key_modes: Option<PskKeyExchangeModes>, |
902 | | |
903 | | /// Certificate authority names (RFC8446) |
904 | | ExtensionType::CertificateAuthorities => |
905 | | pub(crate) certificate_authority_names: Option<Vec<DistinguishedName>>, |
906 | | |
907 | | /// Offered key exchange shares (RFC8446) |
908 | | ExtensionType::KeyShare => |
909 | | pub(crate) key_shares: Option<Vec<KeyShareEntry>>, |
910 | | |
911 | | /// QUIC transport parameters (RFC9001) |
912 | | ExtensionType::TransportParameters => |
913 | | pub(crate) transport_parameters: Option<Payload<'a>>, |
914 | | |
915 | | /// Secure renegotiation (RFC5746) |
916 | | ExtensionType::RenegotiationInfo => |
917 | | pub(crate) renegotiation_info: Option<PayloadU8>, |
918 | | |
919 | | /// QUIC transport parameters (RFC9001 prior to draft 33) |
920 | | ExtensionType::TransportParametersDraft => |
921 | | pub(crate) transport_parameters_draft: Option<Payload<'a>>, |
922 | | |
923 | | /// Encrypted inner client hello (draft-ietf-tls-esni) |
924 | | ExtensionType::EncryptedClientHello => |
925 | | pub(crate) encrypted_client_hello: Option<EncryptedClientHello>, |
926 | | |
927 | | /// Encrypted client hello outer extensions (draft-ietf-tls-esni) |
928 | | ExtensionType::EncryptedClientHelloOuterExtensions => |
929 | | pub(crate) encrypted_client_hello_outer: Option<Vec<ExtensionType>>, |
930 | | } + { |
931 | | /// Order randomization seed. |
932 | | pub(crate) order_seed: u16, |
933 | | |
934 | | /// Extensions that must appear contiguously. |
935 | | pub(crate) contiguous_extensions: Vec<ExtensionType>, |
936 | | } |
937 | | } |
938 | | |
939 | | impl ClientExtensions<'_> { |
940 | 0 | pub(crate) fn into_owned(self) -> ClientExtensions<'static> { |
941 | 0 | let Self { |
942 | 0 | server_name, |
943 | 0 | certificate_status_request, |
944 | 0 | named_groups, |
945 | 0 | ec_point_formats, |
946 | 0 | signature_schemes, |
947 | 0 | protocols, |
948 | 0 | client_certificate_types, |
949 | 0 | server_certificate_types, |
950 | 0 | extended_master_secret_request, |
951 | 0 | certificate_compression_algorithms, |
952 | 0 | session_ticket, |
953 | 0 | preshared_key_offer, |
954 | 0 | early_data_request, |
955 | 0 | supported_versions, |
956 | 0 | cookie, |
957 | 0 | preshared_key_modes, |
958 | 0 | certificate_authority_names, |
959 | 0 | key_shares, |
960 | 0 | transport_parameters, |
961 | 0 | renegotiation_info, |
962 | 0 | transport_parameters_draft, |
963 | 0 | encrypted_client_hello, |
964 | 0 | encrypted_client_hello_outer, |
965 | 0 | order_seed, |
966 | 0 | contiguous_extensions, |
967 | 0 | } = self; |
968 | | ClientExtensions { |
969 | 0 | server_name: server_name.map(|x| x.into_owned()), |
970 | 0 | certificate_status_request, |
971 | 0 | named_groups, |
972 | 0 | ec_point_formats, |
973 | 0 | signature_schemes, |
974 | 0 | protocols, |
975 | 0 | client_certificate_types, |
976 | 0 | server_certificate_types, |
977 | 0 | extended_master_secret_request, |
978 | 0 | certificate_compression_algorithms, |
979 | 0 | session_ticket, |
980 | 0 | preshared_key_offer, |
981 | 0 | early_data_request, |
982 | 0 | supported_versions, |
983 | 0 | cookie, |
984 | 0 | preshared_key_modes, |
985 | 0 | certificate_authority_names, |
986 | 0 | key_shares, |
987 | 0 | transport_parameters: transport_parameters.map(|x| x.into_owned()), |
988 | 0 | renegotiation_info, |
989 | 0 | transport_parameters_draft: transport_parameters_draft.map(|x| x.into_owned()), |
990 | 0 | encrypted_client_hello, |
991 | 0 | encrypted_client_hello_outer, |
992 | 0 | order_seed, |
993 | 0 | contiguous_extensions, |
994 | | } |
995 | 0 | } |
996 | | |
997 | 0 | pub(crate) fn used_extensions_in_encoding_order(&self) -> Vec<ExtensionType> { |
998 | 0 | let mut exts = self.order_insensitive_extensions_in_random_order(); |
999 | 0 | exts.extend(&self.contiguous_extensions); |
1000 | | |
1001 | 0 | if self |
1002 | 0 | .encrypted_client_hello_outer |
1003 | 0 | .is_some() |
1004 | 0 | { |
1005 | 0 | exts.push(ExtensionType::EncryptedClientHelloOuterExtensions); |
1006 | 0 | } |
1007 | 0 | if self.encrypted_client_hello.is_some() { |
1008 | 0 | exts.push(ExtensionType::EncryptedClientHello); |
1009 | 0 | } |
1010 | 0 | if self.preshared_key_offer.is_some() { |
1011 | 0 | exts.push(ExtensionType::PreSharedKey); |
1012 | 0 | } |
1013 | 0 | exts |
1014 | 0 | } |
1015 | | |
1016 | | /// Returns extensions which don't need a specific order, in randomized order. |
1017 | | /// |
1018 | | /// Extensions are encoded in three portions: |
1019 | | /// |
1020 | | /// - First, extensions not otherwise dealt with by other cases. |
1021 | | /// These are encoded in random order, controlled by `self.order_seed`, |
1022 | | /// and this is the set of extensions returned by this function. |
1023 | | /// |
1024 | | /// - Second, extensions named in `self.contiguous_extensions`, in the order |
1025 | | /// given by that field. |
1026 | | /// |
1027 | | /// - Lastly, any ECH and PSK extensions (in that order). These |
1028 | | /// are required to be last by the standard. |
1029 | 0 | fn order_insensitive_extensions_in_random_order(&self) -> Vec<ExtensionType> { |
1030 | 0 | let mut order = self.collect_used(); |
1031 | | |
1032 | | // Remove extensions which have specific order requirements. |
1033 | 0 | order.retain(|ext| { |
1034 | 0 | !(matches!( |
1035 | 0 | ext, |
1036 | | ExtensionType::PreSharedKey |
1037 | | | ExtensionType::EncryptedClientHello |
1038 | | | ExtensionType::EncryptedClientHelloOuterExtensions |
1039 | 0 | ) || self.contiguous_extensions.contains(ext)) |
1040 | 0 | }); |
1041 | | |
1042 | 0 | order.sort_by_cached_key(|new_ext| { |
1043 | 0 | let seed = ((self.order_seed as u32) << 16) | (u16::from(*new_ext) as u32); |
1044 | 0 | low_quality_integer_hash(seed) |
1045 | 0 | }); |
1046 | | |
1047 | 0 | order |
1048 | 0 | } |
1049 | | } |
1050 | | |
1051 | | impl<'a> Codec<'a> for ClientExtensions<'a> { |
1052 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1053 | 0 | let order = self.used_extensions_in_encoding_order(); |
1054 | | |
1055 | 0 | if order.is_empty() { |
1056 | 0 | return; |
1057 | 0 | } |
1058 | | |
1059 | 0 | let body = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
1060 | 0 | for item in order { |
1061 | 0 | self.encode_one(item, body.buf); |
1062 | 0 | } |
1063 | 0 | } |
1064 | | |
1065 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1066 | 0 | let mut out = Self::default(); |
1067 | | |
1068 | | // extensions length can be absent if no extensions |
1069 | 0 | if !r.any_left() { |
1070 | 0 | return Ok(out); |
1071 | 0 | } |
1072 | | |
1073 | 0 | let mut checker = DuplicateExtensionChecker::new(); |
1074 | | |
1075 | 0 | let len = usize::from(u16::read(r)?); |
1076 | 0 | let mut sub = r.sub(len)?; |
1077 | | |
1078 | 0 | while sub.any_left() { |
1079 | 0 | let typ = out.read_one(&mut sub, |unknown| checker.check(unknown))?; |
1080 | | |
1081 | | // PreSharedKey offer must come last |
1082 | 0 | if typ == ExtensionType::PreSharedKey && sub.any_left() { |
1083 | 0 | return Err(InvalidMessage::PreSharedKeyIsNotFinalExtension); |
1084 | 0 | } |
1085 | | } |
1086 | | |
1087 | 0 | Ok(out) |
1088 | 0 | } |
1089 | | } |
1090 | | |
1091 | 0 | fn trim_hostname_trailing_dot_for_sni(dns_name: &DnsName<'_>) -> DnsName<'static> { |
1092 | 0 | let dns_name_str = dns_name.as_ref(); |
1093 | | |
1094 | | // RFC6066: "The hostname is represented as a byte string using |
1095 | | // ASCII encoding without a trailing dot" |
1096 | 0 | if dns_name_str.ends_with('.') { |
1097 | 0 | let trimmed = &dns_name_str[0..dns_name_str.len() - 1]; |
1098 | 0 | DnsName::try_from(trimmed) |
1099 | 0 | .unwrap() |
1100 | 0 | .to_owned() |
1101 | | } else { |
1102 | 0 | dns_name.to_owned() |
1103 | | } |
1104 | 0 | } |
1105 | | |
1106 | | #[derive(Clone, Debug)] |
1107 | | pub(crate) enum ClientSessionTicket { |
1108 | | Request, |
1109 | | Offer(Payload<'static>), |
1110 | | } |
1111 | | |
1112 | | impl<'a> Codec<'a> for ClientSessionTicket { |
1113 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1114 | 0 | match self { |
1115 | 0 | Self::Request => (), |
1116 | 0 | Self::Offer(p) => p.encode(bytes), |
1117 | | } |
1118 | 0 | } |
1119 | | |
1120 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1121 | 0 | Ok(match r.left() { |
1122 | 0 | 0 => Self::Request, |
1123 | 0 | _ => Self::Offer(Payload::read(r).into_owned()), |
1124 | | }) |
1125 | 0 | } |
1126 | | } |
1127 | | |
1128 | | #[derive(Default)] |
1129 | | pub(crate) struct ServerExtensionsInput<'a> { |
1130 | | /// QUIC transport parameters |
1131 | | pub(crate) transport_parameters: Option<TransportParameters<'a>>, |
1132 | | } |
1133 | | |
1134 | | extension_struct! { |
1135 | | pub(crate) struct ServerExtensions<'a> { |
1136 | | /// Supported EC point formats (RFC4492) |
1137 | | ExtensionType::ECPointFormats => |
1138 | | pub(crate) ec_point_formats: Option<SupportedEcPointFormats>, |
1139 | | |
1140 | | /// Server name indication acknowledgement (RFC6066) |
1141 | | ExtensionType::ServerName => |
1142 | | pub(crate) server_name_ack: Option<()>, |
1143 | | |
1144 | | /// Session ticket acknowledgement (RFC5077) |
1145 | | ExtensionType::SessionTicket => |
1146 | | pub(crate) session_ticket_ack: Option<()>, |
1147 | | |
1148 | | ExtensionType::RenegotiationInfo => |
1149 | | pub(crate) renegotiation_info: Option<PayloadU8>, |
1150 | | |
1151 | | /// Selected ALPN protocol (RFC7301) |
1152 | | ExtensionType::ALProtocolNegotiation => |
1153 | | pub(crate) selected_protocol: Option<SingleProtocolName>, |
1154 | | |
1155 | | /// Key exchange server share (RFC8446) |
1156 | | ExtensionType::KeyShare => |
1157 | | pub(crate) key_share: Option<KeyShareEntry>, |
1158 | | |
1159 | | /// Selected preshared key index (RFC8446) |
1160 | | ExtensionType::PreSharedKey => |
1161 | | pub(crate) preshared_key: Option<u16>, |
1162 | | |
1163 | | /// Required client certificate type (RFC7250) |
1164 | | ExtensionType::ClientCertificateType => |
1165 | | pub(crate) client_certificate_type: Option<CertificateType>, |
1166 | | |
1167 | | /// Selected server certificate type (RFC7250) |
1168 | | ExtensionType::ServerCertificateType => |
1169 | | pub(crate) server_certificate_type: Option<CertificateType>, |
1170 | | |
1171 | | /// Extended master secret is in use (RFC7627) |
1172 | | ExtensionType::ExtendedMasterSecret => |
1173 | | pub(crate) extended_master_secret_ack: Option<()>, |
1174 | | |
1175 | | /// Certificate status acknowledgement (RFC6066) |
1176 | | ExtensionType::StatusRequest => |
1177 | | pub(crate) certificate_status_request_ack: Option<()>, |
1178 | | |
1179 | | /// Selected TLS version (RFC8446) |
1180 | | ExtensionType::SupportedVersions => |
1181 | | pub(crate) selected_version: Option<ProtocolVersion>, |
1182 | | |
1183 | | /// QUIC transport parameters (RFC9001) |
1184 | | ExtensionType::TransportParameters => |
1185 | | pub(crate) transport_parameters: Option<Payload<'a>>, |
1186 | | |
1187 | | /// QUIC transport parameters (RFC9001 prior to draft 33) |
1188 | | ExtensionType::TransportParametersDraft => |
1189 | | pub(crate) transport_parameters_draft: Option<Payload<'a>>, |
1190 | | |
1191 | | /// Early data is accepted (RFC8446) |
1192 | | ExtensionType::EarlyData => |
1193 | | pub(crate) early_data_ack: Option<()>, |
1194 | | |
1195 | | /// Encrypted inner client hello response (draft-ietf-tls-esni) |
1196 | | ExtensionType::EncryptedClientHello => |
1197 | | pub(crate) encrypted_client_hello_ack: Option<ServerEncryptedClientHello>, |
1198 | | } + { |
1199 | | pub(crate) unknown_extensions: BTreeSet<u16>, |
1200 | | } |
1201 | | } |
1202 | | |
1203 | | impl ServerExtensions<'_> { |
1204 | 0 | fn into_owned(self) -> ServerExtensions<'static> { |
1205 | 0 | let Self { |
1206 | 0 | ec_point_formats, |
1207 | 0 | server_name_ack, |
1208 | 0 | session_ticket_ack, |
1209 | 0 | renegotiation_info, |
1210 | 0 | selected_protocol, |
1211 | 0 | key_share, |
1212 | 0 | preshared_key, |
1213 | 0 | client_certificate_type, |
1214 | 0 | server_certificate_type, |
1215 | 0 | extended_master_secret_ack, |
1216 | 0 | certificate_status_request_ack, |
1217 | 0 | selected_version, |
1218 | 0 | transport_parameters, |
1219 | 0 | transport_parameters_draft, |
1220 | 0 | early_data_ack, |
1221 | 0 | encrypted_client_hello_ack, |
1222 | 0 | unknown_extensions, |
1223 | 0 | } = self; |
1224 | | ServerExtensions { |
1225 | 0 | ec_point_formats, |
1226 | 0 | server_name_ack, |
1227 | 0 | session_ticket_ack, |
1228 | 0 | renegotiation_info, |
1229 | 0 | selected_protocol, |
1230 | 0 | key_share, |
1231 | 0 | preshared_key, |
1232 | 0 | client_certificate_type, |
1233 | 0 | server_certificate_type, |
1234 | 0 | extended_master_secret_ack, |
1235 | 0 | certificate_status_request_ack, |
1236 | 0 | selected_version, |
1237 | 0 | transport_parameters: transport_parameters.map(|x| x.into_owned()), |
1238 | 0 | transport_parameters_draft: transport_parameters_draft.map(|x| x.into_owned()), |
1239 | 0 | early_data_ack, |
1240 | 0 | encrypted_client_hello_ack, |
1241 | 0 | unknown_extensions, |
1242 | | } |
1243 | 0 | } |
1244 | | } |
1245 | | |
1246 | | impl<'a> Codec<'a> for ServerExtensions<'a> { |
1247 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1248 | 0 | let extensions = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
1249 | | |
1250 | 0 | for ext in Self::ALL_EXTENSIONS { |
1251 | 0 | self.encode_one(*ext, extensions.buf); |
1252 | 0 | } |
1253 | 0 | } |
1254 | | |
1255 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1256 | 0 | let mut out = Self::default(); |
1257 | 0 | let mut checker = DuplicateExtensionChecker::new(); |
1258 | | |
1259 | 0 | let len = usize::from(u16::read(r)?); |
1260 | 0 | let mut sub = r.sub(len)?; |
1261 | | |
1262 | 0 | while sub.any_left() { |
1263 | 0 | out.read_one(&mut sub, |unknown| checker.check(unknown))?; |
1264 | | } |
1265 | | |
1266 | 0 | out.unknown_extensions = checker.0; |
1267 | 0 | Ok(out) |
1268 | 0 | } |
1269 | | } |
1270 | | |
1271 | | #[derive(Clone, Debug)] |
1272 | | pub(crate) struct ClientHelloPayload { |
1273 | | pub(crate) client_version: ProtocolVersion, |
1274 | | pub(crate) random: Random, |
1275 | | pub(crate) session_id: SessionId, |
1276 | | pub(crate) cipher_suites: Vec<CipherSuite>, |
1277 | | pub(crate) compression_methods: Vec<Compression>, |
1278 | | pub(crate) extensions: Box<ClientExtensions<'static>>, |
1279 | | } |
1280 | | |
1281 | | impl ClientHelloPayload { |
1282 | 0 | pub(crate) fn ech_inner_encoding(&self, to_compress: Vec<ExtensionType>) -> Vec<u8> { |
1283 | 0 | let mut bytes = Vec::new(); |
1284 | 0 | self.payload_encode(&mut bytes, Encoding::EchInnerHello { to_compress }); |
1285 | 0 | bytes |
1286 | 0 | } |
1287 | | |
1288 | 0 | pub(crate) fn payload_encode(&self, bytes: &mut Vec<u8>, purpose: Encoding) { |
1289 | 0 | self.client_version.encode(bytes); |
1290 | 0 | self.random.encode(bytes); |
1291 | | |
1292 | 0 | match purpose { |
1293 | | // SessionID is required to be empty in the encoded inner client hello. |
1294 | 0 | Encoding::EchInnerHello { .. } => SessionId::empty().encode(bytes), |
1295 | 0 | _ => self.session_id.encode(bytes), |
1296 | | } |
1297 | | |
1298 | 0 | self.cipher_suites.encode(bytes); |
1299 | 0 | self.compression_methods.encode(bytes); |
1300 | | |
1301 | 0 | let to_compress = match purpose { |
1302 | 0 | Encoding::EchInnerHello { to_compress } if !to_compress.is_empty() => to_compress, |
1303 | | _ => { |
1304 | 0 | self.extensions.encode(bytes); |
1305 | 0 | return; |
1306 | | } |
1307 | | }; |
1308 | | |
1309 | 0 | let mut compressed = self.extensions.clone(); |
1310 | | |
1311 | | // First, eliminate the full-fat versions of the extensions |
1312 | 0 | for e in &to_compress { |
1313 | 0 | compressed.clear(*e); |
1314 | 0 | } |
1315 | | |
1316 | | // Replace with the marker noting which extensions were elided. |
1317 | 0 | compressed.encrypted_client_hello_outer = Some(to_compress); |
1318 | | |
1319 | | // And encode as normal. |
1320 | 0 | compressed.encode(bytes); |
1321 | 0 | } |
1322 | | |
1323 | 0 | pub(crate) fn has_keyshare_extension_with_duplicates(&self) -> bool { |
1324 | 0 | self.key_shares |
1325 | 0 | .as_ref() |
1326 | 0 | .map(|entries| { |
1327 | 0 | has_duplicates::<_, _, u16>( |
1328 | 0 | entries |
1329 | 0 | .iter() |
1330 | 0 | .map(|kse| u16::from(kse.group)), |
1331 | | ) |
1332 | 0 | }) |
1333 | 0 | .unwrap_or_default() |
1334 | 0 | } |
1335 | | |
1336 | 0 | pub(crate) fn has_certificate_compression_extension_with_duplicates(&self) -> bool { |
1337 | 0 | if let Some(algs) = &self.certificate_compression_algorithms { |
1338 | 0 | has_duplicates::<_, _, u16>(algs.iter().cloned()) |
1339 | | } else { |
1340 | 0 | false |
1341 | | } |
1342 | 0 | } |
1343 | | } |
1344 | | |
1345 | | impl Codec<'_> for ClientHelloPayload { |
1346 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1347 | 0 | self.payload_encode(bytes, Encoding::Standard) |
1348 | 0 | } |
1349 | | |
1350 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1351 | 0 | let ret = Self { |
1352 | 0 | client_version: ProtocolVersion::read(r)?, |
1353 | 0 | random: Random::read(r)?, |
1354 | 0 | session_id: SessionId::read(r)?, |
1355 | 0 | cipher_suites: Vec::read(r)?, |
1356 | 0 | compression_methods: Vec::read(r)?, |
1357 | 0 | extensions: Box::new(ClientExtensions::read(r)?.into_owned()), |
1358 | | }; |
1359 | | |
1360 | 0 | match r.any_left() { |
1361 | 0 | true => Err(InvalidMessage::TrailingData("ClientHelloPayload")), |
1362 | 0 | false => Ok(ret), |
1363 | | } |
1364 | 0 | } |
1365 | | } |
1366 | | |
1367 | | impl Deref for ClientHelloPayload { |
1368 | | type Target = ClientExtensions<'static>; |
1369 | 0 | fn deref(&self) -> &Self::Target { |
1370 | 0 | &self.extensions |
1371 | 0 | } |
1372 | | } |
1373 | | |
1374 | | impl DerefMut for ClientHelloPayload { |
1375 | 0 | fn deref_mut(&mut self) -> &mut Self::Target { |
1376 | 0 | &mut self.extensions |
1377 | 0 | } |
1378 | | } |
1379 | | |
1380 | | /// RFC8446: `CipherSuite cipher_suites<2..2^16-2>;` |
1381 | | impl TlsListElement for CipherSuite { |
1382 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
1383 | | empty_error: InvalidMessage::IllegalEmptyList("CipherSuites"), |
1384 | | }; |
1385 | | } |
1386 | | |
1387 | | /// RFC5246: `CompressionMethod compression_methods<1..2^8-1>;` |
1388 | | impl TlsListElement for Compression { |
1389 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
1390 | | empty_error: InvalidMessage::IllegalEmptyList("Compressions"), |
1391 | | }; |
1392 | | } |
1393 | | |
1394 | | /// draft-ietf-tls-esni-17: `ExtensionType OuterExtensions<2..254>;` |
1395 | | impl TlsListElement for ExtensionType { |
1396 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
1397 | | empty_error: InvalidMessage::IllegalEmptyList("ExtensionTypes"), |
1398 | | }; |
1399 | | } |
1400 | | |
1401 | | extension_struct! { |
1402 | | /// A representation of extensions present in a `HelloRetryRequest` message |
1403 | | pub(crate) struct HelloRetryRequestExtensions<'a> { |
1404 | | ExtensionType::KeyShare => |
1405 | | pub(crate) key_share: Option<NamedGroup>, |
1406 | | |
1407 | | ExtensionType::Cookie => |
1408 | | pub(crate) cookie: Option<PayloadU16<NonEmpty>>, |
1409 | | |
1410 | | ExtensionType::SupportedVersions => |
1411 | | pub(crate) supported_versions: Option<ProtocolVersion>, |
1412 | | |
1413 | | ExtensionType::EncryptedClientHello => |
1414 | | pub(crate) encrypted_client_hello: Option<Payload<'a>>, |
1415 | | } + { |
1416 | | /// Records decoding order of records, and controls encoding order. |
1417 | | pub(crate) order: Option<Vec<ExtensionType>>, |
1418 | | } |
1419 | | } |
1420 | | |
1421 | | impl HelloRetryRequestExtensions<'_> { |
1422 | 0 | fn into_owned(self) -> HelloRetryRequestExtensions<'static> { |
1423 | 0 | let Self { |
1424 | 0 | key_share, |
1425 | 0 | cookie, |
1426 | 0 | supported_versions, |
1427 | 0 | encrypted_client_hello, |
1428 | 0 | order, |
1429 | 0 | } = self; |
1430 | | HelloRetryRequestExtensions { |
1431 | 0 | key_share, |
1432 | 0 | cookie, |
1433 | 0 | supported_versions, |
1434 | 0 | encrypted_client_hello: encrypted_client_hello.map(|x| x.into_owned()), |
1435 | 0 | order, |
1436 | | } |
1437 | 0 | } |
1438 | | } |
1439 | | |
1440 | | impl<'a> Codec<'a> for HelloRetryRequestExtensions<'a> { |
1441 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1442 | 0 | let extensions = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
1443 | | |
1444 | 0 | for ext in self |
1445 | 0 | .order |
1446 | 0 | .as_deref() |
1447 | 0 | .unwrap_or(Self::ALL_EXTENSIONS) |
1448 | 0 | { |
1449 | 0 | self.encode_one(*ext, extensions.buf); |
1450 | 0 | } |
1451 | 0 | } |
1452 | | |
1453 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1454 | 0 | let mut out = Self::default(); |
1455 | | |
1456 | | // we must record order, so re-encoding round trips. this is needed, |
1457 | | // unfortunately, for ECH HRR confirmation |
1458 | 0 | let mut order = vec![]; |
1459 | | |
1460 | 0 | let len = usize::from(u16::read(r)?); |
1461 | 0 | let mut sub = r.sub(len)?; |
1462 | | |
1463 | 0 | while sub.any_left() { |
1464 | 0 | let typ = out.read_one(&mut sub, |_unk| { |
1465 | 0 | Err(InvalidMessage::UnknownHelloRetryRequestExtension) |
1466 | 0 | })?; |
1467 | | |
1468 | 0 | order.push(typ); |
1469 | | } |
1470 | | |
1471 | 0 | out.order = Some(order); |
1472 | 0 | Ok(out) |
1473 | 0 | } |
1474 | | } |
1475 | | |
1476 | | #[derive(Clone, Debug)] |
1477 | | pub(crate) struct HelloRetryRequest { |
1478 | | pub(crate) legacy_version: ProtocolVersion, |
1479 | | pub(crate) session_id: SessionId, |
1480 | | pub(crate) cipher_suite: CipherSuite, |
1481 | | pub(crate) extensions: HelloRetryRequestExtensions<'static>, |
1482 | | } |
1483 | | |
1484 | | impl Codec<'_> for HelloRetryRequest { |
1485 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1486 | 0 | self.payload_encode(bytes, Encoding::Standard) |
1487 | 0 | } |
1488 | | |
1489 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1490 | 0 | let session_id = SessionId::read(r)?; |
1491 | 0 | let cipher_suite = CipherSuite::read(r)?; |
1492 | 0 | let compression = Compression::read(r)?; |
1493 | | |
1494 | 0 | if compression != Compression::Null { |
1495 | 0 | return Err(InvalidMessage::UnsupportedCompression); |
1496 | 0 | } |
1497 | | |
1498 | | Ok(Self { |
1499 | 0 | legacy_version: ProtocolVersion::Unknown(0), |
1500 | 0 | session_id, |
1501 | 0 | cipher_suite, |
1502 | 0 | extensions: HelloRetryRequestExtensions::read(r)?.into_owned(), |
1503 | | }) |
1504 | 0 | } |
1505 | | } |
1506 | | |
1507 | | impl HelloRetryRequest { |
1508 | 0 | fn payload_encode(&self, bytes: &mut Vec<u8>, purpose: Encoding) { |
1509 | 0 | self.legacy_version.encode(bytes); |
1510 | 0 | HELLO_RETRY_REQUEST_RANDOM.encode(bytes); |
1511 | 0 | self.session_id.encode(bytes); |
1512 | 0 | self.cipher_suite.encode(bytes); |
1513 | 0 | Compression::Null.encode(bytes); |
1514 | | |
1515 | 0 | match purpose { |
1516 | | // For the purpose of ECH confirmation, the Encrypted Client Hello extension |
1517 | | // must have its payload replaced by 8 zero bytes. |
1518 | | // |
1519 | | // See draft-ietf-tls-esni-18 7.2.1: |
1520 | | // <https://datatracker.ietf.org/doc/html/draft-ietf-tls-esni-18#name-sending-helloretryrequest-2> |
1521 | | Encoding::EchConfirmation |
1522 | 0 | if self |
1523 | 0 | .extensions |
1524 | 0 | .encrypted_client_hello |
1525 | 0 | .is_some() => |
1526 | 0 | { |
1527 | 0 | let hrr_confirmation = [0u8; 8]; |
1528 | 0 | HelloRetryRequestExtensions { |
1529 | 0 | encrypted_client_hello: Some(Payload::Borrowed(&hrr_confirmation)), |
1530 | 0 | ..self.extensions.clone() |
1531 | 0 | } |
1532 | 0 | .encode(bytes); |
1533 | 0 | } |
1534 | 0 | _ => self.extensions.encode(bytes), |
1535 | | } |
1536 | 0 | } |
1537 | | } |
1538 | | |
1539 | | impl Deref for HelloRetryRequest { |
1540 | | type Target = HelloRetryRequestExtensions<'static>; |
1541 | 0 | fn deref(&self) -> &Self::Target { |
1542 | 0 | &self.extensions |
1543 | 0 | } |
1544 | | } |
1545 | | |
1546 | | impl DerefMut for HelloRetryRequest { |
1547 | 0 | fn deref_mut(&mut self) -> &mut Self::Target { |
1548 | 0 | &mut self.extensions |
1549 | 0 | } |
1550 | | } |
1551 | | |
1552 | | #[derive(Clone, Debug)] |
1553 | | pub(crate) struct ServerHelloPayload { |
1554 | | pub(crate) legacy_version: ProtocolVersion, |
1555 | | pub(crate) random: Random, |
1556 | | pub(crate) session_id: SessionId, |
1557 | | pub(crate) cipher_suite: CipherSuite, |
1558 | | pub(crate) compression_method: Compression, |
1559 | | pub(crate) extensions: Box<ServerExtensions<'static>>, |
1560 | | } |
1561 | | |
1562 | | impl Codec<'_> for ServerHelloPayload { |
1563 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1564 | 0 | self.payload_encode(bytes, Encoding::Standard) |
1565 | 0 | } |
1566 | | |
1567 | | // minus version and random, which have already been read. |
1568 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1569 | 0 | let session_id = SessionId::read(r)?; |
1570 | 0 | let suite = CipherSuite::read(r)?; |
1571 | 0 | let compression = Compression::read(r)?; |
1572 | | |
1573 | | // RFC5246: |
1574 | | // "The presence of extensions can be detected by determining whether |
1575 | | // there are bytes following the compression_method field at the end of |
1576 | | // the ServerHello." |
1577 | 0 | let extensions = Box::new( |
1578 | 0 | if r.any_left() { |
1579 | 0 | ServerExtensions::read(r)? |
1580 | | } else { |
1581 | 0 | ServerExtensions::default() |
1582 | | } |
1583 | 0 | .into_owned(), |
1584 | | ); |
1585 | | |
1586 | 0 | let ret = Self { |
1587 | 0 | legacy_version: ProtocolVersion::Unknown(0), |
1588 | 0 | random: ZERO_RANDOM, |
1589 | 0 | session_id, |
1590 | 0 | cipher_suite: suite, |
1591 | 0 | compression_method: compression, |
1592 | 0 | extensions, |
1593 | 0 | }; |
1594 | | |
1595 | 0 | r.expect_empty("ServerHelloPayload") |
1596 | 0 | .map(|_| ret) |
1597 | 0 | } |
1598 | | } |
1599 | | |
1600 | | impl ServerHelloPayload { |
1601 | 0 | fn payload_encode(&self, bytes: &mut Vec<u8>, encoding: Encoding) { |
1602 | 0 | debug_assert!( |
1603 | 0 | !matches!(encoding, Encoding::EchConfirmation), |
1604 | 0 | "we cannot compute an ECH confirmation on a received ServerHello" |
1605 | | ); |
1606 | | |
1607 | 0 | self.legacy_version.encode(bytes); |
1608 | 0 | self.random.encode(bytes); |
1609 | 0 | self.session_id.encode(bytes); |
1610 | 0 | self.cipher_suite.encode(bytes); |
1611 | 0 | self.compression_method.encode(bytes); |
1612 | 0 | self.extensions.encode(bytes); |
1613 | 0 | } |
1614 | | } |
1615 | | |
1616 | | impl Deref for ServerHelloPayload { |
1617 | | type Target = ServerExtensions<'static>; |
1618 | 0 | fn deref(&self) -> &Self::Target { |
1619 | 0 | &self.extensions |
1620 | 0 | } |
1621 | | } |
1622 | | |
1623 | | impl DerefMut for ServerHelloPayload { |
1624 | 0 | fn deref_mut(&mut self) -> &mut Self::Target { |
1625 | 0 | &mut self.extensions |
1626 | 0 | } |
1627 | | } |
1628 | | |
1629 | | #[derive(Clone, Default, Debug)] |
1630 | | pub(crate) struct CertificateChain<'a>(pub(crate) Vec<CertificateDer<'a>>); |
1631 | | |
1632 | | impl CertificateChain<'_> { |
1633 | 0 | pub(crate) fn into_owned(self) -> CertificateChain<'static> { |
1634 | | CertificateChain( |
1635 | 0 | self.0 |
1636 | 0 | .into_iter() |
1637 | 0 | .map(|c| c.into_owned()) |
1638 | 0 | .collect(), |
1639 | | ) |
1640 | 0 | } |
1641 | | } |
1642 | | |
1643 | | impl<'a> Codec<'a> for CertificateChain<'a> { |
1644 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1645 | 0 | Vec::encode(&self.0, bytes) |
1646 | 0 | } |
1647 | | |
1648 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1649 | 0 | Vec::read(r).map(Self) |
1650 | 0 | } |
1651 | | } |
1652 | | |
1653 | | impl<'a> Deref for CertificateChain<'a> { |
1654 | | type Target = [CertificateDer<'a>]; |
1655 | | |
1656 | 0 | fn deref(&self) -> &[CertificateDer<'a>] { |
1657 | 0 | &self.0 |
1658 | 0 | } |
1659 | | } |
1660 | | |
1661 | | impl TlsListElement for CertificateDer<'_> { |
1662 | | const SIZE_LEN: ListLength = ListLength::U24 { |
1663 | | max: CERTIFICATE_MAX_SIZE_LIMIT, |
1664 | | error: InvalidMessage::CertificatePayloadTooLarge, |
1665 | | }; |
1666 | | } |
1667 | | |
1668 | | /// TLS has a 16MB size limit on any handshake message, |
1669 | | /// plus a 16MB limit on any given certificate. |
1670 | | /// |
1671 | | /// We contract that to 64KB to limit the amount of memory allocation |
1672 | | /// that is directly controllable by the peer. |
1673 | | pub(crate) const CERTIFICATE_MAX_SIZE_LIMIT: usize = 0x1_0000; |
1674 | | |
1675 | | extension_struct! { |
1676 | | pub(crate) struct CertificateExtensions<'a> { |
1677 | | ExtensionType::StatusRequest => |
1678 | | pub(crate) status: Option<CertificateStatus<'a>>, |
1679 | | } |
1680 | | } |
1681 | | |
1682 | | impl CertificateExtensions<'_> { |
1683 | 0 | fn into_owned(self) -> CertificateExtensions<'static> { |
1684 | | CertificateExtensions { |
1685 | 0 | status: self.status.map(|s| s.into_owned()), |
1686 | | } |
1687 | 0 | } |
1688 | | } |
1689 | | |
1690 | | impl<'a> Codec<'a> for CertificateExtensions<'a> { |
1691 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1692 | 0 | let extensions = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
1693 | | |
1694 | 0 | for ext in Self::ALL_EXTENSIONS { |
1695 | 0 | self.encode_one(*ext, extensions.buf); |
1696 | 0 | } |
1697 | 0 | } |
1698 | | |
1699 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1700 | 0 | let mut out = Self::default(); |
1701 | | |
1702 | 0 | let len = usize::from(u16::read(r)?); |
1703 | 0 | let mut sub = r.sub(len)?; |
1704 | | |
1705 | 0 | while sub.any_left() { |
1706 | 0 | out.read_one(&mut sub, |_unk| { |
1707 | 0 | Err(InvalidMessage::UnknownCertificateExtension) |
1708 | 0 | })?; |
1709 | | } |
1710 | | |
1711 | 0 | Ok(out) |
1712 | 0 | } |
1713 | | } |
1714 | | |
1715 | | #[derive(Debug)] |
1716 | | pub(crate) struct CertificateEntry<'a> { |
1717 | | pub(crate) cert: CertificateDer<'a>, |
1718 | | pub(crate) extensions: CertificateExtensions<'a>, |
1719 | | } |
1720 | | |
1721 | | impl<'a> Codec<'a> for CertificateEntry<'a> { |
1722 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1723 | 0 | self.cert.encode(bytes); |
1724 | 0 | self.extensions.encode(bytes); |
1725 | 0 | } |
1726 | | |
1727 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1728 | | Ok(Self { |
1729 | 0 | cert: CertificateDer::read(r)?, |
1730 | 0 | extensions: CertificateExtensions::read(r)?.into_owned(), |
1731 | | }) |
1732 | 0 | } |
1733 | | } |
1734 | | |
1735 | | impl<'a> CertificateEntry<'a> { |
1736 | 0 | pub(crate) fn new(cert: CertificateDer<'a>) -> Self { |
1737 | 0 | Self { |
1738 | 0 | cert, |
1739 | 0 | extensions: CertificateExtensions::default(), |
1740 | 0 | } |
1741 | 0 | } |
1742 | | |
1743 | 0 | pub(crate) fn into_owned(self) -> CertificateEntry<'static> { |
1744 | 0 | CertificateEntry { |
1745 | 0 | cert: self.cert.into_owned(), |
1746 | 0 | extensions: self.extensions.into_owned(), |
1747 | 0 | } |
1748 | 0 | } |
1749 | | } |
1750 | | |
1751 | | impl TlsListElement for CertificateEntry<'_> { |
1752 | | const SIZE_LEN: ListLength = ListLength::U24 { |
1753 | | max: CERTIFICATE_MAX_SIZE_LIMIT, |
1754 | | error: InvalidMessage::CertificatePayloadTooLarge, |
1755 | | }; |
1756 | | } |
1757 | | |
1758 | | #[derive(Debug)] |
1759 | | pub(crate) struct CertificatePayloadTls13<'a> { |
1760 | | pub(crate) context: PayloadU8, |
1761 | | pub(crate) entries: Vec<CertificateEntry<'a>>, |
1762 | | } |
1763 | | |
1764 | | impl<'a> Codec<'a> for CertificatePayloadTls13<'a> { |
1765 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1766 | 0 | self.context.encode(bytes); |
1767 | 0 | self.entries.encode(bytes); |
1768 | 0 | } |
1769 | | |
1770 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
1771 | | Ok(Self { |
1772 | 0 | context: PayloadU8::read(r)?, |
1773 | 0 | entries: Vec::read(r)?, |
1774 | | }) |
1775 | 0 | } |
1776 | | } |
1777 | | |
1778 | | impl<'a> CertificatePayloadTls13<'a> { |
1779 | 0 | pub(crate) fn new( |
1780 | 0 | certs: impl Iterator<Item = &'a CertificateDer<'a>>, |
1781 | 0 | ocsp_response: Option<&'a [u8]>, |
1782 | 0 | ) -> Self { |
1783 | | Self { |
1784 | 0 | context: PayloadU8::empty(), |
1785 | 0 | entries: certs |
1786 | | // zip certificate iterator with `ocsp_response` followed by |
1787 | | // an infinite-length iterator of `None`. |
1788 | 0 | .zip( |
1789 | 0 | ocsp_response |
1790 | 0 | .into_iter() |
1791 | 0 | .map(Some) |
1792 | 0 | .chain(iter::repeat(None)), |
1793 | | ) |
1794 | 0 | .map(|(cert, ocsp)| { |
1795 | 0 | let mut e = CertificateEntry::new(cert.clone()); |
1796 | 0 | if let Some(ocsp) = ocsp { |
1797 | 0 | e.extensions.status = Some(CertificateStatus::new(ocsp)); |
1798 | 0 | } |
1799 | 0 | e |
1800 | 0 | }) |
1801 | 0 | .collect(), |
1802 | | } |
1803 | 0 | } |
1804 | | |
1805 | 0 | pub(crate) fn into_owned(self) -> CertificatePayloadTls13<'static> { |
1806 | 0 | CertificatePayloadTls13 { |
1807 | 0 | context: self.context, |
1808 | 0 | entries: self |
1809 | 0 | .entries |
1810 | 0 | .into_iter() |
1811 | 0 | .map(CertificateEntry::into_owned) |
1812 | 0 | .collect(), |
1813 | 0 | } |
1814 | 0 | } |
1815 | | |
1816 | 0 | pub(crate) fn end_entity_ocsp(&self) -> Vec<u8> { |
1817 | 0 | let Some(entry) = self.entries.first() else { |
1818 | 0 | return vec![]; |
1819 | | }; |
1820 | 0 | entry |
1821 | 0 | .extensions |
1822 | 0 | .status |
1823 | 0 | .as_ref() |
1824 | 0 | .map(|status| { |
1825 | 0 | status |
1826 | 0 | .ocsp_response |
1827 | 0 | .0 |
1828 | 0 | .clone() |
1829 | 0 | .into_vec() |
1830 | 0 | }) |
1831 | 0 | .unwrap_or_default() |
1832 | 0 | } |
1833 | | |
1834 | 0 | pub(crate) fn into_certificate_chain(self) -> CertificateChain<'a> { |
1835 | | CertificateChain( |
1836 | 0 | self.entries |
1837 | 0 | .into_iter() |
1838 | 0 | .map(|e| e.cert) |
1839 | 0 | .collect(), |
1840 | | ) |
1841 | 0 | } |
1842 | | } |
1843 | | |
1844 | | /// Describes supported key exchange mechanisms. |
1845 | | #[derive(Clone, Copy, Debug, PartialEq)] |
1846 | | #[non_exhaustive] |
1847 | | pub enum KeyExchangeAlgorithm { |
1848 | | /// Diffie-Hellman Key exchange (with only known parameters as defined in [RFC 7919]). |
1849 | | /// |
1850 | | /// [RFC 7919]: https://datatracker.ietf.org/doc/html/rfc7919 |
1851 | | DHE, |
1852 | | /// Key exchange performed via elliptic curve Diffie-Hellman. |
1853 | | ECDHE, |
1854 | | } |
1855 | | |
1856 | | pub(crate) static ALL_KEY_EXCHANGE_ALGORITHMS: &[KeyExchangeAlgorithm] = |
1857 | | &[KeyExchangeAlgorithm::ECDHE, KeyExchangeAlgorithm::DHE]; |
1858 | | |
1859 | | // We don't support arbitrary curves. It's a terrible |
1860 | | // idea and unnecessary attack surface. Please, |
1861 | | // get a grip. |
1862 | | #[derive(Debug)] |
1863 | | pub(crate) struct EcParameters { |
1864 | | pub(crate) curve_type: ECCurveType, |
1865 | | pub(crate) named_group: NamedGroup, |
1866 | | } |
1867 | | |
1868 | | impl Codec<'_> for EcParameters { |
1869 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1870 | 0 | self.curve_type.encode(bytes); |
1871 | 0 | self.named_group.encode(bytes); |
1872 | 0 | } |
1873 | | |
1874 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1875 | 0 | let ct = ECCurveType::read(r)?; |
1876 | 0 | if ct != ECCurveType::NamedCurve { |
1877 | 0 | return Err(InvalidMessage::UnsupportedCurveType); |
1878 | 0 | } |
1879 | | |
1880 | 0 | let grp = NamedGroup::read(r)?; |
1881 | | |
1882 | 0 | Ok(Self { |
1883 | 0 | curve_type: ct, |
1884 | 0 | named_group: grp, |
1885 | 0 | }) |
1886 | 0 | } |
1887 | | } |
1888 | | |
1889 | | #[cfg(feature = "tls12")] |
1890 | | pub(crate) trait KxDecode<'a>: fmt::Debug + Sized { |
1891 | | /// Decode a key exchange message given the key_exchange `algo` |
1892 | | fn decode(r: &mut Reader<'a>, algo: KeyExchangeAlgorithm) -> Result<Self, InvalidMessage>; |
1893 | | } |
1894 | | |
1895 | | #[cfg(feature = "tls12")] |
1896 | | #[derive(Debug)] |
1897 | | pub(crate) enum ClientKeyExchangeParams { |
1898 | | Ecdh(ClientEcdhParams), |
1899 | | Dh(ClientDhParams), |
1900 | | } |
1901 | | |
1902 | | #[cfg(feature = "tls12")] |
1903 | | impl ClientKeyExchangeParams { |
1904 | 0 | pub(crate) fn pub_key(&self) -> &[u8] { |
1905 | 0 | match self { |
1906 | 0 | Self::Ecdh(ecdh) => &ecdh.public.0, |
1907 | 0 | Self::Dh(dh) => &dh.public.0, |
1908 | | } |
1909 | 0 | } |
1910 | | |
1911 | 0 | pub(crate) fn encode(&self, buf: &mut Vec<u8>) { |
1912 | 0 | match self { |
1913 | 0 | Self::Ecdh(ecdh) => ecdh.encode(buf), |
1914 | 0 | Self::Dh(dh) => dh.encode(buf), |
1915 | | } |
1916 | 0 | } |
1917 | | } |
1918 | | |
1919 | | #[cfg(feature = "tls12")] |
1920 | | impl KxDecode<'_> for ClientKeyExchangeParams { |
1921 | 0 | fn decode(r: &mut Reader<'_>, algo: KeyExchangeAlgorithm) -> Result<Self, InvalidMessage> { |
1922 | | use KeyExchangeAlgorithm::*; |
1923 | 0 | Ok(match algo { |
1924 | 0 | ECDHE => Self::Ecdh(ClientEcdhParams::read(r)?), |
1925 | 0 | DHE => Self::Dh(ClientDhParams::read(r)?), |
1926 | | }) |
1927 | 0 | } |
1928 | | } |
1929 | | |
1930 | | #[cfg(feature = "tls12")] |
1931 | | #[derive(Debug)] |
1932 | | pub(crate) struct ClientEcdhParams { |
1933 | | /// RFC4492: `opaque point <1..2^8-1>;` |
1934 | | pub(crate) public: PayloadU8<NonEmpty>, |
1935 | | } |
1936 | | |
1937 | | #[cfg(feature = "tls12")] |
1938 | | impl Codec<'_> for ClientEcdhParams { |
1939 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1940 | 0 | self.public.encode(bytes); |
1941 | 0 | } |
1942 | | |
1943 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1944 | 0 | let pb = PayloadU8::read(r)?; |
1945 | 0 | Ok(Self { public: pb }) |
1946 | 0 | } |
1947 | | } |
1948 | | |
1949 | | #[cfg(feature = "tls12")] |
1950 | | #[derive(Debug)] |
1951 | | pub(crate) struct ClientDhParams { |
1952 | | /// RFC5246: `opaque dh_Yc<1..2^16-1>;` |
1953 | | pub(crate) public: PayloadU16<NonEmpty>, |
1954 | | } |
1955 | | |
1956 | | #[cfg(feature = "tls12")] |
1957 | | impl Codec<'_> for ClientDhParams { |
1958 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1959 | 0 | self.public.encode(bytes); |
1960 | 0 | } |
1961 | | |
1962 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1963 | | Ok(Self { |
1964 | 0 | public: PayloadU16::read(r)?, |
1965 | | }) |
1966 | 0 | } |
1967 | | } |
1968 | | |
1969 | | #[derive(Debug)] |
1970 | | pub(crate) struct ServerEcdhParams { |
1971 | | pub(crate) curve_params: EcParameters, |
1972 | | /// RFC4492: `opaque point <1..2^8-1>;` |
1973 | | pub(crate) public: PayloadU8<NonEmpty>, |
1974 | | } |
1975 | | |
1976 | | impl ServerEcdhParams { |
1977 | | #[cfg(feature = "tls12")] |
1978 | 0 | pub(crate) fn new(kx: &dyn ActiveKeyExchange) -> Self { |
1979 | 0 | Self { |
1980 | 0 | curve_params: EcParameters { |
1981 | 0 | curve_type: ECCurveType::NamedCurve, |
1982 | 0 | named_group: kx.group(), |
1983 | 0 | }, |
1984 | 0 | public: PayloadU8::new(kx.pub_key().to_vec()), |
1985 | 0 | } |
1986 | 0 | } |
1987 | | } |
1988 | | |
1989 | | impl Codec<'_> for ServerEcdhParams { |
1990 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
1991 | 0 | self.curve_params.encode(bytes); |
1992 | 0 | self.public.encode(bytes); |
1993 | 0 | } |
1994 | | |
1995 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
1996 | 0 | let cp = EcParameters::read(r)?; |
1997 | 0 | let pb = PayloadU8::read(r)?; |
1998 | | |
1999 | 0 | Ok(Self { |
2000 | 0 | curve_params: cp, |
2001 | 0 | public: pb, |
2002 | 0 | }) |
2003 | 0 | } |
2004 | | } |
2005 | | |
2006 | | #[derive(Debug)] |
2007 | | #[allow(non_snake_case)] |
2008 | | pub(crate) struct ServerDhParams { |
2009 | | /// RFC5246: `opaque dh_p<1..2^16-1>;` |
2010 | | pub(crate) dh_p: PayloadU16<NonEmpty>, |
2011 | | /// RFC5246: `opaque dh_g<1..2^16-1>;` |
2012 | | pub(crate) dh_g: PayloadU16<NonEmpty>, |
2013 | | /// RFC5246: `opaque dh_Ys<1..2^16-1>;` |
2014 | | pub(crate) dh_Ys: PayloadU16<NonEmpty>, |
2015 | | } |
2016 | | |
2017 | | impl ServerDhParams { |
2018 | | #[cfg(feature = "tls12")] |
2019 | 0 | pub(crate) fn new(kx: &dyn ActiveKeyExchange) -> Self { |
2020 | 0 | let Some(params) = kx.ffdhe_group() else { |
2021 | 0 | panic!("invalid NamedGroup for DHE key exchange: {:?}", kx.group()); |
2022 | | }; |
2023 | | |
2024 | 0 | Self { |
2025 | 0 | dh_p: PayloadU16::new(params.p.to_vec()), |
2026 | 0 | dh_g: PayloadU16::new(params.g.to_vec()), |
2027 | 0 | dh_Ys: PayloadU16::new(kx.pub_key().to_vec()), |
2028 | 0 | } |
2029 | 0 | } |
2030 | | |
2031 | | #[cfg(feature = "tls12")] |
2032 | 0 | pub(crate) fn as_ffdhe_group(&self) -> FfdheGroup<'_> { |
2033 | 0 | FfdheGroup::from_params_trimming_leading_zeros(&self.dh_p.0, &self.dh_g.0) |
2034 | 0 | } |
2035 | | } |
2036 | | |
2037 | | impl Codec<'_> for ServerDhParams { |
2038 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2039 | 0 | self.dh_p.encode(bytes); |
2040 | 0 | self.dh_g.encode(bytes); |
2041 | 0 | self.dh_Ys.encode(bytes); |
2042 | 0 | } |
2043 | | |
2044 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2045 | | Ok(Self { |
2046 | 0 | dh_p: PayloadU16::read(r)?, |
2047 | 0 | dh_g: PayloadU16::read(r)?, |
2048 | 0 | dh_Ys: PayloadU16::read(r)?, |
2049 | | }) |
2050 | 0 | } |
2051 | | } |
2052 | | |
2053 | | #[allow(dead_code)] |
2054 | | #[derive(Debug)] |
2055 | | pub(crate) enum ServerKeyExchangeParams { |
2056 | | Ecdh(ServerEcdhParams), |
2057 | | Dh(ServerDhParams), |
2058 | | } |
2059 | | |
2060 | | impl ServerKeyExchangeParams { |
2061 | | #[cfg(feature = "tls12")] |
2062 | 0 | pub(crate) fn new(kx: &dyn ActiveKeyExchange) -> Self { |
2063 | 0 | match kx.group().key_exchange_algorithm() { |
2064 | 0 | KeyExchangeAlgorithm::DHE => Self::Dh(ServerDhParams::new(kx)), |
2065 | 0 | KeyExchangeAlgorithm::ECDHE => Self::Ecdh(ServerEcdhParams::new(kx)), |
2066 | | } |
2067 | 0 | } |
2068 | | |
2069 | | #[cfg(feature = "tls12")] |
2070 | 0 | pub(crate) fn pub_key(&self) -> &[u8] { |
2071 | 0 | match self { |
2072 | 0 | Self::Ecdh(ecdh) => &ecdh.public.0, |
2073 | 0 | Self::Dh(dh) => &dh.dh_Ys.0, |
2074 | | } |
2075 | 0 | } |
2076 | | |
2077 | 0 | pub(crate) fn encode(&self, buf: &mut Vec<u8>) { |
2078 | 0 | match self { |
2079 | 0 | Self::Ecdh(ecdh) => ecdh.encode(buf), |
2080 | 0 | Self::Dh(dh) => dh.encode(buf), |
2081 | | } |
2082 | 0 | } |
2083 | | } |
2084 | | |
2085 | | #[cfg(feature = "tls12")] |
2086 | | impl KxDecode<'_> for ServerKeyExchangeParams { |
2087 | 0 | fn decode(r: &mut Reader<'_>, algo: KeyExchangeAlgorithm) -> Result<Self, InvalidMessage> { |
2088 | | use KeyExchangeAlgorithm::*; |
2089 | 0 | Ok(match algo { |
2090 | 0 | ECDHE => Self::Ecdh(ServerEcdhParams::read(r)?), |
2091 | 0 | DHE => Self::Dh(ServerDhParams::read(r)?), |
2092 | | }) |
2093 | 0 | } |
2094 | | } |
2095 | | |
2096 | | #[derive(Debug)] |
2097 | | pub(crate) struct ServerKeyExchange { |
2098 | | pub(crate) params: ServerKeyExchangeParams, |
2099 | | pub(crate) dss: DigitallySignedStruct, |
2100 | | } |
2101 | | |
2102 | | impl ServerKeyExchange { |
2103 | 0 | pub(crate) fn encode(&self, buf: &mut Vec<u8>) { |
2104 | 0 | self.params.encode(buf); |
2105 | 0 | self.dss.encode(buf); |
2106 | 0 | } |
2107 | | } |
2108 | | |
2109 | | #[derive(Debug)] |
2110 | | pub(crate) enum ServerKeyExchangePayload { |
2111 | | Known(ServerKeyExchange), |
2112 | | Unknown(Payload<'static>), |
2113 | | } |
2114 | | |
2115 | | impl From<ServerKeyExchange> for ServerKeyExchangePayload { |
2116 | 0 | fn from(value: ServerKeyExchange) -> Self { |
2117 | 0 | Self::Known(value) |
2118 | 0 | } |
2119 | | } |
2120 | | |
2121 | | impl Codec<'_> for ServerKeyExchangePayload { |
2122 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2123 | 0 | match self { |
2124 | 0 | Self::Known(x) => x.encode(bytes), |
2125 | 0 | Self::Unknown(x) => x.encode(bytes), |
2126 | | } |
2127 | 0 | } |
2128 | | |
2129 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2130 | | // read as Unknown, fully parse when we know the |
2131 | | // KeyExchangeAlgorithm |
2132 | 0 | Ok(Self::Unknown(Payload::read(r).into_owned())) |
2133 | 0 | } |
2134 | | } |
2135 | | |
2136 | | impl ServerKeyExchangePayload { |
2137 | | #[cfg(feature = "tls12")] |
2138 | 0 | pub(crate) fn unwrap_given_kxa(&self, kxa: KeyExchangeAlgorithm) -> Option<ServerKeyExchange> { |
2139 | 0 | if let Self::Unknown(unk) = self { |
2140 | 0 | let mut rd = Reader::init(unk.bytes()); |
2141 | | |
2142 | 0 | let result = ServerKeyExchange { |
2143 | 0 | params: ServerKeyExchangeParams::decode(&mut rd, kxa).ok()?, |
2144 | 0 | dss: DigitallySignedStruct::read(&mut rd).ok()?, |
2145 | | }; |
2146 | | |
2147 | 0 | if !rd.any_left() { |
2148 | 0 | return Some(result); |
2149 | 0 | }; |
2150 | 0 | } |
2151 | | |
2152 | 0 | None |
2153 | 0 | } |
2154 | | } |
2155 | | |
2156 | | /// RFC5246: `ClientCertificateType certificate_types<1..2^8-1>;` |
2157 | | impl TlsListElement for ClientCertificateType { |
2158 | | const SIZE_LEN: ListLength = ListLength::NonZeroU8 { |
2159 | | empty_error: InvalidMessage::IllegalEmptyList("ClientCertificateTypes"), |
2160 | | }; |
2161 | | } |
2162 | | |
2163 | | wrapped_payload!( |
2164 | | /// A `DistinguishedName` is a `Vec<u8>` wrapped in internal types. |
2165 | | /// |
2166 | | /// It contains the DER or BER encoded [`Subject` field from RFC 5280](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.6) |
2167 | | /// for a single certificate. The Subject field is [encoded as an RFC 5280 `Name`](https://datatracker.ietf.org/doc/html/rfc5280#page-116). |
2168 | | /// It can be decoded using [x509-parser's FromDer trait](https://docs.rs/x509-parser/latest/x509_parser/prelude/trait.FromDer.html). |
2169 | | /// |
2170 | | /// ```ignore |
2171 | | /// for name in distinguished_names { |
2172 | | /// use x509_parser::prelude::FromDer; |
2173 | | /// println!("{}", x509_parser::x509::X509Name::from_der(&name.0)?.1); |
2174 | | /// } |
2175 | | /// ``` |
2176 | | /// |
2177 | | /// The TLS encoding is defined in RFC5246: `opaque DistinguishedName<1..2^16-1>;` |
2178 | | pub struct DistinguishedName, |
2179 | | PayloadU16<NonEmpty>, |
2180 | | ); |
2181 | | |
2182 | | impl DistinguishedName { |
2183 | | /// Create a [`DistinguishedName`] after prepending its outer SEQUENCE encoding. |
2184 | | /// |
2185 | | /// This can be decoded using [x509-parser's FromDer trait](https://docs.rs/x509-parser/latest/x509_parser/prelude/trait.FromDer.html). |
2186 | | /// |
2187 | | /// ```ignore |
2188 | | /// use x509_parser::prelude::FromDer; |
2189 | | /// println!("{}", x509_parser::x509::X509Name::from_der(dn.as_ref())?.1); |
2190 | | /// ``` |
2191 | 0 | pub fn in_sequence(bytes: &[u8]) -> Self { |
2192 | 0 | Self(PayloadU16::new(wrap_in_sequence(bytes))) |
2193 | 0 | } |
2194 | | } |
2195 | | |
2196 | | /// RFC8446: `DistinguishedName authorities<3..2^16-1>;` however, |
2197 | | /// RFC5246: `DistinguishedName certificate_authorities<0..2^16-1>;` |
2198 | | impl TlsListElement for DistinguishedName { |
2199 | | const SIZE_LEN: ListLength = ListLength::U16; |
2200 | | } |
2201 | | |
2202 | | #[derive(Debug)] |
2203 | | pub(crate) struct CertificateRequestPayload { |
2204 | | pub(crate) certtypes: Vec<ClientCertificateType>, |
2205 | | pub(crate) sigschemes: Vec<SignatureScheme>, |
2206 | | pub(crate) canames: Vec<DistinguishedName>, |
2207 | | } |
2208 | | |
2209 | | impl Codec<'_> for CertificateRequestPayload { |
2210 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2211 | 0 | self.certtypes.encode(bytes); |
2212 | 0 | self.sigschemes.encode(bytes); |
2213 | 0 | self.canames.encode(bytes); |
2214 | 0 | } |
2215 | | |
2216 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2217 | 0 | let certtypes = Vec::read(r)?; |
2218 | 0 | let sigschemes = Vec::read(r)?; |
2219 | 0 | let canames = Vec::read(r)?; |
2220 | | |
2221 | 0 | if sigschemes.is_empty() { |
2222 | 0 | warn!("meaningless CertificateRequest message"); |
2223 | 0 | Err(InvalidMessage::NoSignatureSchemes) |
2224 | | } else { |
2225 | 0 | Ok(Self { |
2226 | 0 | certtypes, |
2227 | 0 | sigschemes, |
2228 | 0 | canames, |
2229 | 0 | }) |
2230 | | } |
2231 | 0 | } |
2232 | | } |
2233 | | |
2234 | | extension_struct! { |
2235 | | pub(crate) struct CertificateRequestExtensions { |
2236 | | ExtensionType::SignatureAlgorithms => |
2237 | | pub(crate) signature_algorithms: Option<Vec<SignatureScheme>>, |
2238 | | |
2239 | | ExtensionType::CertificateAuthorities => |
2240 | | pub(crate) authority_names: Option<Vec<DistinguishedName>>, |
2241 | | |
2242 | | ExtensionType::CompressCertificate => |
2243 | | pub(crate) certificate_compression_algorithms: Option<Vec<CertificateCompressionAlgorithm>>, |
2244 | | } |
2245 | | } |
2246 | | |
2247 | | impl Codec<'_> for CertificateRequestExtensions { |
2248 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2249 | 0 | let extensions = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
2250 | | |
2251 | 0 | for ext in Self::ALL_EXTENSIONS { |
2252 | 0 | self.encode_one(*ext, extensions.buf); |
2253 | 0 | } |
2254 | 0 | } |
2255 | | |
2256 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2257 | 0 | let mut out = Self::default(); |
2258 | | |
2259 | 0 | let mut checker = DuplicateExtensionChecker::new(); |
2260 | | |
2261 | 0 | let len = usize::from(u16::read(r)?); |
2262 | 0 | let mut sub = r.sub(len)?; |
2263 | | |
2264 | 0 | while sub.any_left() { |
2265 | 0 | out.read_one(&mut sub, |unknown| checker.check(unknown))?; |
2266 | | } |
2267 | | |
2268 | 0 | if out |
2269 | 0 | .signature_algorithms |
2270 | 0 | .as_ref() |
2271 | 0 | .map(|algs| algs.is_empty()) |
2272 | 0 | .unwrap_or_default() |
2273 | | { |
2274 | 0 | return Err(InvalidMessage::NoSignatureSchemes); |
2275 | 0 | } |
2276 | | |
2277 | 0 | Ok(out) |
2278 | 0 | } |
2279 | | } |
2280 | | |
2281 | | #[derive(Debug)] |
2282 | | pub(crate) struct CertificateRequestPayloadTls13 { |
2283 | | pub(crate) context: PayloadU8, |
2284 | | pub(crate) extensions: CertificateRequestExtensions, |
2285 | | } |
2286 | | |
2287 | | impl Codec<'_> for CertificateRequestPayloadTls13 { |
2288 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2289 | 0 | self.context.encode(bytes); |
2290 | 0 | self.extensions.encode(bytes); |
2291 | 0 | } |
2292 | | |
2293 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2294 | 0 | let context = PayloadU8::read(r)?; |
2295 | 0 | let extensions = CertificateRequestExtensions::read(r)?; |
2296 | | |
2297 | 0 | Ok(Self { |
2298 | 0 | context, |
2299 | 0 | extensions, |
2300 | 0 | }) |
2301 | 0 | } |
2302 | | } |
2303 | | |
2304 | | // -- NewSessionTicket -- |
2305 | | #[derive(Debug)] |
2306 | | pub(crate) struct NewSessionTicketPayload { |
2307 | | pub(crate) lifetime_hint: u32, |
2308 | | // Tickets can be large (KB), so we deserialise this straight |
2309 | | // into an Arc, so it can be passed directly into the client's |
2310 | | // session object without copying. |
2311 | | pub(crate) ticket: Arc<PayloadU16>, |
2312 | | } |
2313 | | |
2314 | | impl NewSessionTicketPayload { |
2315 | | #[cfg(feature = "tls12")] |
2316 | 0 | pub(crate) fn new(lifetime_hint: u32, ticket: Vec<u8>) -> Self { |
2317 | 0 | Self { |
2318 | 0 | lifetime_hint, |
2319 | 0 | ticket: Arc::new(PayloadU16::new(ticket)), |
2320 | 0 | } |
2321 | 0 | } |
2322 | | } |
2323 | | |
2324 | | impl Codec<'_> for NewSessionTicketPayload { |
2325 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2326 | 0 | self.lifetime_hint.encode(bytes); |
2327 | 0 | self.ticket.encode(bytes); |
2328 | 0 | } |
2329 | | |
2330 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2331 | 0 | let lifetime = u32::read(r)?; |
2332 | 0 | let ticket = Arc::new(PayloadU16::read(r)?); |
2333 | | |
2334 | 0 | Ok(Self { |
2335 | 0 | lifetime_hint: lifetime, |
2336 | 0 | ticket, |
2337 | 0 | }) |
2338 | 0 | } |
2339 | | } |
2340 | | |
2341 | | // -- NewSessionTicket electric boogaloo -- |
2342 | | extension_struct! { |
2343 | | pub(crate) struct NewSessionTicketExtensions { |
2344 | | ExtensionType::EarlyData => |
2345 | | pub(crate) max_early_data_size: Option<u32>, |
2346 | | } |
2347 | | } |
2348 | | |
2349 | | impl Codec<'_> for NewSessionTicketExtensions { |
2350 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2351 | 0 | let extensions = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
2352 | | |
2353 | 0 | for ext in Self::ALL_EXTENSIONS { |
2354 | 0 | self.encode_one(*ext, extensions.buf); |
2355 | 0 | } |
2356 | 0 | } |
2357 | | |
2358 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2359 | 0 | let mut out = Self::default(); |
2360 | | |
2361 | 0 | let mut checker = DuplicateExtensionChecker::new(); |
2362 | | |
2363 | 0 | let len = usize::from(u16::read(r)?); |
2364 | 0 | let mut sub = r.sub(len)?; |
2365 | | |
2366 | 0 | while sub.any_left() { |
2367 | 0 | out.read_one(&mut sub, |unknown| checker.check(unknown))?; |
2368 | | } |
2369 | | |
2370 | 0 | Ok(out) |
2371 | 0 | } |
2372 | | } |
2373 | | |
2374 | | #[derive(Debug)] |
2375 | | pub(crate) struct NewSessionTicketPayloadTls13 { |
2376 | | pub(crate) lifetime: u32, |
2377 | | pub(crate) age_add: u32, |
2378 | | pub(crate) nonce: PayloadU8, |
2379 | | pub(crate) ticket: Arc<PayloadU16>, |
2380 | | pub(crate) extensions: NewSessionTicketExtensions, |
2381 | | } |
2382 | | |
2383 | | impl NewSessionTicketPayloadTls13 { |
2384 | 0 | pub(crate) fn new(lifetime: u32, age_add: u32, nonce: Vec<u8>, ticket: Vec<u8>) -> Self { |
2385 | 0 | Self { |
2386 | 0 | lifetime, |
2387 | 0 | age_add, |
2388 | 0 | nonce: PayloadU8::new(nonce), |
2389 | 0 | ticket: Arc::new(PayloadU16::new(ticket)), |
2390 | 0 | extensions: NewSessionTicketExtensions::default(), |
2391 | 0 | } |
2392 | 0 | } |
2393 | | } |
2394 | | |
2395 | | impl Codec<'_> for NewSessionTicketPayloadTls13 { |
2396 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2397 | 0 | self.lifetime.encode(bytes); |
2398 | 0 | self.age_add.encode(bytes); |
2399 | 0 | self.nonce.encode(bytes); |
2400 | 0 | self.ticket.encode(bytes); |
2401 | 0 | self.extensions.encode(bytes); |
2402 | 0 | } |
2403 | | |
2404 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2405 | 0 | let lifetime = u32::read(r)?; |
2406 | 0 | let age_add = u32::read(r)?; |
2407 | 0 | let nonce = PayloadU8::read(r)?; |
2408 | | // nb. RFC8446: `opaque ticket<1..2^16-1>;` |
2409 | 0 | let ticket = Arc::new(match PayloadU16::<NonEmpty>::read(r) { |
2410 | 0 | Err(InvalidMessage::IllegalEmptyValue) => Err(InvalidMessage::EmptyTicketValue), |
2411 | 0 | Err(err) => Err(err), |
2412 | 0 | Ok(pl) => Ok(PayloadU16::new(pl.0)), |
2413 | 0 | }?); |
2414 | 0 | let extensions = NewSessionTicketExtensions::read(r)?; |
2415 | | |
2416 | 0 | Ok(Self { |
2417 | 0 | lifetime, |
2418 | 0 | age_add, |
2419 | 0 | nonce, |
2420 | 0 | ticket, |
2421 | 0 | extensions, |
2422 | 0 | }) |
2423 | 0 | } |
2424 | | } |
2425 | | |
2426 | | // -- RFC6066 certificate status types |
2427 | | |
2428 | | /// Only supports OCSP |
2429 | | #[derive(Clone, Debug)] |
2430 | | pub(crate) struct CertificateStatus<'a> { |
2431 | | pub(crate) ocsp_response: PayloadU24<'a>, |
2432 | | } |
2433 | | |
2434 | | impl<'a> Codec<'a> for CertificateStatus<'a> { |
2435 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2436 | 0 | CertificateStatusType::OCSP.encode(bytes); |
2437 | 0 | self.ocsp_response.encode(bytes); |
2438 | 0 | } |
2439 | | |
2440 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
2441 | 0 | let typ = CertificateStatusType::read(r)?; |
2442 | | |
2443 | 0 | match typ { |
2444 | | CertificateStatusType::OCSP => Ok(Self { |
2445 | 0 | ocsp_response: PayloadU24::read(r)?, |
2446 | | }), |
2447 | 0 | _ => Err(InvalidMessage::InvalidCertificateStatusType), |
2448 | | } |
2449 | 0 | } |
2450 | | } |
2451 | | |
2452 | | impl<'a> CertificateStatus<'a> { |
2453 | 0 | pub(crate) fn new(ocsp: &'a [u8]) -> Self { |
2454 | 0 | CertificateStatus { |
2455 | 0 | ocsp_response: PayloadU24(Payload::Borrowed(ocsp)), |
2456 | 0 | } |
2457 | 0 | } |
2458 | | |
2459 | | #[cfg(feature = "tls12")] |
2460 | 0 | pub(crate) fn into_inner(self) -> Vec<u8> { |
2461 | 0 | self.ocsp_response.0.into_vec() |
2462 | 0 | } |
2463 | | |
2464 | 0 | pub(crate) fn into_owned(self) -> CertificateStatus<'static> { |
2465 | 0 | CertificateStatus { |
2466 | 0 | ocsp_response: self.ocsp_response.into_owned(), |
2467 | 0 | } |
2468 | 0 | } |
2469 | | } |
2470 | | |
2471 | | // -- RFC8879 compressed certificates |
2472 | | |
2473 | | #[derive(Debug)] |
2474 | | pub(crate) struct CompressedCertificatePayload<'a> { |
2475 | | pub(crate) alg: CertificateCompressionAlgorithm, |
2476 | | pub(crate) uncompressed_len: u32, |
2477 | | pub(crate) compressed: PayloadU24<'a>, |
2478 | | } |
2479 | | |
2480 | | impl<'a> Codec<'a> for CompressedCertificatePayload<'a> { |
2481 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2482 | 0 | self.alg.encode(bytes); |
2483 | 0 | codec::u24(self.uncompressed_len).encode(bytes); |
2484 | 0 | self.compressed.encode(bytes); |
2485 | 0 | } |
2486 | | |
2487 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
2488 | | Ok(Self { |
2489 | 0 | alg: CertificateCompressionAlgorithm::read(r)?, |
2490 | 0 | uncompressed_len: codec::u24::read(r)?.0, |
2491 | 0 | compressed: PayloadU24::read(r)?, |
2492 | | }) |
2493 | 0 | } |
2494 | | } |
2495 | | |
2496 | | impl CompressedCertificatePayload<'_> { |
2497 | 0 | fn into_owned(self) -> CompressedCertificatePayload<'static> { |
2498 | 0 | CompressedCertificatePayload { |
2499 | 0 | compressed: self.compressed.into_owned(), |
2500 | 0 | ..self |
2501 | 0 | } |
2502 | 0 | } |
2503 | | |
2504 | 0 | pub(crate) fn as_borrowed(&self) -> CompressedCertificatePayload<'_> { |
2505 | 0 | CompressedCertificatePayload { |
2506 | 0 | alg: self.alg, |
2507 | 0 | uncompressed_len: self.uncompressed_len, |
2508 | 0 | compressed: PayloadU24(Payload::Borrowed(self.compressed.0.bytes())), |
2509 | 0 | } |
2510 | 0 | } |
2511 | | } |
2512 | | |
2513 | | #[derive(Debug)] |
2514 | | pub(crate) enum HandshakePayload<'a> { |
2515 | | HelloRequest, |
2516 | | ClientHello(ClientHelloPayload), |
2517 | | ServerHello(ServerHelloPayload), |
2518 | | HelloRetryRequest(HelloRetryRequest), |
2519 | | Certificate(CertificateChain<'a>), |
2520 | | CertificateTls13(CertificatePayloadTls13<'a>), |
2521 | | CompressedCertificate(CompressedCertificatePayload<'a>), |
2522 | | ServerKeyExchange(ServerKeyExchangePayload), |
2523 | | CertificateRequest(CertificateRequestPayload), |
2524 | | CertificateRequestTls13(CertificateRequestPayloadTls13), |
2525 | | CertificateVerify(DigitallySignedStruct), |
2526 | | ServerHelloDone, |
2527 | | EndOfEarlyData, |
2528 | | ClientKeyExchange(Payload<'a>), |
2529 | | NewSessionTicket(NewSessionTicketPayload), |
2530 | | NewSessionTicketTls13(NewSessionTicketPayloadTls13), |
2531 | | EncryptedExtensions(Box<ServerExtensions<'a>>), |
2532 | | KeyUpdate(KeyUpdateRequest), |
2533 | | Finished(Payload<'a>), |
2534 | | CertificateStatus(CertificateStatus<'a>), |
2535 | | MessageHash(Payload<'a>), |
2536 | | Unknown((HandshakeType, Payload<'a>)), |
2537 | | } |
2538 | | |
2539 | | impl HandshakePayload<'_> { |
2540 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2541 | | use self::HandshakePayload::*; |
2542 | 0 | match self { |
2543 | 0 | HelloRequest | ServerHelloDone | EndOfEarlyData => {} |
2544 | 0 | ClientHello(x) => x.encode(bytes), |
2545 | 0 | ServerHello(x) => x.encode(bytes), |
2546 | 0 | HelloRetryRequest(x) => x.encode(bytes), |
2547 | 0 | Certificate(x) => x.encode(bytes), |
2548 | 0 | CertificateTls13(x) => x.encode(bytes), |
2549 | 0 | CompressedCertificate(x) => x.encode(bytes), |
2550 | 0 | ServerKeyExchange(x) => x.encode(bytes), |
2551 | 0 | ClientKeyExchange(x) => x.encode(bytes), |
2552 | 0 | CertificateRequest(x) => x.encode(bytes), |
2553 | 0 | CertificateRequestTls13(x) => x.encode(bytes), |
2554 | 0 | CertificateVerify(x) => x.encode(bytes), |
2555 | 0 | NewSessionTicket(x) => x.encode(bytes), |
2556 | 0 | NewSessionTicketTls13(x) => x.encode(bytes), |
2557 | 0 | EncryptedExtensions(x) => x.encode(bytes), |
2558 | 0 | KeyUpdate(x) => x.encode(bytes), |
2559 | 0 | Finished(x) => x.encode(bytes), |
2560 | 0 | CertificateStatus(x) => x.encode(bytes), |
2561 | 0 | MessageHash(x) => x.encode(bytes), |
2562 | 0 | Unknown((_, x)) => x.encode(bytes), |
2563 | | } |
2564 | 0 | } |
2565 | | |
2566 | 0 | pub(crate) fn handshake_type(&self) -> HandshakeType { |
2567 | | use self::HandshakePayload::*; |
2568 | 0 | match self { |
2569 | 0 | HelloRequest => HandshakeType::HelloRequest, |
2570 | 0 | ClientHello(_) => HandshakeType::ClientHello, |
2571 | 0 | ServerHello(_) => HandshakeType::ServerHello, |
2572 | 0 | HelloRetryRequest(_) => HandshakeType::HelloRetryRequest, |
2573 | 0 | Certificate(_) | CertificateTls13(_) => HandshakeType::Certificate, |
2574 | 0 | CompressedCertificate(_) => HandshakeType::CompressedCertificate, |
2575 | 0 | ServerKeyExchange(_) => HandshakeType::ServerKeyExchange, |
2576 | 0 | CertificateRequest(_) | CertificateRequestTls13(_) => HandshakeType::CertificateRequest, |
2577 | 0 | CertificateVerify(_) => HandshakeType::CertificateVerify, |
2578 | 0 | ServerHelloDone => HandshakeType::ServerHelloDone, |
2579 | 0 | EndOfEarlyData => HandshakeType::EndOfEarlyData, |
2580 | 0 | ClientKeyExchange(_) => HandshakeType::ClientKeyExchange, |
2581 | 0 | NewSessionTicket(_) | NewSessionTicketTls13(_) => HandshakeType::NewSessionTicket, |
2582 | 0 | EncryptedExtensions(_) => HandshakeType::EncryptedExtensions, |
2583 | 0 | KeyUpdate(_) => HandshakeType::KeyUpdate, |
2584 | 0 | Finished(_) => HandshakeType::Finished, |
2585 | 0 | CertificateStatus(_) => HandshakeType::CertificateStatus, |
2586 | 0 | MessageHash(_) => HandshakeType::MessageHash, |
2587 | 0 | Unknown((t, _)) => *t, |
2588 | | } |
2589 | 0 | } |
2590 | | |
2591 | 0 | fn wire_handshake_type(&self) -> HandshakeType { |
2592 | 0 | match self.handshake_type() { |
2593 | | // A `HelloRetryRequest` appears on the wire as a `ServerHello` with a magic `random` value. |
2594 | 0 | HandshakeType::HelloRetryRequest => HandshakeType::ServerHello, |
2595 | 0 | other => other, |
2596 | | } |
2597 | 0 | } |
2598 | | |
2599 | 0 | fn into_owned(self) -> HandshakePayload<'static> { |
2600 | | use HandshakePayload::*; |
2601 | | |
2602 | 0 | match self { |
2603 | 0 | HelloRequest => HelloRequest, |
2604 | 0 | ClientHello(x) => ClientHello(x), |
2605 | 0 | ServerHello(x) => ServerHello(x), |
2606 | 0 | HelloRetryRequest(x) => HelloRetryRequest(x), |
2607 | 0 | Certificate(x) => Certificate(x.into_owned()), |
2608 | 0 | CertificateTls13(x) => CertificateTls13(x.into_owned()), |
2609 | 0 | CompressedCertificate(x) => CompressedCertificate(x.into_owned()), |
2610 | 0 | ServerKeyExchange(x) => ServerKeyExchange(x), |
2611 | 0 | CertificateRequest(x) => CertificateRequest(x), |
2612 | 0 | CertificateRequestTls13(x) => CertificateRequestTls13(x), |
2613 | 0 | CertificateVerify(x) => CertificateVerify(x), |
2614 | 0 | ServerHelloDone => ServerHelloDone, |
2615 | 0 | EndOfEarlyData => EndOfEarlyData, |
2616 | 0 | ClientKeyExchange(x) => ClientKeyExchange(x.into_owned()), |
2617 | 0 | NewSessionTicket(x) => NewSessionTicket(x), |
2618 | 0 | NewSessionTicketTls13(x) => NewSessionTicketTls13(x), |
2619 | 0 | EncryptedExtensions(x) => EncryptedExtensions(Box::new(x.into_owned())), |
2620 | 0 | KeyUpdate(x) => KeyUpdate(x), |
2621 | 0 | Finished(x) => Finished(x.into_owned()), |
2622 | 0 | CertificateStatus(x) => CertificateStatus(x.into_owned()), |
2623 | 0 | MessageHash(x) => MessageHash(x.into_owned()), |
2624 | 0 | Unknown((t, x)) => Unknown((t, x.into_owned())), |
2625 | | } |
2626 | 0 | } |
2627 | | } |
2628 | | |
2629 | | #[derive(Debug)] |
2630 | | pub struct HandshakeMessagePayload<'a>(pub(crate) HandshakePayload<'a>); |
2631 | | |
2632 | | impl<'a> Codec<'a> for HandshakeMessagePayload<'a> { |
2633 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2634 | 0 | self.payload_encode(bytes, Encoding::Standard); |
2635 | 0 | } |
2636 | | |
2637 | 0 | fn read(r: &mut Reader<'a>) -> Result<Self, InvalidMessage> { |
2638 | 0 | Self::read_version(r, ProtocolVersion::TLSv1_2) |
2639 | 0 | } |
2640 | | } |
2641 | | |
2642 | | impl<'a> HandshakeMessagePayload<'a> { |
2643 | 0 | pub(crate) fn read_version( |
2644 | 0 | r: &mut Reader<'a>, |
2645 | 0 | vers: ProtocolVersion, |
2646 | 0 | ) -> Result<Self, InvalidMessage> { |
2647 | 0 | let typ = HandshakeType::read(r)?; |
2648 | 0 | let len = codec::u24::read(r)?.0 as usize; |
2649 | 0 | let mut sub = r.sub(len)?; |
2650 | | |
2651 | 0 | let payload = match typ { |
2652 | 0 | HandshakeType::HelloRequest if sub.left() == 0 => HandshakePayload::HelloRequest, |
2653 | | HandshakeType::ClientHello => { |
2654 | 0 | HandshakePayload::ClientHello(ClientHelloPayload::read(&mut sub)?) |
2655 | | } |
2656 | | HandshakeType::ServerHello => { |
2657 | 0 | let version = ProtocolVersion::read(&mut sub)?; |
2658 | 0 | let random = Random::read(&mut sub)?; |
2659 | | |
2660 | 0 | if random == HELLO_RETRY_REQUEST_RANDOM { |
2661 | 0 | let mut hrr = HelloRetryRequest::read(&mut sub)?; |
2662 | 0 | hrr.legacy_version = version; |
2663 | 0 | HandshakePayload::HelloRetryRequest(hrr) |
2664 | | } else { |
2665 | 0 | let mut shp = ServerHelloPayload::read(&mut sub)?; |
2666 | 0 | shp.legacy_version = version; |
2667 | 0 | shp.random = random; |
2668 | 0 | HandshakePayload::ServerHello(shp) |
2669 | | } |
2670 | | } |
2671 | 0 | HandshakeType::Certificate if vers == ProtocolVersion::TLSv1_3 => { |
2672 | 0 | let p = CertificatePayloadTls13::read(&mut sub)?; |
2673 | 0 | HandshakePayload::CertificateTls13(p) |
2674 | | } |
2675 | | HandshakeType::Certificate => { |
2676 | 0 | HandshakePayload::Certificate(CertificateChain::read(&mut sub)?) |
2677 | | } |
2678 | | HandshakeType::ServerKeyExchange => { |
2679 | 0 | let p = ServerKeyExchangePayload::read(&mut sub)?; |
2680 | 0 | HandshakePayload::ServerKeyExchange(p) |
2681 | | } |
2682 | | HandshakeType::ServerHelloDone => { |
2683 | 0 | sub.expect_empty("ServerHelloDone")?; |
2684 | 0 | HandshakePayload::ServerHelloDone |
2685 | | } |
2686 | | HandshakeType::ClientKeyExchange => { |
2687 | 0 | HandshakePayload::ClientKeyExchange(Payload::read(&mut sub)) |
2688 | | } |
2689 | 0 | HandshakeType::CertificateRequest if vers == ProtocolVersion::TLSv1_3 => { |
2690 | 0 | let p = CertificateRequestPayloadTls13::read(&mut sub)?; |
2691 | 0 | HandshakePayload::CertificateRequestTls13(p) |
2692 | | } |
2693 | | HandshakeType::CertificateRequest => { |
2694 | 0 | let p = CertificateRequestPayload::read(&mut sub)?; |
2695 | 0 | HandshakePayload::CertificateRequest(p) |
2696 | | } |
2697 | | HandshakeType::CompressedCertificate => HandshakePayload::CompressedCertificate( |
2698 | 0 | CompressedCertificatePayload::read(&mut sub)?, |
2699 | | ), |
2700 | | HandshakeType::CertificateVerify => { |
2701 | 0 | HandshakePayload::CertificateVerify(DigitallySignedStruct::read(&mut sub)?) |
2702 | | } |
2703 | 0 | HandshakeType::NewSessionTicket if vers == ProtocolVersion::TLSv1_3 => { |
2704 | 0 | let p = NewSessionTicketPayloadTls13::read(&mut sub)?; |
2705 | 0 | HandshakePayload::NewSessionTicketTls13(p) |
2706 | | } |
2707 | | HandshakeType::NewSessionTicket => { |
2708 | 0 | let p = NewSessionTicketPayload::read(&mut sub)?; |
2709 | 0 | HandshakePayload::NewSessionTicket(p) |
2710 | | } |
2711 | | HandshakeType::EncryptedExtensions => { |
2712 | 0 | HandshakePayload::EncryptedExtensions(Box::new(ServerExtensions::read(&mut sub)?)) |
2713 | | } |
2714 | | HandshakeType::KeyUpdate => { |
2715 | 0 | HandshakePayload::KeyUpdate(KeyUpdateRequest::read(&mut sub)?) |
2716 | | } |
2717 | | HandshakeType::EndOfEarlyData => { |
2718 | 0 | sub.expect_empty("EndOfEarlyData")?; |
2719 | 0 | HandshakePayload::EndOfEarlyData |
2720 | | } |
2721 | 0 | HandshakeType::Finished => HandshakePayload::Finished(Payload::read(&mut sub)), |
2722 | | HandshakeType::CertificateStatus => { |
2723 | 0 | HandshakePayload::CertificateStatus(CertificateStatus::read(&mut sub)?) |
2724 | | } |
2725 | | HandshakeType::MessageHash => { |
2726 | | // does not appear on the wire |
2727 | 0 | return Err(InvalidMessage::UnexpectedMessage("MessageHash")); |
2728 | | } |
2729 | | HandshakeType::HelloRetryRequest => { |
2730 | | // not legal on wire |
2731 | 0 | return Err(InvalidMessage::UnexpectedMessage("HelloRetryRequest")); |
2732 | | } |
2733 | 0 | _ => HandshakePayload::Unknown((typ, Payload::read(&mut sub))), |
2734 | | }; |
2735 | | |
2736 | 0 | sub.expect_empty("HandshakeMessagePayload") |
2737 | 0 | .map(|_| Self(payload)) |
2738 | 0 | } |
2739 | | |
2740 | 0 | pub(crate) fn encoding_for_binder_signing(&self) -> Vec<u8> { |
2741 | 0 | let mut ret = self.get_encoding(); |
2742 | 0 | let ret_len = ret.len() - self.total_binder_length(); |
2743 | 0 | ret.truncate(ret_len); |
2744 | 0 | ret |
2745 | 0 | } |
2746 | | |
2747 | 0 | pub(crate) fn total_binder_length(&self) -> usize { |
2748 | 0 | match &self.0 { |
2749 | 0 | HandshakePayload::ClientHello(ch) => match &ch.preshared_key_offer { |
2750 | 0 | Some(offer) => { |
2751 | 0 | let mut binders_encoding = Vec::new(); |
2752 | 0 | offer |
2753 | 0 | .binders |
2754 | 0 | .encode(&mut binders_encoding); |
2755 | 0 | binders_encoding.len() |
2756 | | } |
2757 | 0 | _ => 0, |
2758 | | }, |
2759 | 0 | _ => 0, |
2760 | | } |
2761 | 0 | } |
2762 | | |
2763 | 0 | pub(crate) fn payload_encode(&self, bytes: &mut Vec<u8>, encoding: Encoding) { |
2764 | | // output type, length, and encoded payload |
2765 | 0 | self.0 |
2766 | 0 | .wire_handshake_type() |
2767 | 0 | .encode(bytes); |
2768 | | |
2769 | 0 | let nested = LengthPrefixedBuffer::new( |
2770 | 0 | ListLength::U24 { |
2771 | 0 | max: usize::MAX, |
2772 | 0 | error: InvalidMessage::MessageTooLarge, |
2773 | 0 | }, |
2774 | 0 | bytes, |
2775 | | ); |
2776 | | |
2777 | 0 | match &self.0 { |
2778 | | // for Server Hello and HelloRetryRequest payloads we need to encode the payload |
2779 | | // differently based on the purpose of the encoding. |
2780 | 0 | HandshakePayload::ServerHello(payload) => payload.payload_encode(nested.buf, encoding), |
2781 | 0 | HandshakePayload::HelloRetryRequest(payload) => { |
2782 | 0 | payload.payload_encode(nested.buf, encoding) |
2783 | | } |
2784 | | |
2785 | | // All other payload types are encoded the same regardless of purpose. |
2786 | 0 | _ => self.0.encode(nested.buf), |
2787 | | } |
2788 | 0 | } |
2789 | | |
2790 | 0 | pub(crate) fn build_handshake_hash(hash: &[u8]) -> Self { |
2791 | 0 | Self(HandshakePayload::MessageHash(Payload::new(hash.to_vec()))) |
2792 | 0 | } |
2793 | | |
2794 | 0 | pub(crate) fn into_owned(self) -> HandshakeMessagePayload<'static> { |
2795 | 0 | HandshakeMessagePayload(self.0.into_owned()) |
2796 | 0 | } |
2797 | | } |
2798 | | |
2799 | | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
2800 | | pub struct HpkeSymmetricCipherSuite { |
2801 | | pub kdf_id: HpkeKdf, |
2802 | | pub aead_id: HpkeAead, |
2803 | | } |
2804 | | |
2805 | | impl Codec<'_> for HpkeSymmetricCipherSuite { |
2806 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2807 | 0 | self.kdf_id.encode(bytes); |
2808 | 0 | self.aead_id.encode(bytes); |
2809 | 0 | } |
2810 | | |
2811 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2812 | | Ok(Self { |
2813 | 0 | kdf_id: HpkeKdf::read(r)?, |
2814 | 0 | aead_id: HpkeAead::read(r)?, |
2815 | | }) |
2816 | 0 | } |
2817 | | } |
2818 | | |
2819 | | /// draft-ietf-tls-esni-24: `HpkeSymmetricCipherSuite cipher_suites<4..2^16-4>;` |
2820 | | impl TlsListElement for HpkeSymmetricCipherSuite { |
2821 | | const SIZE_LEN: ListLength = ListLength::NonZeroU16 { |
2822 | | empty_error: InvalidMessage::IllegalEmptyList("HpkeSymmetricCipherSuites"), |
2823 | | }; |
2824 | | } |
2825 | | |
2826 | | #[derive(Clone, Debug, PartialEq)] |
2827 | | pub struct HpkeKeyConfig { |
2828 | | pub config_id: u8, |
2829 | | pub kem_id: HpkeKem, |
2830 | | /// draft-ietf-tls-esni-24: `opaque HpkePublicKey<1..2^16-1>;` |
2831 | | pub public_key: PayloadU16<NonEmpty>, |
2832 | | pub symmetric_cipher_suites: Vec<HpkeSymmetricCipherSuite>, |
2833 | | } |
2834 | | |
2835 | | impl Codec<'_> for HpkeKeyConfig { |
2836 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2837 | 0 | self.config_id.encode(bytes); |
2838 | 0 | self.kem_id.encode(bytes); |
2839 | 0 | self.public_key.encode(bytes); |
2840 | 0 | self.symmetric_cipher_suites |
2841 | 0 | .encode(bytes); |
2842 | 0 | } |
2843 | | |
2844 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2845 | | Ok(Self { |
2846 | 0 | config_id: u8::read(r)?, |
2847 | 0 | kem_id: HpkeKem::read(r)?, |
2848 | 0 | public_key: PayloadU16::read(r)?, |
2849 | 0 | symmetric_cipher_suites: Vec::<HpkeSymmetricCipherSuite>::read(r)?, |
2850 | | }) |
2851 | 0 | } |
2852 | | } |
2853 | | |
2854 | | #[derive(Clone, Debug, PartialEq)] |
2855 | | pub struct EchConfigContents { |
2856 | | pub key_config: HpkeKeyConfig, |
2857 | | pub maximum_name_length: u8, |
2858 | | pub public_name: DnsName<'static>, |
2859 | | pub extensions: Vec<EchConfigExtension>, |
2860 | | } |
2861 | | |
2862 | | impl EchConfigContents { |
2863 | | /// Returns true if there is more than one extension of a given |
2864 | | /// type. |
2865 | 0 | pub(crate) fn has_duplicate_extension(&self) -> bool { |
2866 | 0 | has_duplicates::<_, _, u16>( |
2867 | 0 | self.extensions |
2868 | 0 | .iter() |
2869 | 0 | .map(|ext| ext.ext_type()), |
2870 | | ) |
2871 | 0 | } |
2872 | | |
2873 | | /// Returns true if there is at least one mandatory unsupported extension. |
2874 | 0 | pub(crate) fn has_unknown_mandatory_extension(&self) -> bool { |
2875 | 0 | self.extensions |
2876 | 0 | .iter() |
2877 | | // An extension is considered mandatory if the high bit of its type is set. |
2878 | 0 | .any(|ext| { |
2879 | 0 | matches!(ext.ext_type(), ExtensionType::Unknown(_)) |
2880 | 0 | && u16::from(ext.ext_type()) & 0x8000 != 0 |
2881 | 0 | }) |
2882 | 0 | } |
2883 | | } |
2884 | | |
2885 | | impl Codec<'_> for EchConfigContents { |
2886 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2887 | 0 | self.key_config.encode(bytes); |
2888 | 0 | self.maximum_name_length.encode(bytes); |
2889 | 0 | let dns_name = &self.public_name.borrow(); |
2890 | 0 | PayloadU8::<MaybeEmpty>::encode_slice(dns_name.as_ref().as_ref(), bytes); |
2891 | 0 | self.extensions.encode(bytes); |
2892 | 0 | } |
2893 | | |
2894 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2895 | | Ok(Self { |
2896 | 0 | key_config: HpkeKeyConfig::read(r)?, |
2897 | 0 | maximum_name_length: u8::read(r)?, |
2898 | | public_name: { |
2899 | 0 | DnsName::try_from( |
2900 | 0 | PayloadU8::<MaybeEmpty>::read(r)? |
2901 | | .0 |
2902 | 0 | .as_slice(), |
2903 | | ) |
2904 | 0 | .map_err(|_| InvalidMessage::InvalidServerName)? |
2905 | 0 | .to_owned() |
2906 | | }, |
2907 | 0 | extensions: Vec::read(r)?, |
2908 | | }) |
2909 | 0 | } |
2910 | | } |
2911 | | |
2912 | | /// An encrypted client hello (ECH) config. |
2913 | | #[derive(Clone, Debug, PartialEq)] |
2914 | | pub enum EchConfigPayload { |
2915 | | /// A recognized V18 ECH configuration. |
2916 | | V18(EchConfigContents), |
2917 | | /// An unknown version ECH configuration. |
2918 | | Unknown { |
2919 | | version: EchVersion, |
2920 | | contents: PayloadU16, |
2921 | | }, |
2922 | | } |
2923 | | |
2924 | | impl TlsListElement for EchConfigPayload { |
2925 | | const SIZE_LEN: ListLength = ListLength::U16; |
2926 | | } |
2927 | | |
2928 | | impl Codec<'_> for EchConfigPayload { |
2929 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2930 | 0 | match self { |
2931 | 0 | Self::V18(c) => { |
2932 | 0 | // Write the version, the length, and the contents. |
2933 | 0 | EchVersion::V18.encode(bytes); |
2934 | 0 | let inner = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
2935 | 0 | c.encode(inner.buf); |
2936 | 0 | } |
2937 | 0 | Self::Unknown { version, contents } => { |
2938 | 0 | // Unknown configuration versions are opaque. |
2939 | 0 | version.encode(bytes); |
2940 | 0 | contents.encode(bytes); |
2941 | 0 | } |
2942 | | } |
2943 | 0 | } |
2944 | | |
2945 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2946 | 0 | let version = EchVersion::read(r)?; |
2947 | 0 | let length = u16::read(r)?; |
2948 | 0 | let mut contents = r.sub(length as usize)?; |
2949 | | |
2950 | 0 | Ok(match version { |
2951 | 0 | EchVersion::V18 => Self::V18(EchConfigContents::read(&mut contents)?), |
2952 | | _ => { |
2953 | | // Note: we don't PayloadU16::read() here because we've already read the length prefix. |
2954 | 0 | let data = PayloadU16::new(contents.rest().into()); |
2955 | 0 | Self::Unknown { |
2956 | 0 | version, |
2957 | 0 | contents: data, |
2958 | 0 | } |
2959 | | } |
2960 | | }) |
2961 | 0 | } |
2962 | | } |
2963 | | |
2964 | | #[derive(Clone, Debug, PartialEq)] |
2965 | | pub enum EchConfigExtension { |
2966 | | Unknown(UnknownExtension), |
2967 | | } |
2968 | | |
2969 | | impl EchConfigExtension { |
2970 | 0 | pub(crate) fn ext_type(&self) -> ExtensionType { |
2971 | 0 | match self { |
2972 | 0 | Self::Unknown(r) => r.typ, |
2973 | | } |
2974 | 0 | } |
2975 | | } |
2976 | | |
2977 | | impl Codec<'_> for EchConfigExtension { |
2978 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
2979 | 0 | self.ext_type().encode(bytes); |
2980 | | |
2981 | 0 | let nested = LengthPrefixedBuffer::new(ListLength::U16, bytes); |
2982 | 0 | match self { |
2983 | 0 | Self::Unknown(r) => r.encode(nested.buf), |
2984 | | } |
2985 | 0 | } |
2986 | | |
2987 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
2988 | 0 | let typ = ExtensionType::read(r)?; |
2989 | 0 | let len = u16::read(r)? as usize; |
2990 | 0 | let mut sub = r.sub(len)?; |
2991 | | |
2992 | | #[allow(clippy::match_single_binding)] // Future-proofing. |
2993 | 0 | let ext = match typ { |
2994 | 0 | _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)), |
2995 | | }; |
2996 | | |
2997 | 0 | sub.expect_empty("EchConfigExtension") |
2998 | 0 | .map(|_| ext) |
2999 | 0 | } |
3000 | | } |
3001 | | |
3002 | | impl TlsListElement for EchConfigExtension { |
3003 | | const SIZE_LEN: ListLength = ListLength::U16; |
3004 | | } |
3005 | | |
3006 | | /// Representation of the `ECHClientHello` client extension specified in |
3007 | | /// [draft-ietf-tls-esni Section 5]. |
3008 | | /// |
3009 | | /// [draft-ietf-tls-esni Section 5]: <https://www.ietf.org/archive/id/draft-ietf-tls-esni-18.html#section-5> |
3010 | | #[derive(Clone, Debug)] |
3011 | | pub(crate) enum EncryptedClientHello { |
3012 | | /// A `ECHClientHello` with type [EchClientHelloType::ClientHelloOuter]. |
3013 | | Outer(EncryptedClientHelloOuter), |
3014 | | /// An empty `ECHClientHello` with type [EchClientHelloType::ClientHelloInner]. |
3015 | | /// |
3016 | | /// This variant has no payload. |
3017 | | Inner, |
3018 | | } |
3019 | | |
3020 | | impl Codec<'_> for EncryptedClientHello { |
3021 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
3022 | 0 | match self { |
3023 | 0 | Self::Outer(payload) => { |
3024 | 0 | EchClientHelloType::ClientHelloOuter.encode(bytes); |
3025 | 0 | payload.encode(bytes); |
3026 | 0 | } |
3027 | 0 | Self::Inner => { |
3028 | 0 | EchClientHelloType::ClientHelloInner.encode(bytes); |
3029 | 0 | // Empty payload. |
3030 | 0 | } |
3031 | | } |
3032 | 0 | } |
3033 | | |
3034 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
3035 | 0 | match EchClientHelloType::read(r)? { |
3036 | | EchClientHelloType::ClientHelloOuter => { |
3037 | 0 | Ok(Self::Outer(EncryptedClientHelloOuter::read(r)?)) |
3038 | | } |
3039 | 0 | EchClientHelloType::ClientHelloInner => Ok(Self::Inner), |
3040 | 0 | _ => Err(InvalidMessage::InvalidContentType), |
3041 | | } |
3042 | 0 | } |
3043 | | } |
3044 | | |
3045 | | /// Representation of the ECHClientHello extension with type outer specified in |
3046 | | /// [draft-ietf-tls-esni Section 5]. |
3047 | | /// |
3048 | | /// [draft-ietf-tls-esni Section 5]: <https://www.ietf.org/archive/id/draft-ietf-tls-esni-18.html#section-5> |
3049 | | #[derive(Clone, Debug)] |
3050 | | pub(crate) struct EncryptedClientHelloOuter { |
3051 | | /// The cipher suite used to encrypt ClientHelloInner. Must match a value from |
3052 | | /// ECHConfigContents.cipher_suites list. |
3053 | | pub cipher_suite: HpkeSymmetricCipherSuite, |
3054 | | /// The ECHConfigContents.key_config.config_id for the chosen ECHConfig. |
3055 | | pub config_id: u8, |
3056 | | /// The HPKE encapsulated key, used by servers to decrypt the corresponding payload field. |
3057 | | /// This field is empty in a ClientHelloOuter sent in response to a HelloRetryRequest. |
3058 | | pub enc: PayloadU16, |
3059 | | /// The serialized and encrypted ClientHelloInner structure, encrypted using HPKE. |
3060 | | pub payload: PayloadU16<NonEmpty>, |
3061 | | } |
3062 | | |
3063 | | impl Codec<'_> for EncryptedClientHelloOuter { |
3064 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
3065 | 0 | self.cipher_suite.encode(bytes); |
3066 | 0 | self.config_id.encode(bytes); |
3067 | 0 | self.enc.encode(bytes); |
3068 | 0 | self.payload.encode(bytes); |
3069 | 0 | } |
3070 | | |
3071 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
3072 | | Ok(Self { |
3073 | 0 | cipher_suite: HpkeSymmetricCipherSuite::read(r)?, |
3074 | 0 | config_id: u8::read(r)?, |
3075 | 0 | enc: PayloadU16::read(r)?, |
3076 | 0 | payload: PayloadU16::read(r)?, |
3077 | | }) |
3078 | 0 | } |
3079 | | } |
3080 | | |
3081 | | /// Representation of the ECHEncryptedExtensions extension specified in |
3082 | | /// [draft-ietf-tls-esni Section 5]. |
3083 | | /// |
3084 | | /// [draft-ietf-tls-esni Section 5]: <https://www.ietf.org/archive/id/draft-ietf-tls-esni-18.html#section-5> |
3085 | | #[derive(Clone, Debug)] |
3086 | | pub(crate) struct ServerEncryptedClientHello { |
3087 | | pub(crate) retry_configs: Vec<EchConfigPayload>, |
3088 | | } |
3089 | | |
3090 | | impl Codec<'_> for ServerEncryptedClientHello { |
3091 | 0 | fn encode(&self, bytes: &mut Vec<u8>) { |
3092 | 0 | self.retry_configs.encode(bytes); |
3093 | 0 | } |
3094 | | |
3095 | 0 | fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> { |
3096 | | Ok(Self { |
3097 | 0 | retry_configs: Vec::<EchConfigPayload>::read(r)?, |
3098 | | }) |
3099 | 0 | } |
3100 | | } |
3101 | | |
3102 | | /// The method of encoding to use for a handshake message. |
3103 | | /// |
3104 | | /// In some cases a handshake message may be encoded differently depending on the purpose |
3105 | | /// the encoded message is being used for. |
3106 | | pub(crate) enum Encoding { |
3107 | | /// Standard RFC 8446 encoding. |
3108 | | Standard, |
3109 | | /// Encoding for ECH confirmation for HRR. |
3110 | | EchConfirmation, |
3111 | | /// Encoding for ECH inner client hello. |
3112 | | EchInnerHello { to_compress: Vec<ExtensionType> }, |
3113 | | } |
3114 | | |
3115 | 0 | fn has_duplicates<I: IntoIterator<Item = E>, E: Into<T>, T: Eq + Ord>(iter: I) -> bool { |
3116 | 0 | let mut seen = BTreeSet::new(); |
3117 | | |
3118 | 0 | for x in iter { |
3119 | 0 | if !seen.insert(x.into()) { |
3120 | 0 | return true; |
3121 | 0 | } |
3122 | | } |
3123 | | |
3124 | 0 | false |
3125 | 0 | } Unexecuted instantiation: rustls::msgs::handshake::has_duplicates::<core::iter::adapters::map::Map<core::slice::iter::Iter<rustls::msgs::handshake::KeyShareEntry>, <rustls::msgs::handshake::ClientHelloPayload>::has_keyshare_extension_with_duplicates::{closure#0}::{closure#0}>, u16, u16>Unexecuted instantiation: rustls::msgs::handshake::has_duplicates::<core::iter::adapters::map::Map<core::slice::iter::Iter<rustls::msgs::handshake::EchConfigExtension>, <rustls::msgs::handshake::EchConfigContents>::has_duplicate_extension::{closure#0}>, rustls::msgs::enums::ExtensionType, u16>Unexecuted instantiation: rustls::msgs::handshake::has_duplicates::<core::iter::adapters::cloned::Cloned<core::slice::iter::Iter<rustls::enums::CertificateCompressionAlgorithm>>, rustls::enums::CertificateCompressionAlgorithm, u16> |
3126 | | |
3127 | | struct DuplicateExtensionChecker(BTreeSet<u16>); |
3128 | | |
3129 | | impl DuplicateExtensionChecker { |
3130 | 0 | fn new() -> Self { |
3131 | 0 | Self(BTreeSet::new()) |
3132 | 0 | } |
3133 | | |
3134 | 0 | fn check(&mut self, typ: ExtensionType) -> Result<(), InvalidMessage> { |
3135 | 0 | let u = u16::from(typ); |
3136 | 0 | match self.0.insert(u) { |
3137 | 0 | true => Ok(()), |
3138 | 0 | false => Err(InvalidMessage::DuplicateExtension(u)), |
3139 | | } |
3140 | 0 | } |
3141 | | } |
3142 | | |
3143 | 0 | fn low_quality_integer_hash(mut x: u32) -> u32 { |
3144 | 0 | x = x |
3145 | 0 | .wrapping_add(0x7ed55d16) |
3146 | 0 | .wrapping_add(x << 12); |
3147 | 0 | x = (x ^ 0xc761c23c) ^ (x >> 19); |
3148 | 0 | x = x |
3149 | 0 | .wrapping_add(0x165667b1) |
3150 | 0 | .wrapping_add(x << 5); |
3151 | 0 | x = x.wrapping_add(0xd3a2646c) ^ (x << 9); |
3152 | 0 | x = x |
3153 | 0 | .wrapping_add(0xfd7046c5) |
3154 | 0 | .wrapping_add(x << 3); |
3155 | 0 | x = (x ^ 0xb55a4f09) ^ (x >> 16); |
3156 | 0 | x |
3157 | 0 | } |
3158 | | |
3159 | | #[cfg(test)] |
3160 | | mod tests { |
3161 | | use super::*; |
3162 | | |
3163 | | #[test] |
3164 | | fn test_ech_config_dupe_exts() { |
3165 | | let unknown_ext = EchConfigExtension::Unknown(UnknownExtension { |
3166 | | typ: ExtensionType::Unknown(0x42), |
3167 | | payload: Payload::new(vec![0x42]), |
3168 | | }); |
3169 | | let mut config = config_template(); |
3170 | | config |
3171 | | .extensions |
3172 | | .push(unknown_ext.clone()); |
3173 | | config.extensions.push(unknown_ext); |
3174 | | |
3175 | | assert!(config.has_duplicate_extension()); |
3176 | | assert!(!config.has_unknown_mandatory_extension()); |
3177 | | } |
3178 | | |
3179 | | #[test] |
3180 | | fn test_ech_config_mandatory_exts() { |
3181 | | let mandatory_unknown_ext = EchConfigExtension::Unknown(UnknownExtension { |
3182 | | typ: ExtensionType::Unknown(0x42 | 0x8000), // Note: high bit set. |
3183 | | payload: Payload::new(vec![0x42]), |
3184 | | }); |
3185 | | let mut config = config_template(); |
3186 | | config |
3187 | | .extensions |
3188 | | .push(mandatory_unknown_ext); |
3189 | | |
3190 | | assert!(!config.has_duplicate_extension()); |
3191 | | assert!(config.has_unknown_mandatory_extension()); |
3192 | | } |
3193 | | |
3194 | | fn config_template() -> EchConfigContents { |
3195 | | EchConfigContents { |
3196 | | key_config: HpkeKeyConfig { |
3197 | | config_id: 0, |
3198 | | kem_id: HpkeKem::DHKEM_P256_HKDF_SHA256, |
3199 | | public_key: PayloadU16::new(b"xxx".into()), |
3200 | | symmetric_cipher_suites: vec![HpkeSymmetricCipherSuite { |
3201 | | kdf_id: HpkeKdf::HKDF_SHA256, |
3202 | | aead_id: HpkeAead::AES_128_GCM, |
3203 | | }], |
3204 | | }, |
3205 | | maximum_name_length: 0, |
3206 | | public_name: DnsName::try_from("example.com").unwrap(), |
3207 | | extensions: vec![], |
3208 | | } |
3209 | | } |
3210 | | } |