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