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