Skip to main content

rustls/msgs/
handshake.rs

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