rustls/msgs/
handshake.rs

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