1 use crate::key;
2 use crate::msgs::base::{Payload, PayloadU16, PayloadU24, PayloadU8};
3 use crate::msgs::codec;
4 use crate::msgs::codec::{Codec, Reader};
5 use crate::msgs::enums::ECCurveType;
6 use crate::msgs::enums::PSKKeyExchangeMode;
7 use crate::msgs::enums::{CertificateStatusType, ClientCertificateType};
8 use crate::msgs::enums::{CipherSuite, Compression, ECPointFormat, ExtensionType};
9 use crate::msgs::enums::{HandshakeType, ProtocolVersion};
10 use crate::msgs::enums::{HashAlgorithm, ServerNameType, SignatureAlgorithm};
11 use crate::msgs::enums::{KeyUpdateRequest, NamedGroup, SignatureScheme};
12 use crate::rand;
13 
14 #[cfg(feature = "logging")]
15 use crate::log::warn;
16 
17 use std::collections;
18 use std::fmt;
19 
20 macro_rules! declare_u8_vec(
21   ($name:ident, $itemtype:ty) => {
22     pub type $name = Vec<$itemtype>;
23 
24     impl Codec for $name {
25       fn encode(&self, bytes: &mut Vec<u8>) {
26         codec::encode_vec_u8(bytes, self);
27       }
28 
29       fn read(r: &mut Reader) -> Option<Self> {
30         codec::read_vec_u8::<$itemtype>(r)
31       }
32     }
33   }
34 );
35 
36 macro_rules! declare_u16_vec(
37   ($name:ident, $itemtype:ty) => {
38     pub type $name = Vec<$itemtype>;
39 
40     impl Codec for $name {
41       fn encode(&self, bytes: &mut Vec<u8>) {
42         codec::encode_vec_u16(bytes, self);
43       }
44 
45       fn read(r: &mut Reader) -> Option<Self> {
46         codec::read_vec_u16::<$itemtype>(r)
47       }
48     }
49   }
50 );
51 
52 declare_u16_vec!(VecU16OfPayloadU8, PayloadU8);
53 declare_u16_vec!(VecU16OfPayloadU16, PayloadU16);
54 
55 #[derive(Clone, Copy, Debug, PartialEq)]
56 pub struct Random(pub [u8; 32]);
57 
58 static HELLO_RETRY_REQUEST_RANDOM: Random = Random([
59     0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91,
60     0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
61 ]);
62 
63 static ZERO_RANDOM: Random = Random([0u8; 32]);
64 
65 impl Codec for Random {
encode(&self, bytes: &mut Vec<u8>)66     fn encode(&self, bytes: &mut Vec<u8>) {
67         bytes.extend_from_slice(&self.0);
68     }
69 
read(r: &mut Reader) -> Option<Self>70     fn read(r: &mut Reader) -> Option<Self> {
71         let bytes = r.take(32)?;
72         let mut opaque = [0; 32];
73         opaque.clone_from_slice(bytes);
74 
75         Some(Self(opaque))
76     }
77 }
78 
79 impl Random {
new() -> Result<Self, rand::GetRandomFailed>80     pub fn new() -> Result<Self, rand::GetRandomFailed> {
81         let mut data = [0u8; 32];
82         rand::fill_random(&mut data)?;
83         Ok(Self(data))
84     }
85 
write_slice(&self, bytes: &mut [u8])86     pub fn write_slice(&self, bytes: &mut [u8]) {
87         let buf = self.get_encoding();
88         bytes.copy_from_slice(&buf);
89     }
90 }
91 
92 impl From<[u8; 32]> for Random {
93     #[inline]
from(bytes: [u8; 32]) -> Self94     fn from(bytes: [u8; 32]) -> Self {
95         Self(bytes)
96     }
97 }
98 
99 #[derive(Copy, Clone)]
100 pub struct SessionID {
101     len: usize,
102     data: [u8; 32],
103 }
104 
105 impl fmt::Debug for SessionID {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result106     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107         f.debug_tuple("SessionID")
108             .field(&&self.data[..self.len]) // must be `Sized` to cast to `dyn Debug`
109             .finish()
110     }
111 }
112 
113 impl PartialEq for SessionID {
eq(&self, other: &Self) -> bool114     fn eq(&self, other: &Self) -> bool {
115         if self.len != other.len {
116             return false;
117         }
118 
119         let mut diff = 0u8;
120         for i in 0..self.len {
121             diff |= self.data[i] ^ other.data[i]
122         }
123 
124         diff == 0u8
125     }
126 }
127 
128 impl Codec for SessionID {
encode(&self, bytes: &mut Vec<u8>)129     fn encode(&self, bytes: &mut Vec<u8>) {
130         debug_assert!(self.len <= 32);
131         bytes.push(self.len as u8);
132         bytes.extend_from_slice(&self.data[..self.len]);
133     }
134 
read(r: &mut Reader) -> Option<Self>135     fn read(r: &mut Reader) -> Option<Self> {
136         let len = u8::read(r)? as usize;
137         if len > 32 {
138             return None;
139         }
140 
141         let bytes = r.take(len)?;
142         let mut out = [0u8; 32];
143         out[..len].clone_from_slice(&bytes[..len]);
144 
145         Some(Self { data: out, len })
146     }
147 }
148 
149 impl SessionID {
random() -> Result<Self, rand::GetRandomFailed>150     pub fn random() -> Result<Self, rand::GetRandomFailed> {
151         let mut data = [0u8; 32];
152         rand::fill_random(&mut data)?;
153         Ok(Self { data, len: 32 })
154     }
155 
empty() -> Self156     pub fn empty() -> Self {
157         Self {
158             data: [0u8; 32],
159             len: 0,
160         }
161     }
162 
len(&self) -> usize163     pub fn len(&self) -> usize {
164         self.len
165     }
166 
is_empty(&self) -> bool167     pub fn is_empty(&self) -> bool {
168         self.len == 0
169     }
170 }
171 
172 #[derive(Clone, Debug)]
173 pub struct UnknownExtension {
174     pub typ: ExtensionType,
175     pub payload: Payload,
176 }
177 
178 impl UnknownExtension {
encode(&self, bytes: &mut Vec<u8>)179     fn encode(&self, bytes: &mut Vec<u8>) {
180         self.payload.encode(bytes);
181     }
182 
read(typ: ExtensionType, r: &mut Reader) -> Self183     fn read(typ: ExtensionType, r: &mut Reader) -> Self {
184         let payload = Payload::read(r);
185         Self { typ, payload }
186     }
187 }
188 
189 declare_u8_vec!(ECPointFormatList, ECPointFormat);
190 
191 pub trait SupportedPointFormats {
supported() -> ECPointFormatList192     fn supported() -> ECPointFormatList;
193 }
194 
195 impl SupportedPointFormats for ECPointFormatList {
supported() -> ECPointFormatList196     fn supported() -> ECPointFormatList {
197         vec![ECPointFormat::Uncompressed]
198     }
199 }
200 
201 declare_u16_vec!(NamedGroups, NamedGroup);
202 
203 declare_u16_vec!(SupportedSignatureSchemes, SignatureScheme);
204 
205 pub trait DecomposedSignatureScheme {
sign(&self) -> SignatureAlgorithm206     fn sign(&self) -> SignatureAlgorithm;
make(alg: SignatureAlgorithm, hash: HashAlgorithm) -> SignatureScheme207     fn make(alg: SignatureAlgorithm, hash: HashAlgorithm) -> SignatureScheme;
208 }
209 
210 impl DecomposedSignatureScheme for SignatureScheme {
sign(&self) -> SignatureAlgorithm211     fn sign(&self) -> SignatureAlgorithm {
212         match *self {
213             Self::RSA_PKCS1_SHA1
214             | Self::RSA_PKCS1_SHA256
215             | Self::RSA_PKCS1_SHA384
216             | Self::RSA_PKCS1_SHA512
217             | Self::RSA_PSS_SHA256
218             | Self::RSA_PSS_SHA384
219             | Self::RSA_PSS_SHA512 => SignatureAlgorithm::RSA,
220             Self::ECDSA_NISTP256_SHA256
221             | Self::ECDSA_NISTP384_SHA384
222             | Self::ECDSA_NISTP521_SHA512 => SignatureAlgorithm::ECDSA,
223             _ => SignatureAlgorithm::Unknown(0),
224         }
225     }
226 
make(alg: SignatureAlgorithm, hash: HashAlgorithm) -> SignatureScheme227     fn make(alg: SignatureAlgorithm, hash: HashAlgorithm) -> SignatureScheme {
228         use crate::msgs::enums::HashAlgorithm::{SHA1, SHA256, SHA384, SHA512};
229         use crate::msgs::enums::SignatureAlgorithm::{ECDSA, RSA};
230 
231         match (alg, hash) {
232             (RSA, SHA1) => Self::RSA_PKCS1_SHA1,
233             (RSA, SHA256) => Self::RSA_PKCS1_SHA256,
234             (RSA, SHA384) => Self::RSA_PKCS1_SHA384,
235             (RSA, SHA512) => Self::RSA_PKCS1_SHA512,
236             (ECDSA, SHA256) => Self::ECDSA_NISTP256_SHA256,
237             (ECDSA, SHA384) => Self::ECDSA_NISTP384_SHA384,
238             (ECDSA, SHA512) => Self::ECDSA_NISTP521_SHA512,
239             (_, _) => unreachable!(),
240         }
241     }
242 }
243 
244 #[derive(Clone, Debug)]
245 pub enum ServerNamePayload {
246     // Stored twice, bytes so we can round-trip, and DnsName for use
247     HostName((PayloadU16, webpki::DnsName)),
248     Unknown(Payload),
249 }
250 
251 impl ServerNamePayload {
new_hostname(hostname: webpki::DnsName) -> Self252     pub fn new_hostname(hostname: webpki::DnsName) -> Self {
253         let raw = {
254             let s: &str = hostname.as_ref().into();
255             PayloadU16::new(s.as_bytes().into())
256         };
257         Self::HostName((raw, hostname))
258     }
259 
read_hostname(r: &mut Reader) -> Option<Self>260     fn read_hostname(r: &mut Reader) -> Option<Self> {
261         let raw = PayloadU16::read(r)?;
262 
263         let dns_name = {
264             match webpki::DnsNameRef::try_from_ascii(&raw.0) {
265                 Ok(dns_name) => dns_name.into(),
266                 Err(_) => {
267                     warn!("Illegal SNI hostname received {:?}", raw.0);
268                     return None;
269                 }
270             }
271         };
272         Some(Self::HostName((raw, dns_name)))
273     }
274 
encode(&self, bytes: &mut Vec<u8>)275     fn encode(&self, bytes: &mut Vec<u8>) {
276         match *self {
277             Self::HostName((ref r, _)) => r.encode(bytes),
278             Self::Unknown(ref r) => r.encode(bytes),
279         }
280     }
281 }
282 
283 #[derive(Clone, Debug)]
284 pub struct ServerName {
285     pub typ: ServerNameType,
286     pub payload: ServerNamePayload,
287 }
288 
289 impl Codec for ServerName {
encode(&self, bytes: &mut Vec<u8>)290     fn encode(&self, bytes: &mut Vec<u8>) {
291         self.typ.encode(bytes);
292         self.payload.encode(bytes);
293     }
294 
read(r: &mut Reader) -> Option<Self>295     fn read(r: &mut Reader) -> Option<Self> {
296         let typ = ServerNameType::read(r)?;
297 
298         let payload = match typ {
299             ServerNameType::HostName => ServerNamePayload::read_hostname(r)?,
300             _ => ServerNamePayload::Unknown(Payload::read(r)),
301         };
302 
303         Some(Self { typ, payload })
304     }
305 }
306 
307 declare_u16_vec!(ServerNameRequest, ServerName);
308 
309 pub trait ConvertServerNameList {
has_duplicate_names_for_type(&self) -> bool310     fn has_duplicate_names_for_type(&self) -> bool;
get_single_hostname(&self) -> Option<webpki::DnsNameRef>311     fn get_single_hostname(&self) -> Option<webpki::DnsNameRef>;
312 }
313 
314 impl ConvertServerNameList for ServerNameRequest {
315     /// RFC6066: "The ServerNameList MUST NOT contain more than one name of the same name_type."
has_duplicate_names_for_type(&self) -> bool316     fn has_duplicate_names_for_type(&self) -> bool {
317         let mut seen = collections::HashSet::new();
318 
319         for name in self {
320             if !seen.insert(name.typ.get_u8()) {
321                 return true;
322             }
323         }
324 
325         false
326     }
327 
get_single_hostname(&self) -> Option<webpki::DnsNameRef>328     fn get_single_hostname(&self) -> Option<webpki::DnsNameRef> {
329         fn only_dns_hostnames(name: &ServerName) -> Option<webpki::DnsNameRef> {
330             if let ServerNamePayload::HostName((_, ref dns)) = name.payload {
331                 Some(dns.as_ref())
332             } else {
333                 None
334             }
335         }
336 
337         self.iter()
338             .filter_map(only_dns_hostnames)
339             .next()
340     }
341 }
342 
343 pub type ProtocolNameList = VecU16OfPayloadU8;
344 
345 pub trait ConvertProtocolNameList {
from_slices(names: &[&[u8]]) -> Self346     fn from_slices(names: &[&[u8]]) -> Self;
to_slices(&self) -> Vec<&[u8]>347     fn to_slices(&self) -> Vec<&[u8]>;
as_single_slice(&self) -> Option<&[u8]>348     fn as_single_slice(&self) -> Option<&[u8]>;
349 }
350 
351 impl ConvertProtocolNameList for ProtocolNameList {
from_slices(names: &[&[u8]]) -> Self352     fn from_slices(names: &[&[u8]]) -> Self {
353         let mut ret = Self::new();
354 
355         for name in names {
356             ret.push(PayloadU8::new(name.to_vec()));
357         }
358 
359         ret
360     }
361 
to_slices(&self) -> Vec<&[u8]>362     fn to_slices(&self) -> Vec<&[u8]> {
363         self.iter()
364             .map(|proto| -> &[u8] { &proto.0 })
365             .collect::<Vec<&[u8]>>()
366     }
367 
as_single_slice(&self) -> Option<&[u8]>368     fn as_single_slice(&self) -> Option<&[u8]> {
369         if self.len() == 1 {
370             Some(&self[0].0)
371         } else {
372             None
373         }
374     }
375 }
376 
377 // --- TLS 1.3 Key shares ---
378 #[derive(Clone, Debug)]
379 pub struct KeyShareEntry {
380     pub group: NamedGroup,
381     pub payload: PayloadU16,
382 }
383 
384 impl KeyShareEntry {
new(group: NamedGroup, payload: &[u8]) -> Self385     pub fn new(group: NamedGroup, payload: &[u8]) -> Self {
386         Self {
387             group,
388             payload: PayloadU16::new(payload.to_vec()),
389         }
390     }
391 }
392 
393 impl Codec for KeyShareEntry {
encode(&self, bytes: &mut Vec<u8>)394     fn encode(&self, bytes: &mut Vec<u8>) {
395         self.group.encode(bytes);
396         self.payload.encode(bytes);
397     }
398 
read(r: &mut Reader) -> Option<Self>399     fn read(r: &mut Reader) -> Option<Self> {
400         let group = NamedGroup::read(r)?;
401         let payload = PayloadU16::read(r)?;
402 
403         Some(Self { group, payload })
404     }
405 }
406 
407 // --- TLS 1.3 PresharedKey offers ---
408 #[derive(Clone, Debug)]
409 pub struct PresharedKeyIdentity {
410     pub identity: PayloadU16,
411     pub obfuscated_ticket_age: u32,
412 }
413 
414 impl PresharedKeyIdentity {
new(id: Vec<u8>, age: u32) -> Self415     pub fn new(id: Vec<u8>, age: u32) -> Self {
416         Self {
417             identity: PayloadU16::new(id),
418             obfuscated_ticket_age: age,
419         }
420     }
421 }
422 
423 impl Codec for PresharedKeyIdentity {
encode(&self, bytes: &mut Vec<u8>)424     fn encode(&self, bytes: &mut Vec<u8>) {
425         self.identity.encode(bytes);
426         self.obfuscated_ticket_age.encode(bytes);
427     }
428 
read(r: &mut Reader) -> Option<Self>429     fn read(r: &mut Reader) -> Option<Self> {
430         Some(Self {
431             identity: PayloadU16::read(r)?,
432             obfuscated_ticket_age: u32::read(r)?,
433         })
434     }
435 }
436 
437 declare_u16_vec!(PresharedKeyIdentities, PresharedKeyIdentity);
438 pub type PresharedKeyBinder = PayloadU8;
439 pub type PresharedKeyBinders = VecU16OfPayloadU8;
440 
441 #[derive(Clone, Debug)]
442 pub struct PresharedKeyOffer {
443     pub identities: PresharedKeyIdentities,
444     pub binders: PresharedKeyBinders,
445 }
446 
447 impl PresharedKeyOffer {
448     /// Make a new one with one entry.
new(id: PresharedKeyIdentity, binder: Vec<u8>) -> Self449     pub fn new(id: PresharedKeyIdentity, binder: Vec<u8>) -> Self {
450         Self {
451             identities: vec![id],
452             binders: vec![PresharedKeyBinder::new(binder)],
453         }
454     }
455 }
456 
457 impl Codec for PresharedKeyOffer {
encode(&self, bytes: &mut Vec<u8>)458     fn encode(&self, bytes: &mut Vec<u8>) {
459         self.identities.encode(bytes);
460         self.binders.encode(bytes);
461     }
462 
read(r: &mut Reader) -> Option<Self>463     fn read(r: &mut Reader) -> Option<Self> {
464         Some(Self {
465             identities: PresharedKeyIdentities::read(r)?,
466             binders: PresharedKeyBinders::read(r)?,
467         })
468     }
469 }
470 
471 // --- RFC6066 certificate status request ---
472 type ResponderIDs = VecU16OfPayloadU16;
473 
474 #[derive(Clone, Debug)]
475 pub struct OCSPCertificateStatusRequest {
476     pub responder_ids: ResponderIDs,
477     pub extensions: PayloadU16,
478 }
479 
480 impl Codec for OCSPCertificateStatusRequest {
encode(&self, bytes: &mut Vec<u8>)481     fn encode(&self, bytes: &mut Vec<u8>) {
482         CertificateStatusType::OCSP.encode(bytes);
483         self.responder_ids.encode(bytes);
484         self.extensions.encode(bytes);
485     }
486 
read(r: &mut Reader) -> Option<Self>487     fn read(r: &mut Reader) -> Option<Self> {
488         Some(Self {
489             responder_ids: ResponderIDs::read(r)?,
490             extensions: PayloadU16::read(r)?,
491         })
492     }
493 }
494 
495 #[derive(Clone, Debug)]
496 pub enum CertificateStatusRequest {
497     OCSP(OCSPCertificateStatusRequest),
498     Unknown((CertificateStatusType, Payload)),
499 }
500 
501 impl Codec for CertificateStatusRequest {
encode(&self, bytes: &mut Vec<u8>)502     fn encode(&self, bytes: &mut Vec<u8>) {
503         match *self {
504             Self::OCSP(ref r) => r.encode(bytes),
505             Self::Unknown((typ, ref payload)) => {
506                 typ.encode(bytes);
507                 payload.encode(bytes);
508             }
509         }
510     }
511 
read(r: &mut Reader) -> Option<Self>512     fn read(r: &mut Reader) -> Option<Self> {
513         let typ = CertificateStatusType::read(r)?;
514 
515         match typ {
516             CertificateStatusType::OCSP => {
517                 let ocsp_req = OCSPCertificateStatusRequest::read(r)?;
518                 Some(Self::OCSP(ocsp_req))
519             }
520             _ => {
521                 let data = Payload::read(r);
522                 Some(Self::Unknown((typ, data)))
523             }
524         }
525     }
526 }
527 
528 impl CertificateStatusRequest {
build_ocsp() -> Self529     pub fn build_ocsp() -> Self {
530         let ocsp = OCSPCertificateStatusRequest {
531             responder_ids: ResponderIDs::new(),
532             extensions: PayloadU16::empty(),
533         };
534         Self::OCSP(ocsp)
535     }
536 }
537 
538 // ---
539 // SCTs
540 
541 pub type SCTList = VecU16OfPayloadU16;
542 
543 // ---
544 
545 declare_u8_vec!(PSKKeyExchangeModes, PSKKeyExchangeMode);
546 declare_u16_vec!(KeyShareEntries, KeyShareEntry);
547 declare_u8_vec!(ProtocolVersions, ProtocolVersion);
548 
549 #[derive(Clone, Debug)]
550 pub enum ClientExtension {
551     ECPointFormats(ECPointFormatList),
552     NamedGroups(NamedGroups),
553     SignatureAlgorithms(SupportedSignatureSchemes),
554     ServerName(ServerNameRequest),
555     SessionTicket(ClientSessionTicket),
556     Protocols(ProtocolNameList),
557     SupportedVersions(ProtocolVersions),
558     KeyShare(KeyShareEntries),
559     PresharedKeyModes(PSKKeyExchangeModes),
560     PresharedKey(PresharedKeyOffer),
561     Cookie(PayloadU16),
562     ExtendedMasterSecretRequest,
563     CertificateStatusRequest(CertificateStatusRequest),
564     SignedCertificateTimestampRequest,
565     TransportParameters(Vec<u8>),
566     TransportParametersDraft(Vec<u8>),
567     EarlyData,
568     Unknown(UnknownExtension),
569 }
570 
571 impl ClientExtension {
get_type(&self) -> ExtensionType572     pub fn get_type(&self) -> ExtensionType {
573         match *self {
574             Self::ECPointFormats(_) => ExtensionType::ECPointFormats,
575             Self::NamedGroups(_) => ExtensionType::EllipticCurves,
576             Self::SignatureAlgorithms(_) => ExtensionType::SignatureAlgorithms,
577             Self::ServerName(_) => ExtensionType::ServerName,
578             Self::SessionTicket(_) => ExtensionType::SessionTicket,
579             Self::Protocols(_) => ExtensionType::ALProtocolNegotiation,
580             Self::SupportedVersions(_) => ExtensionType::SupportedVersions,
581             Self::KeyShare(_) => ExtensionType::KeyShare,
582             Self::PresharedKeyModes(_) => ExtensionType::PSKKeyExchangeModes,
583             Self::PresharedKey(_) => ExtensionType::PreSharedKey,
584             Self::Cookie(_) => ExtensionType::Cookie,
585             Self::ExtendedMasterSecretRequest => ExtensionType::ExtendedMasterSecret,
586             Self::CertificateStatusRequest(_) => ExtensionType::StatusRequest,
587             Self::SignedCertificateTimestampRequest => ExtensionType::SCT,
588             Self::TransportParameters(_) => ExtensionType::TransportParameters,
589             Self::TransportParametersDraft(_) => ExtensionType::TransportParametersDraft,
590             Self::EarlyData => ExtensionType::EarlyData,
591             Self::Unknown(ref r) => r.typ,
592         }
593     }
594 }
595 
596 impl Codec for ClientExtension {
encode(&self, bytes: &mut Vec<u8>)597     fn encode(&self, bytes: &mut Vec<u8>) {
598         self.get_type().encode(bytes);
599 
600         let mut sub: Vec<u8> = Vec::new();
601         match *self {
602             Self::ECPointFormats(ref r) => r.encode(&mut sub),
603             Self::NamedGroups(ref r) => r.encode(&mut sub),
604             Self::SignatureAlgorithms(ref r) => r.encode(&mut sub),
605             Self::ServerName(ref r) => r.encode(&mut sub),
606             Self::SessionTicket(ClientSessionTicket::Request)
607             | Self::ExtendedMasterSecretRequest
608             | Self::SignedCertificateTimestampRequest
609             | Self::EarlyData => {}
610             Self::SessionTicket(ClientSessionTicket::Offer(ref r)) => r.encode(&mut sub),
611             Self::Protocols(ref r) => r.encode(&mut sub),
612             Self::SupportedVersions(ref r) => r.encode(&mut sub),
613             Self::KeyShare(ref r) => r.encode(&mut sub),
614             Self::PresharedKeyModes(ref r) => r.encode(&mut sub),
615             Self::PresharedKey(ref r) => r.encode(&mut sub),
616             Self::Cookie(ref r) => r.encode(&mut sub),
617             Self::CertificateStatusRequest(ref r) => r.encode(&mut sub),
618             Self::TransportParameters(ref r) | Self::TransportParametersDraft(ref r) => {
619                 sub.extend_from_slice(r)
620             }
621             Self::Unknown(ref r) => r.encode(&mut sub),
622         }
623 
624         (sub.len() as u16).encode(bytes);
625         bytes.append(&mut sub);
626     }
627 
read(r: &mut Reader) -> Option<Self>628     fn read(r: &mut Reader) -> Option<Self> {
629         let typ = ExtensionType::read(r)?;
630         let len = u16::read(r)? as usize;
631         let mut sub = r.sub(len)?;
632 
633         let ext = match typ {
634             ExtensionType::ECPointFormats => {
635                 Self::ECPointFormats(ECPointFormatList::read(&mut sub)?)
636             }
637             ExtensionType::EllipticCurves => Self::NamedGroups(NamedGroups::read(&mut sub)?),
638             ExtensionType::SignatureAlgorithms => {
639                 let schemes = SupportedSignatureSchemes::read(&mut sub)?;
640                 Self::SignatureAlgorithms(schemes)
641             }
642             ExtensionType::ServerName => Self::ServerName(ServerNameRequest::read(&mut sub)?),
643             ExtensionType::SessionTicket => {
644                 if sub.any_left() {
645                     let contents = Payload::read(&mut sub);
646                     Self::SessionTicket(ClientSessionTicket::Offer(contents))
647                 } else {
648                     Self::SessionTicket(ClientSessionTicket::Request)
649                 }
650             }
651             ExtensionType::ALProtocolNegotiation => {
652                 Self::Protocols(ProtocolNameList::read(&mut sub)?)
653             }
654             ExtensionType::SupportedVersions => {
655                 Self::SupportedVersions(ProtocolVersions::read(&mut sub)?)
656             }
657             ExtensionType::KeyShare => Self::KeyShare(KeyShareEntries::read(&mut sub)?),
658             ExtensionType::PSKKeyExchangeModes => {
659                 Self::PresharedKeyModes(PSKKeyExchangeModes::read(&mut sub)?)
660             }
661             ExtensionType::PreSharedKey => Self::PresharedKey(PresharedKeyOffer::read(&mut sub)?),
662             ExtensionType::Cookie => Self::Cookie(PayloadU16::read(&mut sub)?),
663             ExtensionType::ExtendedMasterSecret if !sub.any_left() => {
664                 Self::ExtendedMasterSecretRequest
665             }
666             ExtensionType::StatusRequest => {
667                 let csr = CertificateStatusRequest::read(&mut sub)?;
668                 Self::CertificateStatusRequest(csr)
669             }
670             ExtensionType::SCT if !sub.any_left() => Self::SignedCertificateTimestampRequest,
671             ExtensionType::TransportParameters => Self::TransportParameters(sub.rest().to_vec()),
672             ExtensionType::TransportParametersDraft => {
673                 Self::TransportParametersDraft(sub.rest().to_vec())
674             }
675             ExtensionType::EarlyData if !sub.any_left() => Self::EarlyData,
676             _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)),
677         };
678 
679         if sub.any_left() {
680             None
681         } else {
682             Some(ext)
683         }
684     }
685 }
686 
trim_hostname_trailing_dot_for_sni(dns_name: webpki::DnsNameRef) -> webpki::DnsName687 fn trim_hostname_trailing_dot_for_sni(dns_name: webpki::DnsNameRef) -> webpki::DnsName {
688     let dns_name_str: &str = dns_name.into();
689 
690     // RFC6066: "The hostname is represented as a byte string using
691     // ASCII encoding without a trailing dot"
692     if dns_name_str.ends_with('.') {
693         let trimmed = &dns_name_str[0..dns_name_str.len() - 1];
694         webpki::DnsNameRef::try_from_ascii_str(trimmed)
695             .unwrap()
696             .to_owned()
697     } else {
698         dns_name.to_owned()
699     }
700 }
701 
702 impl ClientExtension {
703     /// Make a basic SNI ServerNameRequest quoting `hostname`.
make_sni(dns_name: webpki::DnsNameRef) -> Self704     pub fn make_sni(dns_name: webpki::DnsNameRef) -> Self {
705         let name = ServerName {
706             typ: ServerNameType::HostName,
707             payload: ServerNamePayload::new_hostname(trim_hostname_trailing_dot_for_sni(dns_name)),
708         };
709 
710         Self::ServerName(vec![name])
711     }
712 }
713 
714 #[derive(Clone, Debug)]
715 pub enum ClientSessionTicket {
716     Request,
717     Offer(Payload),
718 }
719 
720 #[derive(Clone, Debug)]
721 pub enum ServerExtension {
722     ECPointFormats(ECPointFormatList),
723     ServerNameAck,
724     SessionTicketAck,
725     RenegotiationInfo(PayloadU8),
726     Protocols(ProtocolNameList),
727     KeyShare(KeyShareEntry),
728     PresharedKey(u16),
729     ExtendedMasterSecretAck,
730     CertificateStatusAck,
731     SignedCertificateTimestamp(SCTList),
732     SupportedVersions(ProtocolVersion),
733     TransportParameters(Vec<u8>),
734     TransportParametersDraft(Vec<u8>),
735     EarlyData,
736     Unknown(UnknownExtension),
737 }
738 
739 impl ServerExtension {
get_type(&self) -> ExtensionType740     pub fn get_type(&self) -> ExtensionType {
741         match *self {
742             Self::ECPointFormats(_) => ExtensionType::ECPointFormats,
743             Self::ServerNameAck => ExtensionType::ServerName,
744             Self::SessionTicketAck => ExtensionType::SessionTicket,
745             Self::RenegotiationInfo(_) => ExtensionType::RenegotiationInfo,
746             Self::Protocols(_) => ExtensionType::ALProtocolNegotiation,
747             Self::KeyShare(_) => ExtensionType::KeyShare,
748             Self::PresharedKey(_) => ExtensionType::PreSharedKey,
749             Self::ExtendedMasterSecretAck => ExtensionType::ExtendedMasterSecret,
750             Self::CertificateStatusAck => ExtensionType::StatusRequest,
751             Self::SignedCertificateTimestamp(_) => ExtensionType::SCT,
752             Self::SupportedVersions(_) => ExtensionType::SupportedVersions,
753             Self::TransportParameters(_) => ExtensionType::TransportParameters,
754             Self::TransportParametersDraft(_) => ExtensionType::TransportParametersDraft,
755             Self::EarlyData => ExtensionType::EarlyData,
756             Self::Unknown(ref r) => r.typ,
757         }
758     }
759 }
760 
761 impl Codec for ServerExtension {
encode(&self, bytes: &mut Vec<u8>)762     fn encode(&self, bytes: &mut Vec<u8>) {
763         self.get_type().encode(bytes);
764 
765         let mut sub: Vec<u8> = Vec::new();
766         match *self {
767             Self::ECPointFormats(ref r) => r.encode(&mut sub),
768             Self::ServerNameAck
769             | Self::SessionTicketAck
770             | Self::ExtendedMasterSecretAck
771             | Self::CertificateStatusAck
772             | Self::EarlyData => {}
773             Self::RenegotiationInfo(ref r) => r.encode(&mut sub),
774             Self::Protocols(ref r) => r.encode(&mut sub),
775             Self::KeyShare(ref r) => r.encode(&mut sub),
776             Self::PresharedKey(r) => r.encode(&mut sub),
777             Self::SignedCertificateTimestamp(ref r) => r.encode(&mut sub),
778             Self::SupportedVersions(ref r) => r.encode(&mut sub),
779             Self::TransportParameters(ref r) | Self::TransportParametersDraft(ref r) => {
780                 sub.extend_from_slice(r)
781             }
782             Self::Unknown(ref r) => r.encode(&mut sub),
783         }
784 
785         (sub.len() as u16).encode(bytes);
786         bytes.append(&mut sub);
787     }
788 
read(r: &mut Reader) -> Option<Self>789     fn read(r: &mut Reader) -> Option<Self> {
790         let typ = ExtensionType::read(r)?;
791         let len = u16::read(r)? as usize;
792         let mut sub = r.sub(len)?;
793 
794         let ext = match typ {
795             ExtensionType::ECPointFormats => {
796                 Self::ECPointFormats(ECPointFormatList::read(&mut sub)?)
797             }
798             ExtensionType::ServerName => Self::ServerNameAck,
799             ExtensionType::SessionTicket => Self::SessionTicketAck,
800             ExtensionType::StatusRequest => Self::CertificateStatusAck,
801             ExtensionType::RenegotiationInfo => Self::RenegotiationInfo(PayloadU8::read(&mut sub)?),
802             ExtensionType::ALProtocolNegotiation => {
803                 Self::Protocols(ProtocolNameList::read(&mut sub)?)
804             }
805             ExtensionType::KeyShare => Self::KeyShare(KeyShareEntry::read(&mut sub)?),
806             ExtensionType::PreSharedKey => Self::PresharedKey(u16::read(&mut sub)?),
807             ExtensionType::ExtendedMasterSecret => Self::ExtendedMasterSecretAck,
808             ExtensionType::SCT => {
809                 let scts = SCTList::read(&mut sub)?;
810                 Self::SignedCertificateTimestamp(scts)
811             }
812             ExtensionType::SupportedVersions => {
813                 Self::SupportedVersions(ProtocolVersion::read(&mut sub)?)
814             }
815             ExtensionType::TransportParameters => Self::TransportParameters(sub.rest().to_vec()),
816             ExtensionType::TransportParametersDraft => {
817                 Self::TransportParametersDraft(sub.rest().to_vec())
818             }
819             ExtensionType::EarlyData => Self::EarlyData,
820             _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)),
821         };
822 
823         if sub.any_left() {
824             None
825         } else {
826             Some(ext)
827         }
828     }
829 }
830 
831 impl ServerExtension {
make_alpn(proto: &[&[u8]]) -> Self832     pub fn make_alpn(proto: &[&[u8]]) -> Self {
833         Self::Protocols(ProtocolNameList::from_slices(proto))
834     }
835 
make_empty_renegotiation_info() -> Self836     pub fn make_empty_renegotiation_info() -> Self {
837         let empty = Vec::new();
838         Self::RenegotiationInfo(PayloadU8::new(empty))
839     }
840 
make_sct(sctl: Vec<u8>) -> Self841     pub fn make_sct(sctl: Vec<u8>) -> Self {
842         let scts = SCTList::read_bytes(&sctl).expect("invalid SCT list");
843         Self::SignedCertificateTimestamp(scts)
844     }
845 }
846 
847 #[derive(Debug)]
848 pub struct ClientHelloPayload {
849     pub client_version: ProtocolVersion,
850     pub random: Random,
851     pub session_id: SessionID,
852     pub cipher_suites: Vec<CipherSuite>,
853     pub compression_methods: Vec<Compression>,
854     pub extensions: Vec<ClientExtension>,
855 }
856 
857 impl Codec for ClientHelloPayload {
encode(&self, bytes: &mut Vec<u8>)858     fn encode(&self, bytes: &mut Vec<u8>) {
859         self.client_version.encode(bytes);
860         self.random.encode(bytes);
861         self.session_id.encode(bytes);
862         codec::encode_vec_u16(bytes, &self.cipher_suites);
863         codec::encode_vec_u8(bytes, &self.compression_methods);
864 
865         if !self.extensions.is_empty() {
866             codec::encode_vec_u16(bytes, &self.extensions);
867         }
868     }
869 
read(r: &mut Reader) -> Option<Self>870     fn read(r: &mut Reader) -> Option<Self> {
871         let mut ret = Self {
872             client_version: ProtocolVersion::read(r)?,
873             random: Random::read(r)?,
874             session_id: SessionID::read(r)?,
875             cipher_suites: codec::read_vec_u16::<CipherSuite>(r)?,
876             compression_methods: codec::read_vec_u8::<Compression>(r)?,
877             extensions: Vec::new(),
878         };
879 
880         if r.any_left() {
881             ret.extensions = codec::read_vec_u16::<ClientExtension>(r)?;
882         }
883 
884         if r.any_left() || ret.extensions.is_empty() {
885             None
886         } else {
887             Some(ret)
888         }
889     }
890 }
891 
892 impl ClientHelloPayload {
893     /// Returns true if there is more than one extension of a given
894     /// type.
has_duplicate_extension(&self) -> bool895     pub fn has_duplicate_extension(&self) -> bool {
896         let mut seen = collections::HashSet::new();
897 
898         for ext in &self.extensions {
899             let typ = ext.get_type().get_u16();
900 
901             if seen.contains(&typ) {
902                 return true;
903             }
904             seen.insert(typ);
905         }
906 
907         false
908     }
909 
find_extension(&self, ext: ExtensionType) -> Option<&ClientExtension>910     pub fn find_extension(&self, ext: ExtensionType) -> Option<&ClientExtension> {
911         self.extensions
912             .iter()
913             .find(|x| x.get_type() == ext)
914     }
915 
get_sni_extension(&self) -> Option<&ServerNameRequest>916     pub fn get_sni_extension(&self) -> Option<&ServerNameRequest> {
917         let ext = self.find_extension(ExtensionType::ServerName)?;
918         match *ext {
919             ClientExtension::ServerName(ref req) => Some(req),
920             _ => None,
921         }
922     }
923 
get_sigalgs_extension(&self) -> Option<&SupportedSignatureSchemes>924     pub fn get_sigalgs_extension(&self) -> Option<&SupportedSignatureSchemes> {
925         let ext = self.find_extension(ExtensionType::SignatureAlgorithms)?;
926         match *ext {
927             ClientExtension::SignatureAlgorithms(ref req) => Some(req),
928             _ => None,
929         }
930     }
931 
get_namedgroups_extension(&self) -> Option<&NamedGroups>932     pub fn get_namedgroups_extension(&self) -> Option<&NamedGroups> {
933         let ext = self.find_extension(ExtensionType::EllipticCurves)?;
934         match *ext {
935             ClientExtension::NamedGroups(ref req) => Some(req),
936             _ => None,
937         }
938     }
939 
get_ecpoints_extension(&self) -> Option<&ECPointFormatList>940     pub fn get_ecpoints_extension(&self) -> Option<&ECPointFormatList> {
941         let ext = self.find_extension(ExtensionType::ECPointFormats)?;
942         match *ext {
943             ClientExtension::ECPointFormats(ref req) => Some(req),
944             _ => None,
945         }
946     }
947 
get_alpn_extension(&self) -> Option<&ProtocolNameList>948     pub fn get_alpn_extension(&self) -> Option<&ProtocolNameList> {
949         let ext = self.find_extension(ExtensionType::ALProtocolNegotiation)?;
950         match *ext {
951             ClientExtension::Protocols(ref req) => Some(req),
952             _ => None,
953         }
954     }
955 
get_quic_params_extension(&self) -> Option<Vec<u8>>956     pub fn get_quic_params_extension(&self) -> Option<Vec<u8>> {
957         let ext = self
958             .find_extension(ExtensionType::TransportParameters)
959             .or_else(|| self.find_extension(ExtensionType::TransportParametersDraft))?;
960         match *ext {
961             ClientExtension::TransportParameters(ref bytes)
962             | ClientExtension::TransportParametersDraft(ref bytes) => Some(bytes.to_vec()),
963             _ => None,
964         }
965     }
966 
get_ticket_extension(&self) -> Option<&ClientExtension>967     pub fn get_ticket_extension(&self) -> Option<&ClientExtension> {
968         self.find_extension(ExtensionType::SessionTicket)
969     }
970 
get_versions_extension(&self) -> Option<&ProtocolVersions>971     pub fn get_versions_extension(&self) -> Option<&ProtocolVersions> {
972         let ext = self.find_extension(ExtensionType::SupportedVersions)?;
973         match *ext {
974             ClientExtension::SupportedVersions(ref vers) => Some(vers),
975             _ => None,
976         }
977     }
978 
get_keyshare_extension(&self) -> Option<&KeyShareEntries>979     pub fn get_keyshare_extension(&self) -> Option<&KeyShareEntries> {
980         let ext = self.find_extension(ExtensionType::KeyShare)?;
981         match *ext {
982             ClientExtension::KeyShare(ref shares) => Some(shares),
983             _ => None,
984         }
985     }
986 
has_keyshare_extension_with_duplicates(&self) -> bool987     pub fn has_keyshare_extension_with_duplicates(&self) -> bool {
988         if let Some(entries) = self.get_keyshare_extension() {
989             let mut seen = collections::HashSet::new();
990 
991             for kse in entries {
992                 let grp = kse.group.get_u16();
993 
994                 if !seen.insert(grp) {
995                     return true;
996                 }
997             }
998         }
999 
1000         false
1001     }
1002 
get_psk(&self) -> Option<&PresharedKeyOffer>1003     pub fn get_psk(&self) -> Option<&PresharedKeyOffer> {
1004         let ext = self.find_extension(ExtensionType::PreSharedKey)?;
1005         match *ext {
1006             ClientExtension::PresharedKey(ref psk) => Some(psk),
1007             _ => None,
1008         }
1009     }
1010 
check_psk_ext_is_last(&self) -> bool1011     pub fn check_psk_ext_is_last(&self) -> bool {
1012         self.extensions
1013             .last()
1014             .map_or(false, |ext| ext.get_type() == ExtensionType::PreSharedKey)
1015     }
1016 
get_psk_modes(&self) -> Option<&PSKKeyExchangeModes>1017     pub fn get_psk_modes(&self) -> Option<&PSKKeyExchangeModes> {
1018         let ext = self.find_extension(ExtensionType::PSKKeyExchangeModes)?;
1019         match *ext {
1020             ClientExtension::PresharedKeyModes(ref psk_modes) => Some(psk_modes),
1021             _ => None,
1022         }
1023     }
1024 
psk_mode_offered(&self, mode: PSKKeyExchangeMode) -> bool1025     pub fn psk_mode_offered(&self, mode: PSKKeyExchangeMode) -> bool {
1026         self.get_psk_modes()
1027             .map(|modes| modes.contains(&mode))
1028             .unwrap_or(false)
1029     }
1030 
set_psk_binder(&mut self, binder: impl Into<Vec<u8>>)1031     pub fn set_psk_binder(&mut self, binder: impl Into<Vec<u8>>) {
1032         let last_extension = self.extensions.last_mut();
1033         if let Some(ClientExtension::PresharedKey(ref mut offer)) = last_extension {
1034             offer.binders[0] = PresharedKeyBinder::new(binder.into());
1035         }
1036     }
1037 
ems_support_offered(&self) -> bool1038     pub fn ems_support_offered(&self) -> bool {
1039         self.find_extension(ExtensionType::ExtendedMasterSecret)
1040             .is_some()
1041     }
1042 
early_data_extension_offered(&self) -> bool1043     pub fn early_data_extension_offered(&self) -> bool {
1044         self.find_extension(ExtensionType::EarlyData)
1045             .is_some()
1046     }
1047 }
1048 
1049 #[derive(Debug)]
1050 pub enum HelloRetryExtension {
1051     KeyShare(NamedGroup),
1052     Cookie(PayloadU16),
1053     SupportedVersions(ProtocolVersion),
1054     Unknown(UnknownExtension),
1055 }
1056 
1057 impl HelloRetryExtension {
get_type(&self) -> ExtensionType1058     pub fn get_type(&self) -> ExtensionType {
1059         match *self {
1060             HelloRetryExtension::KeyShare(_) => ExtensionType::KeyShare,
1061             HelloRetryExtension::Cookie(_) => ExtensionType::Cookie,
1062             HelloRetryExtension::SupportedVersions(_) => ExtensionType::SupportedVersions,
1063             HelloRetryExtension::Unknown(ref r) => r.typ,
1064         }
1065     }
1066 }
1067 
1068 impl Codec for HelloRetryExtension {
encode(&self, bytes: &mut Vec<u8>)1069     fn encode(&self, bytes: &mut Vec<u8>) {
1070         self.get_type().encode(bytes);
1071 
1072         let mut sub: Vec<u8> = Vec::new();
1073         match *self {
1074             HelloRetryExtension::KeyShare(ref r) => r.encode(&mut sub),
1075             HelloRetryExtension::Cookie(ref r) => r.encode(&mut sub),
1076             HelloRetryExtension::SupportedVersions(ref r) => r.encode(&mut sub),
1077             HelloRetryExtension::Unknown(ref r) => r.encode(&mut sub),
1078         }
1079 
1080         (sub.len() as u16).encode(bytes);
1081         bytes.append(&mut sub);
1082     }
1083 
read(r: &mut Reader) -> Option<Self>1084     fn read(r: &mut Reader) -> Option<Self> {
1085         let typ = ExtensionType::read(r)?;
1086         let len = u16::read(r)? as usize;
1087         let mut sub = r.sub(len)?;
1088 
1089         let ext = match typ {
1090             ExtensionType::KeyShare => Self::KeyShare(NamedGroup::read(&mut sub)?),
1091             ExtensionType::Cookie => Self::Cookie(PayloadU16::read(&mut sub)?),
1092             ExtensionType::SupportedVersions => {
1093                 Self::SupportedVersions(ProtocolVersion::read(&mut sub)?)
1094             }
1095             _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)),
1096         };
1097 
1098         if sub.any_left() {
1099             None
1100         } else {
1101             Some(ext)
1102         }
1103     }
1104 }
1105 
1106 #[derive(Debug)]
1107 pub struct HelloRetryRequest {
1108     pub legacy_version: ProtocolVersion,
1109     pub session_id: SessionID,
1110     pub cipher_suite: CipherSuite,
1111     pub extensions: Vec<HelloRetryExtension>,
1112 }
1113 
1114 impl Codec for HelloRetryRequest {
encode(&self, bytes: &mut Vec<u8>)1115     fn encode(&self, bytes: &mut Vec<u8>) {
1116         self.legacy_version.encode(bytes);
1117         HELLO_RETRY_REQUEST_RANDOM.encode(bytes);
1118         self.session_id.encode(bytes);
1119         self.cipher_suite.encode(bytes);
1120         Compression::Null.encode(bytes);
1121         codec::encode_vec_u16(bytes, &self.extensions);
1122     }
1123 
read(r: &mut Reader) -> Option<Self>1124     fn read(r: &mut Reader) -> Option<Self> {
1125         let session_id = SessionID::read(r)?;
1126         let cipher_suite = CipherSuite::read(r)?;
1127         let compression = Compression::read(r)?;
1128 
1129         if compression != Compression::Null {
1130             return None;
1131         }
1132 
1133         Some(Self {
1134             legacy_version: ProtocolVersion::Unknown(0),
1135             session_id,
1136             cipher_suite,
1137             extensions: codec::read_vec_u16::<HelloRetryExtension>(r)?,
1138         })
1139     }
1140 }
1141 
1142 impl HelloRetryRequest {
1143     /// Returns true if there is more than one extension of a given
1144     /// type.
has_duplicate_extension(&self) -> bool1145     pub fn has_duplicate_extension(&self) -> bool {
1146         let mut seen = collections::HashSet::new();
1147 
1148         for ext in &self.extensions {
1149             let typ = ext.get_type().get_u16();
1150 
1151             if seen.contains(&typ) {
1152                 return true;
1153             }
1154             seen.insert(typ);
1155         }
1156 
1157         false
1158     }
1159 
has_unknown_extension(&self) -> bool1160     pub fn has_unknown_extension(&self) -> bool {
1161         self.extensions.iter().any(|ext| {
1162             ext.get_type() != ExtensionType::KeyShare
1163                 && ext.get_type() != ExtensionType::SupportedVersions
1164                 && ext.get_type() != ExtensionType::Cookie
1165         })
1166     }
1167 
find_extension(&self, ext: ExtensionType) -> Option<&HelloRetryExtension>1168     fn find_extension(&self, ext: ExtensionType) -> Option<&HelloRetryExtension> {
1169         self.extensions
1170             .iter()
1171             .find(|x| x.get_type() == ext)
1172     }
1173 
get_requested_key_share_group(&self) -> Option<NamedGroup>1174     pub fn get_requested_key_share_group(&self) -> Option<NamedGroup> {
1175         let ext = self.find_extension(ExtensionType::KeyShare)?;
1176         match *ext {
1177             HelloRetryExtension::KeyShare(grp) => Some(grp),
1178             _ => None,
1179         }
1180     }
1181 
get_cookie(&self) -> Option<&PayloadU16>1182     pub fn get_cookie(&self) -> Option<&PayloadU16> {
1183         let ext = self.find_extension(ExtensionType::Cookie)?;
1184         match *ext {
1185             HelloRetryExtension::Cookie(ref ck) => Some(ck),
1186             _ => None,
1187         }
1188     }
1189 
get_supported_versions(&self) -> Option<ProtocolVersion>1190     pub fn get_supported_versions(&self) -> Option<ProtocolVersion> {
1191         let ext = self.find_extension(ExtensionType::SupportedVersions)?;
1192         match *ext {
1193             HelloRetryExtension::SupportedVersions(ver) => Some(ver),
1194             _ => None,
1195         }
1196     }
1197 }
1198 
1199 #[derive(Debug)]
1200 pub struct ServerHelloPayload {
1201     pub legacy_version: ProtocolVersion,
1202     pub random: Random,
1203     pub session_id: SessionID,
1204     pub cipher_suite: CipherSuite,
1205     pub compression_method: Compression,
1206     pub extensions: Vec<ServerExtension>,
1207 }
1208 
1209 impl Codec for ServerHelloPayload {
encode(&self, bytes: &mut Vec<u8>)1210     fn encode(&self, bytes: &mut Vec<u8>) {
1211         self.legacy_version.encode(bytes);
1212         self.random.encode(bytes);
1213 
1214         self.session_id.encode(bytes);
1215         self.cipher_suite.encode(bytes);
1216         self.compression_method.encode(bytes);
1217         codec::encode_vec_u16(bytes, &self.extensions);
1218     }
1219 
1220     // minus version and random, which have already been read.
read(r: &mut Reader) -> Option<Self>1221     fn read(r: &mut Reader) -> Option<Self> {
1222         let session_id = SessionID::read(r)?;
1223         let suite = CipherSuite::read(r)?;
1224         let compression = Compression::read(r)?;
1225         let extensions = codec::read_vec_u16::<ServerExtension>(r)?;
1226 
1227         let ret = Self {
1228             legacy_version: ProtocolVersion::Unknown(0),
1229             random: ZERO_RANDOM,
1230             session_id,
1231             cipher_suite: suite,
1232             compression_method: compression,
1233             extensions,
1234         };
1235 
1236         if r.any_left() {
1237             None
1238         } else {
1239             Some(ret)
1240         }
1241     }
1242 }
1243 
1244 impl HasServerExtensions for ServerHelloPayload {
get_extensions(&self) -> &[ServerExtension]1245     fn get_extensions(&self) -> &[ServerExtension] {
1246         &self.extensions
1247     }
1248 }
1249 
1250 impl ServerHelloPayload {
get_key_share(&self) -> Option<&KeyShareEntry>1251     pub fn get_key_share(&self) -> Option<&KeyShareEntry> {
1252         let ext = self.find_extension(ExtensionType::KeyShare)?;
1253         match *ext {
1254             ServerExtension::KeyShare(ref share) => Some(share),
1255             _ => None,
1256         }
1257     }
1258 
get_psk_index(&self) -> Option<u16>1259     pub fn get_psk_index(&self) -> Option<u16> {
1260         let ext = self.find_extension(ExtensionType::PreSharedKey)?;
1261         match *ext {
1262             ServerExtension::PresharedKey(ref index) => Some(*index),
1263             _ => None,
1264         }
1265     }
1266 
get_ecpoints_extension(&self) -> Option<&ECPointFormatList>1267     pub fn get_ecpoints_extension(&self) -> Option<&ECPointFormatList> {
1268         let ext = self.find_extension(ExtensionType::ECPointFormats)?;
1269         match *ext {
1270             ServerExtension::ECPointFormats(ref fmts) => Some(fmts),
1271             _ => None,
1272         }
1273     }
1274 
ems_support_acked(&self) -> bool1275     pub fn ems_support_acked(&self) -> bool {
1276         self.find_extension(ExtensionType::ExtendedMasterSecret)
1277             .is_some()
1278     }
1279 
get_sct_list(&self) -> Option<&SCTList>1280     pub fn get_sct_list(&self) -> Option<&SCTList> {
1281         let ext = self.find_extension(ExtensionType::SCT)?;
1282         match *ext {
1283             ServerExtension::SignedCertificateTimestamp(ref sctl) => Some(sctl),
1284             _ => None,
1285         }
1286     }
1287 
get_supported_versions(&self) -> Option<ProtocolVersion>1288     pub fn get_supported_versions(&self) -> Option<ProtocolVersion> {
1289         let ext = self.find_extension(ExtensionType::SupportedVersions)?;
1290         match *ext {
1291             ServerExtension::SupportedVersions(vers) => Some(vers),
1292             _ => None,
1293         }
1294     }
1295 }
1296 
1297 pub type CertificatePayload = Vec<key::Certificate>;
1298 
1299 impl Codec for CertificatePayload {
encode(&self, bytes: &mut Vec<u8>)1300     fn encode(&self, bytes: &mut Vec<u8>) {
1301         codec::encode_vec_u24(bytes, self);
1302     }
1303 
read(r: &mut Reader) -> Option<Self>1304     fn read(r: &mut Reader) -> Option<Self> {
1305         // 64KB of certificates is plenty, 16MB is obviously silly
1306         codec::read_vec_u24_limited(r, 0x10000)
1307     }
1308 }
1309 
1310 // TLS1.3 changes the Certificate payload encoding.
1311 // That's annoying. It means the parsing is not
1312 // context-free any more.
1313 
1314 #[derive(Debug)]
1315 pub enum CertificateExtension {
1316     CertificateStatus(CertificateStatus),
1317     SignedCertificateTimestamp(SCTList),
1318     Unknown(UnknownExtension),
1319 }
1320 
1321 impl CertificateExtension {
get_type(&self) -> ExtensionType1322     pub fn get_type(&self) -> ExtensionType {
1323         match *self {
1324             CertificateExtension::CertificateStatus(_) => ExtensionType::StatusRequest,
1325             CertificateExtension::SignedCertificateTimestamp(_) => ExtensionType::SCT,
1326             CertificateExtension::Unknown(ref r) => r.typ,
1327         }
1328     }
1329 
make_sct(sct_list: Vec<u8>) -> Self1330     pub fn make_sct(sct_list: Vec<u8>) -> Self {
1331         let sctl = SCTList::read_bytes(&sct_list).expect("invalid SCT list");
1332         Self::SignedCertificateTimestamp(sctl)
1333     }
1334 
get_cert_status(&self) -> Option<&Vec<u8>>1335     pub fn get_cert_status(&self) -> Option<&Vec<u8>> {
1336         match *self {
1337             CertificateExtension::CertificateStatus(ref cs) => Some(&cs.ocsp_response.0),
1338             _ => None,
1339         }
1340     }
1341 
get_sct_list(&self) -> Option<&SCTList>1342     pub fn get_sct_list(&self) -> Option<&SCTList> {
1343         match *self {
1344             CertificateExtension::SignedCertificateTimestamp(ref sctl) => Some(sctl),
1345             _ => None,
1346         }
1347     }
1348 }
1349 
1350 impl Codec for CertificateExtension {
encode(&self, bytes: &mut Vec<u8>)1351     fn encode(&self, bytes: &mut Vec<u8>) {
1352         self.get_type().encode(bytes);
1353 
1354         let mut sub: Vec<u8> = Vec::new();
1355         match *self {
1356             CertificateExtension::CertificateStatus(ref r) => r.encode(&mut sub),
1357             CertificateExtension::SignedCertificateTimestamp(ref r) => r.encode(&mut sub),
1358             CertificateExtension::Unknown(ref r) => r.encode(&mut sub),
1359         }
1360 
1361         (sub.len() as u16).encode(bytes);
1362         bytes.append(&mut sub);
1363     }
1364 
read(r: &mut Reader) -> Option<Self>1365     fn read(r: &mut Reader) -> Option<Self> {
1366         let typ = ExtensionType::read(r)?;
1367         let len = u16::read(r)? as usize;
1368         let mut sub = r.sub(len)?;
1369 
1370         let ext = match typ {
1371             ExtensionType::StatusRequest => {
1372                 let st = CertificateStatus::read(&mut sub)?;
1373                 Self::CertificateStatus(st)
1374             }
1375             ExtensionType::SCT => {
1376                 let scts = SCTList::read(&mut sub)?;
1377                 Self::SignedCertificateTimestamp(scts)
1378             }
1379             _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)),
1380         };
1381 
1382         if sub.any_left() {
1383             None
1384         } else {
1385             Some(ext)
1386         }
1387     }
1388 }
1389 
1390 declare_u16_vec!(CertificateExtensions, CertificateExtension);
1391 
1392 #[derive(Debug)]
1393 pub struct CertificateEntry {
1394     pub cert: key::Certificate,
1395     pub exts: CertificateExtensions,
1396 }
1397 
1398 impl Codec for CertificateEntry {
encode(&self, bytes: &mut Vec<u8>)1399     fn encode(&self, bytes: &mut Vec<u8>) {
1400         self.cert.encode(bytes);
1401         self.exts.encode(bytes);
1402     }
1403 
read(r: &mut Reader) -> Option<Self>1404     fn read(r: &mut Reader) -> Option<Self> {
1405         Some(Self {
1406             cert: key::Certificate::read(r)?,
1407             exts: CertificateExtensions::read(r)?,
1408         })
1409     }
1410 }
1411 
1412 impl CertificateEntry {
new(cert: key::Certificate) -> Self1413     pub fn new(cert: key::Certificate) -> Self {
1414         Self {
1415             cert,
1416             exts: Vec::new(),
1417         }
1418     }
1419 
has_duplicate_extension(&self) -> bool1420     pub fn has_duplicate_extension(&self) -> bool {
1421         let mut seen = collections::HashSet::new();
1422 
1423         for ext in &self.exts {
1424             let typ = ext.get_type().get_u16();
1425 
1426             if seen.contains(&typ) {
1427                 return true;
1428             }
1429             seen.insert(typ);
1430         }
1431 
1432         false
1433     }
1434 
has_unknown_extension(&self) -> bool1435     pub fn has_unknown_extension(&self) -> bool {
1436         self.exts.iter().any(|ext| {
1437             ext.get_type() != ExtensionType::StatusRequest && ext.get_type() != ExtensionType::SCT
1438         })
1439     }
1440 
get_ocsp_response(&self) -> Option<&Vec<u8>>1441     pub fn get_ocsp_response(&self) -> Option<&Vec<u8>> {
1442         self.exts
1443             .iter()
1444             .find(|ext| ext.get_type() == ExtensionType::StatusRequest)
1445             .and_then(CertificateExtension::get_cert_status)
1446     }
1447 
get_scts(&self) -> Option<&SCTList>1448     pub fn get_scts(&self) -> Option<&SCTList> {
1449         self.exts
1450             .iter()
1451             .find(|ext| ext.get_type() == ExtensionType::SCT)
1452             .and_then(CertificateExtension::get_sct_list)
1453     }
1454 }
1455 
1456 #[derive(Debug)]
1457 pub struct CertificatePayloadTLS13 {
1458     pub context: PayloadU8,
1459     pub entries: Vec<CertificateEntry>,
1460 }
1461 
1462 impl Codec for CertificatePayloadTLS13 {
encode(&self, bytes: &mut Vec<u8>)1463     fn encode(&self, bytes: &mut Vec<u8>) {
1464         self.context.encode(bytes);
1465         codec::encode_vec_u24(bytes, &self.entries);
1466     }
1467 
read(r: &mut Reader) -> Option<Self>1468     fn read(r: &mut Reader) -> Option<Self> {
1469         Some(Self {
1470             context: PayloadU8::read(r)?,
1471             entries: codec::read_vec_u24_limited::<CertificateEntry>(r, 0x10000)?,
1472         })
1473     }
1474 }
1475 
1476 impl CertificatePayloadTLS13 {
new(entries: Vec<CertificateEntry>) -> Self1477     pub fn new(entries: Vec<CertificateEntry>) -> Self {
1478         Self {
1479             context: PayloadU8::empty(),
1480             entries,
1481         }
1482     }
1483 
any_entry_has_duplicate_extension(&self) -> bool1484     pub fn any_entry_has_duplicate_extension(&self) -> bool {
1485         for entry in &self.entries {
1486             if entry.has_duplicate_extension() {
1487                 return true;
1488             }
1489         }
1490 
1491         false
1492     }
1493 
any_entry_has_unknown_extension(&self) -> bool1494     pub fn any_entry_has_unknown_extension(&self) -> bool {
1495         for entry in &self.entries {
1496             if entry.has_unknown_extension() {
1497                 return true;
1498             }
1499         }
1500 
1501         false
1502     }
1503 
any_entry_has_extension(&self) -> bool1504     pub fn any_entry_has_extension(&self) -> bool {
1505         for entry in &self.entries {
1506             if !entry.exts.is_empty() {
1507                 return true;
1508             }
1509         }
1510 
1511         false
1512     }
1513 
get_end_entity_ocsp(&self) -> Vec<u8>1514     pub fn get_end_entity_ocsp(&self) -> Vec<u8> {
1515         self.entries
1516             .first()
1517             .and_then(CertificateEntry::get_ocsp_response)
1518             .cloned()
1519             .unwrap_or_else(Vec::new)
1520     }
1521 
get_end_entity_scts(&self) -> Option<SCTList>1522     pub fn get_end_entity_scts(&self) -> Option<SCTList> {
1523         self.entries
1524             .first()
1525             .and_then(CertificateEntry::get_scts)
1526             .cloned()
1527     }
1528 
convert(&self) -> CertificatePayload1529     pub fn convert(&self) -> CertificatePayload {
1530         let mut ret = Vec::new();
1531         for entry in &self.entries {
1532             ret.push(entry.cert.clone());
1533         }
1534         ret
1535     }
1536 }
1537 
1538 #[derive(Debug)]
1539 pub enum KeyExchangeAlgorithm {
1540     BulkOnly,
1541     DH,
1542     DHE,
1543     RSA,
1544     ECDH,
1545     ECDHE,
1546 }
1547 
1548 // We don't support arbitrary curves.  It's a terrible
1549 // idea and unnecessary attack surface.  Please,
1550 // get a grip.
1551 #[derive(Debug)]
1552 pub struct ECParameters {
1553     pub curve_type: ECCurveType,
1554     pub named_group: NamedGroup,
1555 }
1556 
1557 impl Codec for ECParameters {
encode(&self, bytes: &mut Vec<u8>)1558     fn encode(&self, bytes: &mut Vec<u8>) {
1559         self.curve_type.encode(bytes);
1560         self.named_group.encode(bytes);
1561     }
1562 
read(r: &mut Reader) -> Option<Self>1563     fn read(r: &mut Reader) -> Option<Self> {
1564         let ct = ECCurveType::read(r)?;
1565 
1566         if ct != ECCurveType::NamedCurve {
1567             return None;
1568         }
1569 
1570         let grp = NamedGroup::read(r)?;
1571 
1572         Some(Self {
1573             curve_type: ct,
1574             named_group: grp,
1575         })
1576     }
1577 }
1578 
1579 #[derive(Debug, Clone)]
1580 pub struct DigitallySignedStruct {
1581     pub scheme: SignatureScheme,
1582     pub sig: PayloadU16,
1583 }
1584 
1585 impl DigitallySignedStruct {
new(scheme: SignatureScheme, sig: Vec<u8>) -> Self1586     pub fn new(scheme: SignatureScheme, sig: Vec<u8>) -> Self {
1587         Self {
1588             scheme,
1589             sig: PayloadU16::new(sig),
1590         }
1591     }
1592 }
1593 
1594 impl Codec for DigitallySignedStruct {
encode(&self, bytes: &mut Vec<u8>)1595     fn encode(&self, bytes: &mut Vec<u8>) {
1596         self.scheme.encode(bytes);
1597         self.sig.encode(bytes);
1598     }
1599 
read(r: &mut Reader) -> Option<Self>1600     fn read(r: &mut Reader) -> Option<Self> {
1601         let scheme = SignatureScheme::read(r)?;
1602         let sig = PayloadU16::read(r)?;
1603 
1604         Some(Self { scheme, sig })
1605     }
1606 }
1607 
1608 #[derive(Debug)]
1609 pub struct ClientECDHParams {
1610     pub public: PayloadU8,
1611 }
1612 
1613 impl Codec for ClientECDHParams {
encode(&self, bytes: &mut Vec<u8>)1614     fn encode(&self, bytes: &mut Vec<u8>) {
1615         self.public.encode(bytes);
1616     }
1617 
read(r: &mut Reader) -> Option<Self>1618     fn read(r: &mut Reader) -> Option<Self> {
1619         let pb = PayloadU8::read(r)?;
1620         Some(Self { public: pb })
1621     }
1622 }
1623 
1624 #[derive(Debug)]
1625 pub struct ServerECDHParams {
1626     pub curve_params: ECParameters,
1627     pub public: PayloadU8,
1628 }
1629 
1630 impl ServerECDHParams {
new(named_group: NamedGroup, pubkey: &[u8]) -> Self1631     pub fn new(named_group: NamedGroup, pubkey: &[u8]) -> Self {
1632         Self {
1633             curve_params: ECParameters {
1634                 curve_type: ECCurveType::NamedCurve,
1635                 named_group,
1636             },
1637             public: PayloadU8::new(pubkey.to_vec()),
1638         }
1639     }
1640 }
1641 
1642 impl Codec for ServerECDHParams {
encode(&self, bytes: &mut Vec<u8>)1643     fn encode(&self, bytes: &mut Vec<u8>) {
1644         self.curve_params.encode(bytes);
1645         self.public.encode(bytes);
1646     }
1647 
read(r: &mut Reader) -> Option<Self>1648     fn read(r: &mut Reader) -> Option<Self> {
1649         let cp = ECParameters::read(r)?;
1650         let pb = PayloadU8::read(r)?;
1651 
1652         Some(Self {
1653             curve_params: cp,
1654             public: pb,
1655         })
1656     }
1657 }
1658 
1659 #[derive(Debug)]
1660 pub struct ECDHEServerKeyExchange {
1661     pub params: ServerECDHParams,
1662     pub dss: DigitallySignedStruct,
1663 }
1664 
1665 impl Codec for ECDHEServerKeyExchange {
encode(&self, bytes: &mut Vec<u8>)1666     fn encode(&self, bytes: &mut Vec<u8>) {
1667         self.params.encode(bytes);
1668         self.dss.encode(bytes);
1669     }
1670 
read(r: &mut Reader) -> Option<Self>1671     fn read(r: &mut Reader) -> Option<Self> {
1672         let params = ServerECDHParams::read(r)?;
1673         let dss = DigitallySignedStruct::read(r)?;
1674 
1675         Some(Self { params, dss })
1676     }
1677 }
1678 
1679 #[derive(Debug)]
1680 pub enum ServerKeyExchangePayload {
1681     ECDHE(ECDHEServerKeyExchange),
1682     Unknown(Payload),
1683 }
1684 
1685 impl Codec for ServerKeyExchangePayload {
encode(&self, bytes: &mut Vec<u8>)1686     fn encode(&self, bytes: &mut Vec<u8>) {
1687         match *self {
1688             ServerKeyExchangePayload::ECDHE(ref x) => x.encode(bytes),
1689             ServerKeyExchangePayload::Unknown(ref x) => x.encode(bytes),
1690         }
1691     }
1692 
read(r: &mut Reader) -> Option<Self>1693     fn read(r: &mut Reader) -> Option<Self> {
1694         // read as Unknown, fully parse when we know the
1695         // KeyExchangeAlgorithm
1696         Some(Self::Unknown(Payload::read(r)))
1697     }
1698 }
1699 
1700 impl ServerKeyExchangePayload {
unwrap_given_kxa(&self, kxa: &KeyExchangeAlgorithm) -> Option<ECDHEServerKeyExchange>1701     pub fn unwrap_given_kxa(&self, kxa: &KeyExchangeAlgorithm) -> Option<ECDHEServerKeyExchange> {
1702         if let ServerKeyExchangePayload::Unknown(ref unk) = *self {
1703             let mut rd = Reader::init(&unk.0);
1704 
1705             let result = match *kxa {
1706                 KeyExchangeAlgorithm::ECDHE => ECDHEServerKeyExchange::read(&mut rd),
1707                 _ => None,
1708             };
1709 
1710             if !rd.any_left() {
1711                 return result;
1712             };
1713         }
1714 
1715         None
1716     }
1717 }
1718 
1719 // -- EncryptedExtensions (TLS1.3 only) --
1720 declare_u16_vec!(EncryptedExtensions, ServerExtension);
1721 
1722 pub trait HasServerExtensions {
get_extensions(&self) -> &[ServerExtension]1723     fn get_extensions(&self) -> &[ServerExtension];
1724 
1725     /// Returns true if there is more than one extension of a given
1726     /// type.
has_duplicate_extension(&self) -> bool1727     fn has_duplicate_extension(&self) -> bool {
1728         let mut seen = collections::HashSet::new();
1729 
1730         for ext in self.get_extensions() {
1731             let typ = ext.get_type().get_u16();
1732 
1733             if seen.contains(&typ) {
1734                 return true;
1735             }
1736             seen.insert(typ);
1737         }
1738 
1739         false
1740     }
1741 
find_extension(&self, ext: ExtensionType) -> Option<&ServerExtension>1742     fn find_extension(&self, ext: ExtensionType) -> Option<&ServerExtension> {
1743         self.get_extensions()
1744             .iter()
1745             .find(|x| x.get_type() == ext)
1746     }
1747 
get_alpn_protocol(&self) -> Option<&[u8]>1748     fn get_alpn_protocol(&self) -> Option<&[u8]> {
1749         let ext = self.find_extension(ExtensionType::ALProtocolNegotiation)?;
1750         match *ext {
1751             ServerExtension::Protocols(ref protos) => protos.as_single_slice(),
1752             _ => None,
1753         }
1754     }
1755 
get_quic_params_extension(&self) -> Option<Vec<u8>>1756     fn get_quic_params_extension(&self) -> Option<Vec<u8>> {
1757         let ext = self
1758             .find_extension(ExtensionType::TransportParameters)
1759             .or_else(|| self.find_extension(ExtensionType::TransportParametersDraft))?;
1760         match *ext {
1761             ServerExtension::TransportParameters(ref bytes)
1762             | ServerExtension::TransportParametersDraft(ref bytes) => Some(bytes.to_vec()),
1763             _ => None,
1764         }
1765     }
1766 
early_data_extension_offered(&self) -> bool1767     fn early_data_extension_offered(&self) -> bool {
1768         self.find_extension(ExtensionType::EarlyData)
1769             .is_some()
1770     }
1771 }
1772 
1773 impl HasServerExtensions for EncryptedExtensions {
get_extensions(&self) -> &[ServerExtension]1774     fn get_extensions(&self) -> &[ServerExtension] {
1775         self
1776     }
1777 }
1778 
1779 // -- CertificateRequest and sundries --
1780 declare_u8_vec!(ClientCertificateTypes, ClientCertificateType);
1781 pub type DistinguishedName = PayloadU16;
1782 pub type DistinguishedNames = VecU16OfPayloadU16;
1783 
1784 #[derive(Debug)]
1785 pub struct CertificateRequestPayload {
1786     pub certtypes: ClientCertificateTypes,
1787     pub sigschemes: SupportedSignatureSchemes,
1788     pub canames: DistinguishedNames,
1789 }
1790 
1791 impl Codec for CertificateRequestPayload {
encode(&self, bytes: &mut Vec<u8>)1792     fn encode(&self, bytes: &mut Vec<u8>) {
1793         self.certtypes.encode(bytes);
1794         self.sigschemes.encode(bytes);
1795         self.canames.encode(bytes);
1796     }
1797 
read(r: &mut Reader) -> Option<Self>1798     fn read(r: &mut Reader) -> Option<Self> {
1799         let certtypes = ClientCertificateTypes::read(r)?;
1800         let sigschemes = SupportedSignatureSchemes::read(r)?;
1801         let canames = DistinguishedNames::read(r)?;
1802 
1803         if sigschemes.is_empty() {
1804             warn!("meaningless CertificateRequest message");
1805             None
1806         } else {
1807             Some(Self {
1808                 certtypes,
1809                 sigschemes,
1810                 canames,
1811             })
1812         }
1813     }
1814 }
1815 
1816 #[derive(Debug)]
1817 pub enum CertReqExtension {
1818     SignatureAlgorithms(SupportedSignatureSchemes),
1819     AuthorityNames(DistinguishedNames),
1820     Unknown(UnknownExtension),
1821 }
1822 
1823 impl CertReqExtension {
get_type(&self) -> ExtensionType1824     pub fn get_type(&self) -> ExtensionType {
1825         match *self {
1826             CertReqExtension::SignatureAlgorithms(_) => ExtensionType::SignatureAlgorithms,
1827             CertReqExtension::AuthorityNames(_) => ExtensionType::CertificateAuthorities,
1828             CertReqExtension::Unknown(ref r) => r.typ,
1829         }
1830     }
1831 }
1832 
1833 impl Codec for CertReqExtension {
encode(&self, bytes: &mut Vec<u8>)1834     fn encode(&self, bytes: &mut Vec<u8>) {
1835         self.get_type().encode(bytes);
1836 
1837         let mut sub: Vec<u8> = Vec::new();
1838         match *self {
1839             CertReqExtension::SignatureAlgorithms(ref r) => r.encode(&mut sub),
1840             CertReqExtension::AuthorityNames(ref r) => r.encode(&mut sub),
1841             CertReqExtension::Unknown(ref r) => r.encode(&mut sub),
1842         }
1843 
1844         (sub.len() as u16).encode(bytes);
1845         bytes.append(&mut sub);
1846     }
1847 
read(r: &mut Reader) -> Option<Self>1848     fn read(r: &mut Reader) -> Option<Self> {
1849         let typ = ExtensionType::read(r)?;
1850         let len = u16::read(r)? as usize;
1851         let mut sub = r.sub(len)?;
1852 
1853         let ext = match typ {
1854             ExtensionType::SignatureAlgorithms => {
1855                 let schemes = SupportedSignatureSchemes::read(&mut sub)?;
1856                 if schemes.is_empty() {
1857                     return None;
1858                 }
1859                 Self::SignatureAlgorithms(schemes)
1860             }
1861             ExtensionType::CertificateAuthorities => {
1862                 let cas = DistinguishedNames::read(&mut sub)?;
1863                 Self::AuthorityNames(cas)
1864             }
1865             _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)),
1866         };
1867 
1868         if sub.any_left() {
1869             None
1870         } else {
1871             Some(ext)
1872         }
1873     }
1874 }
1875 
1876 declare_u16_vec!(CertReqExtensions, CertReqExtension);
1877 
1878 #[derive(Debug)]
1879 pub struct CertificateRequestPayloadTLS13 {
1880     pub context: PayloadU8,
1881     pub extensions: CertReqExtensions,
1882 }
1883 
1884 impl Codec for CertificateRequestPayloadTLS13 {
encode(&self, bytes: &mut Vec<u8>)1885     fn encode(&self, bytes: &mut Vec<u8>) {
1886         self.context.encode(bytes);
1887         self.extensions.encode(bytes);
1888     }
1889 
read(r: &mut Reader) -> Option<Self>1890     fn read(r: &mut Reader) -> Option<Self> {
1891         let context = PayloadU8::read(r)?;
1892         let extensions = CertReqExtensions::read(r)?;
1893 
1894         Some(Self {
1895             context,
1896             extensions,
1897         })
1898     }
1899 }
1900 
1901 impl CertificateRequestPayloadTLS13 {
find_extension(&self, ext: ExtensionType) -> Option<&CertReqExtension>1902     pub fn find_extension(&self, ext: ExtensionType) -> Option<&CertReqExtension> {
1903         self.extensions
1904             .iter()
1905             .find(|x| x.get_type() == ext)
1906     }
1907 
get_sigalgs_extension(&self) -> Option<&SupportedSignatureSchemes>1908     pub fn get_sigalgs_extension(&self) -> Option<&SupportedSignatureSchemes> {
1909         let ext = self.find_extension(ExtensionType::SignatureAlgorithms)?;
1910         match *ext {
1911             CertReqExtension::SignatureAlgorithms(ref sa) => Some(sa),
1912             _ => None,
1913         }
1914     }
1915 
get_authorities_extension(&self) -> Option<&DistinguishedNames>1916     pub fn get_authorities_extension(&self) -> Option<&DistinguishedNames> {
1917         let ext = self.find_extension(ExtensionType::CertificateAuthorities)?;
1918         match *ext {
1919             CertReqExtension::AuthorityNames(ref an) => Some(an),
1920             _ => None,
1921         }
1922     }
1923 }
1924 
1925 // -- NewSessionTicket --
1926 #[derive(Debug)]
1927 pub struct NewSessionTicketPayload {
1928     pub lifetime_hint: u32,
1929     pub ticket: PayloadU16,
1930 }
1931 
1932 impl NewSessionTicketPayload {
new(lifetime_hint: u32, ticket: Vec<u8>) -> Self1933     pub fn new(lifetime_hint: u32, ticket: Vec<u8>) -> Self {
1934         Self {
1935             lifetime_hint,
1936             ticket: PayloadU16::new(ticket),
1937         }
1938     }
1939 }
1940 
1941 impl Codec for NewSessionTicketPayload {
encode(&self, bytes: &mut Vec<u8>)1942     fn encode(&self, bytes: &mut Vec<u8>) {
1943         self.lifetime_hint.encode(bytes);
1944         self.ticket.encode(bytes);
1945     }
1946 
read(r: &mut Reader) -> Option<Self>1947     fn read(r: &mut Reader) -> Option<Self> {
1948         let lifetime = u32::read(r)?;
1949         let ticket = PayloadU16::read(r)?;
1950 
1951         Some(Self {
1952             lifetime_hint: lifetime,
1953             ticket,
1954         })
1955     }
1956 }
1957 
1958 // -- NewSessionTicket electric boogaloo --
1959 #[derive(Debug)]
1960 pub enum NewSessionTicketExtension {
1961     EarlyData(u32),
1962     Unknown(UnknownExtension),
1963 }
1964 
1965 impl NewSessionTicketExtension {
get_type(&self) -> ExtensionType1966     pub fn get_type(&self) -> ExtensionType {
1967         match *self {
1968             NewSessionTicketExtension::EarlyData(_) => ExtensionType::EarlyData,
1969             NewSessionTicketExtension::Unknown(ref r) => r.typ,
1970         }
1971     }
1972 }
1973 
1974 impl Codec for NewSessionTicketExtension {
encode(&self, bytes: &mut Vec<u8>)1975     fn encode(&self, bytes: &mut Vec<u8>) {
1976         self.get_type().encode(bytes);
1977 
1978         let mut sub: Vec<u8> = Vec::new();
1979         match *self {
1980             NewSessionTicketExtension::EarlyData(r) => r.encode(&mut sub),
1981             NewSessionTicketExtension::Unknown(ref r) => r.encode(&mut sub),
1982         }
1983 
1984         (sub.len() as u16).encode(bytes);
1985         bytes.append(&mut sub);
1986     }
1987 
read(r: &mut Reader) -> Option<Self>1988     fn read(r: &mut Reader) -> Option<Self> {
1989         let typ = ExtensionType::read(r)?;
1990         let len = u16::read(r)? as usize;
1991         let mut sub = r.sub(len)?;
1992 
1993         let ext = match typ {
1994             ExtensionType::EarlyData => Self::EarlyData(u32::read(&mut sub)?),
1995             _ => Self::Unknown(UnknownExtension::read(typ, &mut sub)),
1996         };
1997 
1998         if sub.any_left() {
1999             None
2000         } else {
2001             Some(ext)
2002         }
2003     }
2004 }
2005 
2006 declare_u16_vec!(NewSessionTicketExtensions, NewSessionTicketExtension);
2007 
2008 #[derive(Debug)]
2009 pub struct NewSessionTicketPayloadTLS13 {
2010     pub lifetime: u32,
2011     pub age_add: u32,
2012     pub nonce: PayloadU8,
2013     pub ticket: PayloadU16,
2014     pub exts: NewSessionTicketExtensions,
2015 }
2016 
2017 impl NewSessionTicketPayloadTLS13 {
new(lifetime: u32, age_add: u32, nonce: Vec<u8>, ticket: Vec<u8>) -> Self2018     pub fn new(lifetime: u32, age_add: u32, nonce: Vec<u8>, ticket: Vec<u8>) -> Self {
2019         Self {
2020             lifetime,
2021             age_add,
2022             nonce: PayloadU8::new(nonce),
2023             ticket: PayloadU16::new(ticket),
2024             exts: vec![],
2025         }
2026     }
2027 
find_extension(&self, ext: ExtensionType) -> Option<&NewSessionTicketExtension>2028     pub fn find_extension(&self, ext: ExtensionType) -> Option<&NewSessionTicketExtension> {
2029         self.exts
2030             .iter()
2031             .find(|x| x.get_type() == ext)
2032     }
2033 
get_max_early_data_size(&self) -> Option<u32>2034     pub fn get_max_early_data_size(&self) -> Option<u32> {
2035         let ext = self.find_extension(ExtensionType::EarlyData)?;
2036         match *ext {
2037             NewSessionTicketExtension::EarlyData(ref sz) => Some(*sz),
2038             _ => None,
2039         }
2040     }
2041 }
2042 
2043 impl Codec for NewSessionTicketPayloadTLS13 {
encode(&self, bytes: &mut Vec<u8>)2044     fn encode(&self, bytes: &mut Vec<u8>) {
2045         self.lifetime.encode(bytes);
2046         self.age_add.encode(bytes);
2047         self.nonce.encode(bytes);
2048         self.ticket.encode(bytes);
2049         self.exts.encode(bytes);
2050     }
2051 
read(r: &mut Reader) -> Option<Self>2052     fn read(r: &mut Reader) -> Option<Self> {
2053         let lifetime = u32::read(r)?;
2054         let age_add = u32::read(r)?;
2055         let nonce = PayloadU8::read(r)?;
2056         let ticket = PayloadU16::read(r)?;
2057         let exts = NewSessionTicketExtensions::read(r)?;
2058 
2059         Some(Self {
2060             lifetime,
2061             age_add,
2062             nonce,
2063             ticket,
2064             exts,
2065         })
2066     }
2067 }
2068 
2069 // -- RFC6066 certificate status types
2070 
2071 /// Only supports OCSP
2072 #[derive(Debug)]
2073 pub struct CertificateStatus {
2074     pub ocsp_response: PayloadU24,
2075 }
2076 
2077 impl Codec for CertificateStatus {
encode(&self, bytes: &mut Vec<u8>)2078     fn encode(&self, bytes: &mut Vec<u8>) {
2079         CertificateStatusType::OCSP.encode(bytes);
2080         self.ocsp_response.encode(bytes);
2081     }
2082 
read(r: &mut Reader) -> Option<Self>2083     fn read(r: &mut Reader) -> Option<Self> {
2084         let typ = CertificateStatusType::read(r)?;
2085 
2086         match typ {
2087             CertificateStatusType::OCSP => Some(Self {
2088                 ocsp_response: PayloadU24::read(r)?,
2089             }),
2090             _ => None,
2091         }
2092     }
2093 }
2094 
2095 impl CertificateStatus {
new(ocsp: Vec<u8>) -> Self2096     pub fn new(ocsp: Vec<u8>) -> Self {
2097         Self {
2098             ocsp_response: PayloadU24::new(ocsp),
2099         }
2100     }
2101 
into_inner(self) -> Vec<u8>2102     pub fn into_inner(self) -> Vec<u8> {
2103         self.ocsp_response.0
2104     }
2105 }
2106 
2107 #[derive(Debug)]
2108 pub enum HandshakePayload {
2109     HelloRequest,
2110     ClientHello(ClientHelloPayload),
2111     ServerHello(ServerHelloPayload),
2112     HelloRetryRequest(HelloRetryRequest),
2113     Certificate(CertificatePayload),
2114     CertificateTLS13(CertificatePayloadTLS13),
2115     ServerKeyExchange(ServerKeyExchangePayload),
2116     CertificateRequest(CertificateRequestPayload),
2117     CertificateRequestTLS13(CertificateRequestPayloadTLS13),
2118     CertificateVerify(DigitallySignedStruct),
2119     ServerHelloDone,
2120     EarlyData,
2121     EndOfEarlyData,
2122     ClientKeyExchange(Payload),
2123     NewSessionTicket(NewSessionTicketPayload),
2124     NewSessionTicketTLS13(NewSessionTicketPayloadTLS13),
2125     EncryptedExtensions(EncryptedExtensions),
2126     KeyUpdate(KeyUpdateRequest),
2127     Finished(Payload),
2128     CertificateStatus(CertificateStatus),
2129     MessageHash(Payload),
2130     Unknown(Payload),
2131 }
2132 
2133 impl HandshakePayload {
encode(&self, bytes: &mut Vec<u8>)2134     fn encode(&self, bytes: &mut Vec<u8>) {
2135         match *self {
2136             HandshakePayload::HelloRequest
2137             | HandshakePayload::ServerHelloDone
2138             | HandshakePayload::EarlyData
2139             | HandshakePayload::EndOfEarlyData => {}
2140             HandshakePayload::ClientHello(ref x) => x.encode(bytes),
2141             HandshakePayload::ServerHello(ref x) => x.encode(bytes),
2142             HandshakePayload::HelloRetryRequest(ref x) => x.encode(bytes),
2143             HandshakePayload::Certificate(ref x) => x.encode(bytes),
2144             HandshakePayload::CertificateTLS13(ref x) => x.encode(bytes),
2145             HandshakePayload::ServerKeyExchange(ref x) => x.encode(bytes),
2146             HandshakePayload::ClientKeyExchange(ref x) => x.encode(bytes),
2147             HandshakePayload::CertificateRequest(ref x) => x.encode(bytes),
2148             HandshakePayload::CertificateRequestTLS13(ref x) => x.encode(bytes),
2149             HandshakePayload::CertificateVerify(ref x) => x.encode(bytes),
2150             HandshakePayload::NewSessionTicket(ref x) => x.encode(bytes),
2151             HandshakePayload::NewSessionTicketTLS13(ref x) => x.encode(bytes),
2152             HandshakePayload::EncryptedExtensions(ref x) => x.encode(bytes),
2153             HandshakePayload::KeyUpdate(ref x) => x.encode(bytes),
2154             HandshakePayload::Finished(ref x) => x.encode(bytes),
2155             HandshakePayload::CertificateStatus(ref x) => x.encode(bytes),
2156             HandshakePayload::MessageHash(ref x) => x.encode(bytes),
2157             HandshakePayload::Unknown(ref x) => x.encode(bytes),
2158         }
2159     }
2160 }
2161 
2162 #[derive(Debug)]
2163 pub struct HandshakeMessagePayload {
2164     pub typ: HandshakeType,
2165     pub payload: HandshakePayload,
2166 }
2167 
2168 impl Codec for HandshakeMessagePayload {
encode(&self, bytes: &mut Vec<u8>)2169     fn encode(&self, bytes: &mut Vec<u8>) {
2170         // encode payload to learn length
2171         let mut sub: Vec<u8> = Vec::new();
2172         self.payload.encode(&mut sub);
2173 
2174         // output type, length, and encoded payload
2175         match self.typ {
2176             HandshakeType::HelloRetryRequest => HandshakeType::ServerHello,
2177             _ => self.typ,
2178         }
2179         .encode(bytes);
2180         codec::u24(sub.len() as u32).encode(bytes);
2181         bytes.append(&mut sub);
2182     }
2183 
read(r: &mut Reader) -> Option<Self>2184     fn read(r: &mut Reader) -> Option<Self> {
2185         Self::read_version(r, ProtocolVersion::TLSv1_2)
2186     }
2187 }
2188 
2189 impl HandshakeMessagePayload {
read_version(r: &mut Reader, vers: ProtocolVersion) -> Option<Self>2190     pub fn read_version(r: &mut Reader, vers: ProtocolVersion) -> Option<Self> {
2191         let mut typ = HandshakeType::read(r)?;
2192         let len = codec::u24::read(r)?.0 as usize;
2193         let mut sub = r.sub(len)?;
2194 
2195         let payload = match typ {
2196             HandshakeType::HelloRequest if sub.left() == 0 => HandshakePayload::HelloRequest,
2197             HandshakeType::ClientHello => {
2198                 HandshakePayload::ClientHello(ClientHelloPayload::read(&mut sub)?)
2199             }
2200             HandshakeType::ServerHello => {
2201                 let version = ProtocolVersion::read(&mut sub)?;
2202                 let random = Random::read(&mut sub)?;
2203 
2204                 if random == HELLO_RETRY_REQUEST_RANDOM {
2205                     let mut hrr = HelloRetryRequest::read(&mut sub)?;
2206                     hrr.legacy_version = version;
2207                     typ = HandshakeType::HelloRetryRequest;
2208                     HandshakePayload::HelloRetryRequest(hrr)
2209                 } else {
2210                     let mut shp = ServerHelloPayload::read(&mut sub)?;
2211                     shp.legacy_version = version;
2212                     shp.random = random;
2213                     HandshakePayload::ServerHello(shp)
2214                 }
2215             }
2216             HandshakeType::Certificate if vers == ProtocolVersion::TLSv1_3 => {
2217                 let p = CertificatePayloadTLS13::read(&mut sub)?;
2218                 HandshakePayload::CertificateTLS13(p)
2219             }
2220             HandshakeType::Certificate => {
2221                 HandshakePayload::Certificate(CertificatePayload::read(&mut sub)?)
2222             }
2223             HandshakeType::ServerKeyExchange => {
2224                 let p = ServerKeyExchangePayload::read(&mut sub)?;
2225                 HandshakePayload::ServerKeyExchange(p)
2226             }
2227             HandshakeType::ServerHelloDone => {
2228                 if sub.any_left() {
2229                     return None;
2230                 }
2231                 HandshakePayload::ServerHelloDone
2232             }
2233             HandshakeType::ClientKeyExchange => {
2234                 HandshakePayload::ClientKeyExchange(Payload::read(&mut sub))
2235             }
2236             HandshakeType::CertificateRequest if vers == ProtocolVersion::TLSv1_3 => {
2237                 let p = CertificateRequestPayloadTLS13::read(&mut sub)?;
2238                 HandshakePayload::CertificateRequestTLS13(p)
2239             }
2240             HandshakeType::CertificateRequest => {
2241                 let p = CertificateRequestPayload::read(&mut sub)?;
2242                 HandshakePayload::CertificateRequest(p)
2243             }
2244             HandshakeType::CertificateVerify => {
2245                 HandshakePayload::CertificateVerify(DigitallySignedStruct::read(&mut sub)?)
2246             }
2247             HandshakeType::NewSessionTicket if vers == ProtocolVersion::TLSv1_3 => {
2248                 let p = NewSessionTicketPayloadTLS13::read(&mut sub)?;
2249                 HandshakePayload::NewSessionTicketTLS13(p)
2250             }
2251             HandshakeType::NewSessionTicket => {
2252                 let p = NewSessionTicketPayload::read(&mut sub)?;
2253                 HandshakePayload::NewSessionTicket(p)
2254             }
2255             HandshakeType::EncryptedExtensions => {
2256                 HandshakePayload::EncryptedExtensions(EncryptedExtensions::read(&mut sub)?)
2257             }
2258             HandshakeType::KeyUpdate => {
2259                 HandshakePayload::KeyUpdate(KeyUpdateRequest::read(&mut sub)?)
2260             }
2261             HandshakeType::Finished => HandshakePayload::Finished(Payload::read(&mut sub)),
2262             HandshakeType::CertificateStatus => {
2263                 HandshakePayload::CertificateStatus(CertificateStatus::read(&mut sub)?)
2264             }
2265             HandshakeType::MessageHash => {
2266                 // does not appear on the wire
2267                 return None;
2268             }
2269             HandshakeType::HelloRetryRequest => {
2270                 // not legal on wire
2271                 return None;
2272             }
2273             _ => HandshakePayload::Unknown(Payload::read(&mut sub)),
2274         };
2275 
2276         if sub.any_left() {
2277             None
2278         } else {
2279             Some(Self { typ, payload })
2280         }
2281     }
2282 
build_key_update_notify() -> Self2283     pub fn build_key_update_notify() -> Self {
2284         Self {
2285             typ: HandshakeType::KeyUpdate,
2286             payload: HandshakePayload::KeyUpdate(KeyUpdateRequest::UpdateNotRequested),
2287         }
2288     }
2289 
get_encoding_for_binder_signing(&self) -> Vec<u8>2290     pub fn get_encoding_for_binder_signing(&self) -> Vec<u8> {
2291         let mut ret = self.get_encoding();
2292 
2293         let binder_len = match self.payload {
2294             HandshakePayload::ClientHello(ref ch) => match ch.extensions.last() {
2295                 Some(ClientExtension::PresharedKey(ref offer)) => {
2296                     let mut binders_encoding = Vec::new();
2297                     offer
2298                         .binders
2299                         .encode(&mut binders_encoding);
2300                     binders_encoding.len()
2301                 }
2302                 _ => 0,
2303             },
2304             _ => 0,
2305         };
2306 
2307         let ret_len = ret.len() - binder_len;
2308         ret.truncate(ret_len);
2309         ret
2310     }
2311 
build_handshake_hash(hash: &[u8]) -> Self2312     pub fn build_handshake_hash(hash: &[u8]) -> Self {
2313         Self {
2314             typ: HandshakeType::MessageHash,
2315             payload: HandshakePayload::MessageHash(Payload::new(hash.to_vec())),
2316         }
2317     }
2318 }
2319