• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package runner
6
7import (
8	"encoding/binary"
9	"fmt"
10)
11
12func writeLen(buf []byte, v, size int) {
13	for i := 0; i < size; i++ {
14		buf[size-i-1] = byte(v)
15		v >>= 8
16	}
17	if v != 0 {
18		panic("length is too long")
19	}
20}
21
22type byteBuilder struct {
23	buf       *[]byte
24	start     int
25	prefixLen int
26	child     *byteBuilder
27}
28
29func newByteBuilder() *byteBuilder {
30	buf := make([]byte, 0, 32)
31	return &byteBuilder{buf: &buf}
32}
33
34func (bb *byteBuilder) len() int {
35	return len(*bb.buf) - bb.start - bb.prefixLen
36}
37
38func (bb *byteBuilder) data() []byte {
39	bb.flush()
40	return (*bb.buf)[bb.start+bb.prefixLen:]
41}
42
43func (bb *byteBuilder) flush() {
44	if bb.child == nil {
45		return
46	}
47	bb.child.flush()
48	writeLen((*bb.buf)[bb.child.start:], bb.child.len(), bb.child.prefixLen)
49	bb.child = nil
50	return
51}
52
53func (bb *byteBuilder) finish() []byte {
54	bb.flush()
55	return *bb.buf
56}
57
58func (bb *byteBuilder) addU8(u uint8) {
59	bb.flush()
60	*bb.buf = append(*bb.buf, u)
61}
62
63func (bb *byteBuilder) addU16(u uint16) {
64	bb.flush()
65	*bb.buf = append(*bb.buf, byte(u>>8), byte(u))
66}
67
68func (bb *byteBuilder) addU24(u int) {
69	bb.flush()
70	*bb.buf = append(*bb.buf, byte(u>>16), byte(u>>8), byte(u))
71}
72
73func (bb *byteBuilder) addU32(u uint32) {
74	bb.flush()
75	*bb.buf = append(*bb.buf, byte(u>>24), byte(u>>16), byte(u>>8), byte(u))
76}
77
78func (bb *byteBuilder) addU64(u uint64) {
79	bb.flush()
80	var b [8]byte
81	binary.BigEndian.PutUint64(b[:], u)
82	*bb.buf = append(*bb.buf, b[:]...)
83}
84
85func (bb *byteBuilder) addU8LengthPrefixed() *byteBuilder {
86	return bb.createChild(1)
87}
88
89func (bb *byteBuilder) addU16LengthPrefixed() *byteBuilder {
90	return bb.createChild(2)
91}
92
93func (bb *byteBuilder) addU24LengthPrefixed() *byteBuilder {
94	return bb.createChild(3)
95}
96
97func (bb *byteBuilder) addU32LengthPrefixed() *byteBuilder {
98	return bb.createChild(4)
99}
100
101func (bb *byteBuilder) addBytes(b []byte) {
102	bb.flush()
103	*bb.buf = append(*bb.buf, b...)
104}
105
106func (bb *byteBuilder) createChild(lengthPrefixSize int) *byteBuilder {
107	bb.flush()
108	bb.child = &byteBuilder{
109		buf:       bb.buf,
110		start:     len(*bb.buf),
111		prefixLen: lengthPrefixSize,
112	}
113	for i := 0; i < lengthPrefixSize; i++ {
114		*bb.buf = append(*bb.buf, 0)
115	}
116	return bb.child
117}
118
119func (bb *byteBuilder) discardChild() {
120	if bb.child == nil {
121		return
122	}
123	*bb.buf = (*bb.buf)[:bb.child.start]
124	bb.child = nil
125}
126
127type byteReader []byte
128
129func (br *byteReader) readInternal(out *byteReader, n int) bool {
130	if len(*br) < n {
131		return false
132	}
133	*out = (*br)[:n]
134	*br = (*br)[n:]
135	return true
136}
137
138func (br *byteReader) readBytes(out *[]byte, n int) bool {
139	var child byteReader
140	if !br.readInternal(&child, n) {
141		return false
142	}
143	*out = []byte(child)
144	return true
145}
146
147func (br *byteReader) readUint(out *uint64, n int) bool {
148	var b []byte
149	if !br.readBytes(&b, n) {
150		return false
151	}
152	*out = 0
153	for _, v := range b {
154		*out <<= 8
155		*out |= uint64(v)
156	}
157	return true
158}
159
160func (br *byteReader) readU8(out *uint8) bool {
161	var b []byte
162	if !br.readBytes(&b, 1) {
163		return false
164	}
165	*out = b[0]
166	return true
167}
168
169func (br *byteReader) readU16(out *uint16) bool {
170	var v uint64
171	if !br.readUint(&v, 2) {
172		return false
173	}
174	*out = uint16(v)
175	return true
176}
177
178func (br *byteReader) readU24(out *uint32) bool {
179	var v uint64
180	if !br.readUint(&v, 3) {
181		return false
182	}
183	*out = uint32(v)
184	return true
185}
186
187func (br *byteReader) readU32(out *uint32) bool {
188	var v uint64
189	if !br.readUint(&v, 4) {
190		return false
191	}
192	*out = uint32(v)
193	return true
194}
195
196func (br *byteReader) readU64(out *uint64) bool {
197	return br.readUint(out, 8)
198}
199
200func (br *byteReader) readLengthPrefixed(out *byteReader, n int) bool {
201	var length uint64
202	return br.readUint(&length, n) &&
203		uint64(len(*br)) >= length &&
204		br.readInternal(out, int(length))
205}
206
207func (br *byteReader) readLengthPrefixedBytes(out *[]byte, n int) bool {
208	var length uint64
209	return br.readUint(&length, n) &&
210		uint64(len(*br)) >= length &&
211		br.readBytes(out, int(length))
212}
213
214func (br *byteReader) readU8LengthPrefixed(out *byteReader) bool {
215	return br.readLengthPrefixed(out, 1)
216}
217func (br *byteReader) readU8LengthPrefixedBytes(out *[]byte) bool {
218	return br.readLengthPrefixedBytes(out, 1)
219}
220
221func (br *byteReader) readU16LengthPrefixed(out *byteReader) bool {
222	return br.readLengthPrefixed(out, 2)
223}
224func (br *byteReader) readU16LengthPrefixedBytes(out *[]byte) bool {
225	return br.readLengthPrefixedBytes(out, 2)
226}
227
228func (br *byteReader) readU24LengthPrefixed(out *byteReader) bool {
229	return br.readLengthPrefixed(out, 3)
230}
231func (br *byteReader) readU24LengthPrefixedBytes(out *[]byte) bool {
232	return br.readLengthPrefixedBytes(out, 3)
233}
234
235func (br *byteReader) readU32LengthPrefixed(out *byteReader) bool {
236	return br.readLengthPrefixed(out, 4)
237}
238func (br *byteReader) readU32LengthPrefixedBytes(out *[]byte) bool {
239	return br.readLengthPrefixedBytes(out, 4)
240}
241
242type keyShareEntry struct {
243	group       CurveID
244	keyExchange []byte
245}
246
247type pskIdentity struct {
248	ticket              []uint8
249	obfuscatedTicketAge uint32
250}
251
252type HPKECipherSuite struct {
253	KDF  uint16
254	AEAD uint16
255}
256
257type ECHConfig struct {
258	PublicName   string
259	PublicKey    []byte
260	KEM          uint16
261	CipherSuites []HPKECipherSuite
262	MaxNameLen   uint16
263}
264
265func MarshalECHConfig(e *ECHConfig) []byte {
266	bb := newByteBuilder()
267	// ECHConfig's wire format reuses the encrypted_client_hello extension
268	// codepoint as a version identifier.
269	bb.addU16(extensionEncryptedClientHello)
270	contents := bb.addU16LengthPrefixed()
271	contents.addU16LengthPrefixed().addBytes([]byte(e.PublicName))
272	contents.addU16LengthPrefixed().addBytes(e.PublicKey)
273	contents.addU16(e.KEM)
274	cipherSuites := contents.addU16LengthPrefixed()
275	for _, suite := range e.CipherSuites {
276		cipherSuites.addU16(suite.KDF)
277		cipherSuites.addU16(suite.AEAD)
278	}
279	contents.addU16(e.MaxNameLen)
280	contents.addU16(0) // Empty extensions field
281	return bb.finish()
282}
283
284// The contents of a CH "encrypted_client_hello" extension.
285// https://tools.ietf.org/html/draft-ietf-tls-esni-09
286type clientECH struct {
287	hpkeKDF  uint16
288	hpkeAEAD uint16
289	configID []byte
290	enc      []byte
291	payload  []byte
292}
293
294type clientHelloMsg struct {
295	raw                       []byte
296	isDTLS                    bool
297	vers                      uint16
298	random                    []byte
299	sessionID                 []byte
300	cookie                    []byte
301	cipherSuites              []uint16
302	compressionMethods        []uint8
303	nextProtoNeg              bool
304	serverName                string
305	clientECH                 *clientECH
306	echIsInner                []byte
307	ocspStapling              bool
308	supportedCurves           []CurveID
309	supportedPoints           []uint8
310	hasKeyShares              bool
311	keyShares                 []keyShareEntry
312	keySharesRaw              []byte
313	trailingKeyShareData      bool
314	pskIdentities             []pskIdentity
315	pskKEModes                []byte
316	pskBinders                [][]uint8
317	hasEarlyData              bool
318	tls13Cookie               []byte
319	ticketSupported           bool
320	sessionTicket             []uint8
321	signatureAlgorithms       []signatureAlgorithm
322	signatureAlgorithmsCert   []signatureAlgorithm
323	supportedVersions         []uint16
324	secureRenegotiation       []byte
325	alpnProtocols             []string
326	quicTransportParams       []byte
327	quicTransportParamsLegacy []byte
328	duplicateExtension        bool
329	channelIDSupported        bool
330	tokenBindingParams        []byte
331	tokenBindingVersion       uint16
332	extendedMasterSecret      bool
333	srtpProtectionProfiles    []uint16
334	srtpMasterKeyIdentifier   string
335	sctListSupported          bool
336	customExtension           string
337	hasGREASEExtension        bool
338	omitExtensions            bool
339	emptyExtensions           bool
340	pad                       int
341	compressedCertAlgs        []uint16
342	delegatedCredentials      bool
343	alpsProtocols             []string
344	prefixExtensions          []uint16
345}
346
347func (m *clientHelloMsg) marshalKeyShares(bb *byteBuilder) {
348	keyShares := bb.addU16LengthPrefixed()
349	for _, keyShare := range m.keyShares {
350		keyShares.addU16(uint16(keyShare.group))
351		keyExchange := keyShares.addU16LengthPrefixed()
352		keyExchange.addBytes(keyShare.keyExchange)
353	}
354	if m.trailingKeyShareData {
355		keyShares.addU8(0)
356	}
357}
358
359func (m *clientHelloMsg) marshal() []byte {
360	if m.raw != nil {
361		return m.raw
362	}
363
364	handshakeMsg := newByteBuilder()
365	handshakeMsg.addU8(typeClientHello)
366	hello := handshakeMsg.addU24LengthPrefixed()
367	hello.addU16(m.vers)
368	hello.addBytes(m.random)
369	sessionID := hello.addU8LengthPrefixed()
370	sessionID.addBytes(m.sessionID)
371	if m.isDTLS {
372		cookie := hello.addU8LengthPrefixed()
373		cookie.addBytes(m.cookie)
374	}
375	cipherSuites := hello.addU16LengthPrefixed()
376	for _, suite := range m.cipherSuites {
377		cipherSuites.addU16(suite)
378	}
379	compressionMethods := hello.addU8LengthPrefixed()
380	compressionMethods.addBytes(m.compressionMethods)
381
382	type extension struct {
383		id   uint16
384		body []byte
385	}
386	var extensions []extension
387
388	if m.duplicateExtension {
389		// Add a duplicate bogus extension at the beginning and end.
390		extensions = append(extensions, extension{id: extensionDuplicate})
391	}
392	if m.nextProtoNeg {
393		extensions = append(extensions, extension{id: extensionNextProtoNeg})
394	}
395	if len(m.serverName) > 0 {
396		// RFC 3546, section 3.1
397		//
398		// struct {
399		//     NameType name_type;
400		//     select (name_type) {
401		//         case host_name: HostName;
402		//     } name;
403		// } ServerName;
404		//
405		// enum {
406		//     host_name(0), (255)
407		// } NameType;
408		//
409		// opaque HostName<1..2^16-1>;
410		//
411		// struct {
412		//     ServerName server_name_list<1..2^16-1>
413		// } ServerNameList;
414
415		serverNameList := newByteBuilder()
416		serverName := serverNameList.addU16LengthPrefixed()
417		serverName.addU8(0) // NameType host_name(0)
418		hostName := serverName.addU16LengthPrefixed()
419		hostName.addBytes([]byte(m.serverName))
420
421		extensions = append(extensions, extension{
422			id:   extensionServerName,
423			body: serverNameList.finish(),
424		})
425	}
426	if m.clientECH != nil {
427		body := newByteBuilder()
428		body.addU16(m.clientECH.hpkeKDF)
429		body.addU16(m.clientECH.hpkeAEAD)
430		body.addU8LengthPrefixed().addBytes(m.clientECH.configID)
431		body.addU16LengthPrefixed().addBytes(m.clientECH.enc)
432		body.addU16LengthPrefixed().addBytes(m.clientECH.payload)
433
434		extensions = append(extensions, extension{
435			id:   extensionEncryptedClientHello,
436			body: body.finish(),
437		})
438	}
439	if m.echIsInner != nil {
440		extensions = append(extensions, extension{
441			id:   extensionECHIsInner,
442			body: m.echIsInner,
443		})
444	}
445	if m.ocspStapling {
446		certificateStatusRequest := newByteBuilder()
447		// RFC 4366, section 3.6
448		certificateStatusRequest.addU8(1) // OCSP type
449		// Two zero valued uint16s for the two lengths.
450		certificateStatusRequest.addU16(0) // ResponderID length
451		certificateStatusRequest.addU16(0) // Extensions length
452		extensions = append(extensions, extension{
453			id:   extensionStatusRequest,
454			body: certificateStatusRequest.finish(),
455		})
456	}
457	if len(m.supportedCurves) > 0 {
458		// http://tools.ietf.org/html/rfc4492#section-5.1.1
459		supportedCurvesList := newByteBuilder()
460		supportedCurves := supportedCurvesList.addU16LengthPrefixed()
461		for _, curve := range m.supportedCurves {
462			supportedCurves.addU16(uint16(curve))
463		}
464		extensions = append(extensions, extension{
465			id:   extensionSupportedCurves,
466			body: supportedCurvesList.finish(),
467		})
468	}
469	if len(m.supportedPoints) > 0 {
470		// http://tools.ietf.org/html/rfc4492#section-5.1.2
471		supportedPointsList := newByteBuilder()
472		supportedPoints := supportedPointsList.addU8LengthPrefixed()
473		supportedPoints.addBytes(m.supportedPoints)
474		extensions = append(extensions, extension{
475			id:   extensionSupportedPoints,
476			body: supportedPointsList.finish(),
477		})
478	}
479	if m.hasKeyShares {
480		keyShareList := newByteBuilder()
481		m.marshalKeyShares(keyShareList)
482		extensions = append(extensions, extension{
483			id:   extensionKeyShare,
484			body: keyShareList.finish(),
485		})
486	}
487	if len(m.pskKEModes) > 0 {
488		pskModesExtension := newByteBuilder()
489		pskModesExtension.addU8LengthPrefixed().addBytes(m.pskKEModes)
490		extensions = append(extensions, extension{
491			id:   extensionPSKKeyExchangeModes,
492			body: pskModesExtension.finish(),
493		})
494	}
495	if m.hasEarlyData {
496		extensions = append(extensions, extension{id: extensionEarlyData})
497	}
498	if len(m.tls13Cookie) > 0 {
499		body := newByteBuilder()
500		body.addU16LengthPrefixed().addBytes(m.tls13Cookie)
501		extensions = append(extensions, extension{
502			id:   extensionCookie,
503			body: body.finish(),
504		})
505	}
506	if m.ticketSupported {
507		// http://tools.ietf.org/html/rfc5077#section-3.2
508		extensions = append(extensions, extension{
509			id:   extensionSessionTicket,
510			body: m.sessionTicket,
511		})
512	}
513	if len(m.signatureAlgorithms) > 0 {
514		// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
515		signatureAlgorithmsExtension := newByteBuilder()
516		signatureAlgorithms := signatureAlgorithmsExtension.addU16LengthPrefixed()
517		for _, sigAlg := range m.signatureAlgorithms {
518			signatureAlgorithms.addU16(uint16(sigAlg))
519		}
520		extensions = append(extensions, extension{
521			id:   extensionSignatureAlgorithms,
522			body: signatureAlgorithmsExtension.finish(),
523		})
524	}
525	if len(m.signatureAlgorithmsCert) > 0 {
526		signatureAlgorithmsCertExtension := newByteBuilder()
527		signatureAlgorithmsCert := signatureAlgorithmsCertExtension.addU16LengthPrefixed()
528		for _, sigAlg := range m.signatureAlgorithmsCert {
529			signatureAlgorithmsCert.addU16(uint16(sigAlg))
530		}
531		extensions = append(extensions, extension{
532			id:   extensionSignatureAlgorithmsCert,
533			body: signatureAlgorithmsCertExtension.finish(),
534		})
535	}
536	if len(m.supportedVersions) > 0 {
537		supportedVersionsExtension := newByteBuilder()
538		supportedVersions := supportedVersionsExtension.addU8LengthPrefixed()
539		for _, version := range m.supportedVersions {
540			supportedVersions.addU16(uint16(version))
541		}
542		extensions = append(extensions, extension{
543			id:   extensionSupportedVersions,
544			body: supportedVersionsExtension.finish(),
545		})
546	}
547	if m.secureRenegotiation != nil {
548		secureRenegoExt := newByteBuilder()
549		secureRenegoExt.addU8LengthPrefixed().addBytes(m.secureRenegotiation)
550		extensions = append(extensions, extension{
551			id:   extensionRenegotiationInfo,
552			body: secureRenegoExt.finish(),
553		})
554	}
555	if len(m.alpnProtocols) > 0 {
556		// https://tools.ietf.org/html/rfc7301#section-3.1
557		alpnExtension := newByteBuilder()
558		protocolNameList := alpnExtension.addU16LengthPrefixed()
559		for _, s := range m.alpnProtocols {
560			protocolName := protocolNameList.addU8LengthPrefixed()
561			protocolName.addBytes([]byte(s))
562		}
563		extensions = append(extensions, extension{
564			id:   extensionALPN,
565			body: alpnExtension.finish(),
566		})
567	}
568	if len(m.quicTransportParams) > 0 {
569		extensions = append(extensions, extension{
570			id:   extensionQUICTransportParams,
571			body: m.quicTransportParams,
572		})
573	}
574	if len(m.quicTransportParamsLegacy) > 0 {
575		extensions = append(extensions, extension{
576			id:   extensionQUICTransportParamsLegacy,
577			body: m.quicTransportParamsLegacy,
578		})
579	}
580	if m.channelIDSupported {
581		extensions = append(extensions, extension{id: extensionChannelID})
582	}
583	if m.tokenBindingParams != nil {
584		tokbindExtension := newByteBuilder()
585		tokbindExtension.addU16(m.tokenBindingVersion)
586		tokbindParams := tokbindExtension.addU8LengthPrefixed()
587		tokbindParams.addBytes(m.tokenBindingParams)
588		extensions = append(extensions, extension{
589			id:   extensionTokenBinding,
590			body: tokbindExtension.finish(),
591		})
592	}
593	if m.duplicateExtension {
594		// Add a duplicate bogus extension at the beginning and end.
595		extensions = append(extensions, extension{id: extensionDuplicate})
596	}
597	if m.extendedMasterSecret {
598		// https://tools.ietf.org/html/rfc7627
599		extensions = append(extensions, extension{id: extensionExtendedMasterSecret})
600	}
601	if len(m.srtpProtectionProfiles) > 0 {
602		// https://tools.ietf.org/html/rfc5764#section-4.1.1
603		useSrtpExt := newByteBuilder()
604
605		srtpProtectionProfiles := useSrtpExt.addU16LengthPrefixed()
606		for _, p := range m.srtpProtectionProfiles {
607			srtpProtectionProfiles.addU16(p)
608		}
609		srtpMki := useSrtpExt.addU8LengthPrefixed()
610		srtpMki.addBytes([]byte(m.srtpMasterKeyIdentifier))
611
612		extensions = append(extensions, extension{
613			id:   extensionUseSRTP,
614			body: useSrtpExt.finish(),
615		})
616	}
617	if m.sctListSupported {
618		extensions = append(extensions, extension{id: extensionSignedCertificateTimestamp})
619	}
620	if l := len(m.customExtension); l > 0 {
621		extensions = append(extensions, extension{
622			id:   extensionCustom,
623			body: []byte(m.customExtension),
624		})
625	}
626	if len(m.compressedCertAlgs) > 0 {
627		body := newByteBuilder()
628		algIDs := body.addU8LengthPrefixed()
629		for _, v := range m.compressedCertAlgs {
630			algIDs.addU16(v)
631		}
632		extensions = append(extensions, extension{
633			id:   extensionCompressedCertAlgs,
634			body: body.finish(),
635		})
636	}
637	if m.delegatedCredentials {
638		body := newByteBuilder()
639		signatureSchemeList := body.addU16LengthPrefixed()
640		for _, sigAlg := range m.signatureAlgorithms {
641			signatureSchemeList.addU16(uint16(sigAlg))
642		}
643		extensions = append(extensions, extension{
644			id:   extensionDelegatedCredentials,
645			body: body.finish(),
646		})
647	}
648	if len(m.alpsProtocols) > 0 {
649		body := newByteBuilder()
650		protocolNameList := body.addU16LengthPrefixed()
651		for _, s := range m.alpsProtocols {
652			protocolNameList.addU8LengthPrefixed().addBytes([]byte(s))
653		}
654		extensions = append(extensions, extension{
655			id:   extensionApplicationSettings,
656			body: body.finish(),
657		})
658	}
659
660	// The PSK extension must be last. See https://tools.ietf.org/html/rfc8446#section-4.2.11
661	if len(m.pskIdentities) > 0 {
662		pskExtension := newByteBuilder()
663		pskIdentities := pskExtension.addU16LengthPrefixed()
664		for _, psk := range m.pskIdentities {
665			pskIdentities.addU16LengthPrefixed().addBytes(psk.ticket)
666			pskIdentities.addU32(psk.obfuscatedTicketAge)
667		}
668		pskBinders := pskExtension.addU16LengthPrefixed()
669		for _, binder := range m.pskBinders {
670			pskBinders.addU8LengthPrefixed().addBytes(binder)
671		}
672		extensions = append(extensions, extension{
673			id:   extensionPreSharedKey,
674			body: pskExtension.finish(),
675		})
676	}
677
678	// Write each extension in |extensions| to the |hello| message, hoisting
679	// the extensions named in |m.prefixExtensions| to the front.
680	extensionsBB := hello.addU16LengthPrefixed()
681	extMap := make(map[uint16][]byte)
682	for _, ext := range extensions {
683		extMap[ext.id] = ext.body
684	}
685	// Write each of the prefix extensions, if we have it.
686	for _, extID := range m.prefixExtensions {
687		if body, ok := extMap[extID]; ok {
688			extensionsBB.addU16(extID)
689			extensionsBB.addU16LengthPrefixed().addBytes(body)
690		}
691	}
692	// Forget each of the prefix extensions. This loop is separate from the
693	// extension-writing loop because |m.prefixExtensions| may contain
694	// duplicates.
695	for _, extID := range m.prefixExtensions {
696		delete(extMap, extID)
697	}
698	// Write each of the remaining extensions in their original order.
699	for _, ext := range extensions {
700		if _, ok := extMap[ext.id]; ok {
701			extensionsBB.addU16(ext.id)
702			extensionsBB.addU16LengthPrefixed().addBytes(ext.body)
703		}
704	}
705
706	if m.pad != 0 && hello.len()%m.pad != 0 {
707		extensionsBB.addU16(extensionPadding)
708		padding := extensionsBB.addU16LengthPrefixed()
709		// Note hello.len() has changed at this point from the length
710		// prefix.
711		if l := hello.len() % m.pad; l != 0 {
712			padding.addBytes(make([]byte, m.pad-l))
713		}
714	}
715
716	if m.omitExtensions || m.emptyExtensions {
717		// Silently erase any extensions which were sent.
718		hello.discardChild()
719		if m.emptyExtensions {
720			hello.addU16(0)
721		}
722	}
723
724	m.raw = handshakeMsg.finish()
725	// Sanity-check padding.
726	if m.pad != 0 && (len(m.raw)-4)%m.pad != 0 {
727		panic(fmt.Sprintf("%d is not a multiple of %d", len(m.raw)-4, m.pad))
728	}
729	return m.raw
730}
731
732func parseSignatureAlgorithms(reader *byteReader, out *[]signatureAlgorithm, allowEmpty bool) bool {
733	var sigAlgs byteReader
734	if !reader.readU16LengthPrefixed(&sigAlgs) {
735		return false
736	}
737	if !allowEmpty && len(sigAlgs) == 0 {
738		return false
739	}
740	*out = make([]signatureAlgorithm, 0, len(sigAlgs)/2)
741	for len(sigAlgs) > 0 {
742		var v uint16
743		if !sigAlgs.readU16(&v) {
744			return false
745		}
746		*out = append(*out, signatureAlgorithm(v))
747	}
748	return true
749}
750
751func checkDuplicateExtensions(extensions byteReader) bool {
752	seen := make(map[uint16]struct{})
753	for len(extensions) > 0 {
754		var extension uint16
755		var body byteReader
756		if !extensions.readU16(&extension) ||
757			!extensions.readU16LengthPrefixed(&body) {
758			return false
759		}
760		if _, ok := seen[extension]; ok {
761			return false
762		}
763		seen[extension] = struct{}{}
764	}
765	return true
766}
767
768func (m *clientHelloMsg) unmarshal(data []byte) bool {
769	m.raw = data
770	reader := byteReader(data[4:])
771	if !reader.readU16(&m.vers) ||
772		!reader.readBytes(&m.random, 32) ||
773		!reader.readU8LengthPrefixedBytes(&m.sessionID) ||
774		len(m.sessionID) > 32 {
775		return false
776	}
777	if m.isDTLS {
778		if !reader.readU8LengthPrefixedBytes(&m.cookie) ||
779			len(m.cookie) > 32 {
780			return false
781		}
782	}
783	var cipherSuites byteReader
784	if !reader.readU16LengthPrefixed(&cipherSuites) ||
785		!reader.readU8LengthPrefixedBytes(&m.compressionMethods) {
786		return false
787	}
788
789	m.cipherSuites = make([]uint16, 0, len(cipherSuites)/2)
790	for len(cipherSuites) > 0 {
791		var v uint16
792		if !cipherSuites.readU16(&v) {
793			return false
794		}
795		m.cipherSuites = append(m.cipherSuites, v)
796		if v == scsvRenegotiation {
797			m.secureRenegotiation = []byte{}
798		}
799	}
800
801	m.nextProtoNeg = false
802	m.serverName = ""
803	m.ocspStapling = false
804	m.keyShares = nil
805	m.pskIdentities = nil
806	m.hasEarlyData = false
807	m.ticketSupported = false
808	m.sessionTicket = nil
809	m.signatureAlgorithms = nil
810	m.signatureAlgorithmsCert = nil
811	m.supportedVersions = nil
812	m.alpnProtocols = nil
813	m.extendedMasterSecret = false
814	m.customExtension = ""
815	m.delegatedCredentials = false
816	m.alpsProtocols = nil
817
818	if len(reader) == 0 {
819		// ClientHello is optionally followed by extension data
820		return true
821	}
822
823	var extensions byteReader
824	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 || !checkDuplicateExtensions(extensions) {
825		return false
826	}
827	for len(extensions) > 0 {
828		var extension uint16
829		var body byteReader
830		if !extensions.readU16(&extension) ||
831			!extensions.readU16LengthPrefixed(&body) {
832			return false
833		}
834		switch extension {
835		case extensionServerName:
836			var names byteReader
837			if !body.readU16LengthPrefixed(&names) || len(body) != 0 {
838				return false
839			}
840			for len(names) > 0 {
841				var nameType byte
842				var name []byte
843				if !names.readU8(&nameType) ||
844					!names.readU16LengthPrefixedBytes(&name) {
845					return false
846				}
847				if nameType == 0 {
848					m.serverName = string(name)
849				}
850			}
851		case extensionEncryptedClientHello:
852			var ech clientECH
853			if !body.readU16(&ech.hpkeKDF) ||
854				!body.readU16(&ech.hpkeAEAD) ||
855				!body.readU8LengthPrefixedBytes(&ech.configID) ||
856				!body.readU16LengthPrefixedBytes(&ech.enc) ||
857				len(ech.enc) == 0 ||
858				!body.readU16LengthPrefixedBytes(&ech.payload) ||
859				len(ech.payload) == 0 ||
860				len(body) > 0 {
861				return false
862			}
863			m.clientECH = &ech
864		case extensionNextProtoNeg:
865			if len(body) != 0 {
866				return false
867			}
868			m.nextProtoNeg = true
869		case extensionStatusRequest:
870			m.ocspStapling = len(body) > 0 && body[0] == statusTypeOCSP
871		case extensionSupportedCurves:
872			// http://tools.ietf.org/html/rfc4492#section-5.5.1
873			var curves byteReader
874			if !body.readU16LengthPrefixed(&curves) || len(body) != 0 {
875				return false
876			}
877			m.supportedCurves = make([]CurveID, 0, len(curves)/2)
878			for len(curves) > 0 {
879				var v uint16
880				if !curves.readU16(&v) {
881					return false
882				}
883				m.supportedCurves = append(m.supportedCurves, CurveID(v))
884			}
885		case extensionSupportedPoints:
886			// http://tools.ietf.org/html/rfc4492#section-5.5.2
887			if !body.readU8LengthPrefixedBytes(&m.supportedPoints) || len(body) != 0 {
888				return false
889			}
890		case extensionSessionTicket:
891			// http://tools.ietf.org/html/rfc5077#section-3.2
892			m.ticketSupported = true
893			m.sessionTicket = []byte(body)
894		case extensionKeyShare:
895			// https://tools.ietf.org/html/rfc8446#section-4.2.8
896			m.hasKeyShares = true
897			m.keySharesRaw = body
898			var keyShares byteReader
899			if !body.readU16LengthPrefixed(&keyShares) || len(body) != 0 {
900				return false
901			}
902			for len(keyShares) > 0 {
903				var entry keyShareEntry
904				var group uint16
905				if !keyShares.readU16(&group) ||
906					!keyShares.readU16LengthPrefixedBytes(&entry.keyExchange) {
907					return false
908				}
909				entry.group = CurveID(group)
910				m.keyShares = append(m.keyShares, entry)
911			}
912		case extensionPreSharedKey:
913			// https://tools.ietf.org/html/rfc8446#section-4.2.11
914			var psks, binders byteReader
915			if !body.readU16LengthPrefixed(&psks) ||
916				!body.readU16LengthPrefixed(&binders) ||
917				len(body) != 0 {
918				return false
919			}
920			for len(psks) > 0 {
921				var psk pskIdentity
922				if !psks.readU16LengthPrefixedBytes(&psk.ticket) ||
923					!psks.readU32(&psk.obfuscatedTicketAge) {
924					return false
925				}
926				m.pskIdentities = append(m.pskIdentities, psk)
927			}
928			for len(binders) > 0 {
929				var binder []byte
930				if !binders.readU8LengthPrefixedBytes(&binder) {
931					return false
932				}
933				m.pskBinders = append(m.pskBinders, binder)
934			}
935
936			// There must be the same number of identities as binders.
937			if len(m.pskIdentities) != len(m.pskBinders) {
938				return false
939			}
940		case extensionPSKKeyExchangeModes:
941			// https://tools.ietf.org/html/rfc8446#section-4.2.9
942			if !body.readU8LengthPrefixedBytes(&m.pskKEModes) || len(body) != 0 {
943				return false
944			}
945		case extensionEarlyData:
946			// https://tools.ietf.org/html/rfc8446#section-4.2.10
947			if len(body) != 0 {
948				return false
949			}
950			m.hasEarlyData = true
951		case extensionCookie:
952			if !body.readU16LengthPrefixedBytes(&m.tls13Cookie) || len(body) != 0 {
953				return false
954			}
955		case extensionSignatureAlgorithms:
956			// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
957			if !parseSignatureAlgorithms(&body, &m.signatureAlgorithms, false) || len(body) != 0 {
958				return false
959			}
960		case extensionSignatureAlgorithmsCert:
961			if !parseSignatureAlgorithms(&body, &m.signatureAlgorithmsCert, false) || len(body) != 0 {
962				return false
963			}
964		case extensionSupportedVersions:
965			var versions byteReader
966			if !body.readU8LengthPrefixed(&versions) || len(body) != 0 {
967				return false
968			}
969			m.supportedVersions = make([]uint16, 0, len(versions)/2)
970			for len(versions) > 0 {
971				var v uint16
972				if !versions.readU16(&v) {
973					return false
974				}
975				m.supportedVersions = append(m.supportedVersions, v)
976			}
977		case extensionRenegotiationInfo:
978			if !body.readU8LengthPrefixedBytes(&m.secureRenegotiation) || len(body) != 0 {
979				return false
980			}
981		case extensionALPN:
982			var protocols byteReader
983			if !body.readU16LengthPrefixed(&protocols) || len(body) != 0 {
984				return false
985			}
986			for len(protocols) > 0 {
987				var protocol []byte
988				if !protocols.readU8LengthPrefixedBytes(&protocol) || len(protocol) == 0 {
989					return false
990				}
991				m.alpnProtocols = append(m.alpnProtocols, string(protocol))
992			}
993		case extensionQUICTransportParams:
994			m.quicTransportParams = body
995		case extensionQUICTransportParamsLegacy:
996			m.quicTransportParamsLegacy = body
997		case extensionChannelID:
998			if len(body) != 0 {
999				return false
1000			}
1001			m.channelIDSupported = true
1002		case extensionTokenBinding:
1003			if !body.readU16(&m.tokenBindingVersion) ||
1004				!body.readU8LengthPrefixedBytes(&m.tokenBindingParams) ||
1005				len(body) != 0 {
1006				return false
1007			}
1008		case extensionExtendedMasterSecret:
1009			if len(body) != 0 {
1010				return false
1011			}
1012			m.extendedMasterSecret = true
1013		case extensionUseSRTP:
1014			var profiles byteReader
1015			var mki []byte
1016			if !body.readU16LengthPrefixed(&profiles) ||
1017				!body.readU8LengthPrefixedBytes(&mki) ||
1018				len(body) != 0 {
1019				return false
1020			}
1021			m.srtpProtectionProfiles = make([]uint16, 0, len(profiles)/2)
1022			for len(profiles) > 0 {
1023				var v uint16
1024				if !profiles.readU16(&v) {
1025					return false
1026				}
1027				m.srtpProtectionProfiles = append(m.srtpProtectionProfiles, v)
1028			}
1029			m.srtpMasterKeyIdentifier = string(mki)
1030		case extensionSignedCertificateTimestamp:
1031			if len(body) != 0 {
1032				return false
1033			}
1034			m.sctListSupported = true
1035		case extensionCustom:
1036			m.customExtension = string(body)
1037		case extensionCompressedCertAlgs:
1038			var algIDs byteReader
1039			if !body.readU8LengthPrefixed(&algIDs) {
1040				return false
1041			}
1042
1043			seen := make(map[uint16]struct{})
1044			for len(algIDs) > 0 {
1045				var algID uint16
1046				if !algIDs.readU16(&algID) {
1047					return false
1048				}
1049				if _, ok := seen[algID]; ok {
1050					return false
1051				}
1052				seen[algID] = struct{}{}
1053				m.compressedCertAlgs = append(m.compressedCertAlgs, algID)
1054			}
1055		case extensionPadding:
1056			// Padding bytes must be all zero.
1057			for _, b := range body {
1058				if b != 0 {
1059					return false
1060				}
1061			}
1062		case extensionDelegatedCredentials:
1063			if len(body) != 0 {
1064				return false
1065			}
1066			m.delegatedCredentials = true
1067		case extensionApplicationSettings:
1068			var protocols byteReader
1069			if !body.readU16LengthPrefixed(&protocols) || len(body) != 0 {
1070				return false
1071			}
1072			for len(protocols) > 0 {
1073				var protocol []byte
1074				if !protocols.readU8LengthPrefixedBytes(&protocol) || len(protocol) == 0 {
1075					return false
1076				}
1077				m.alpsProtocols = append(m.alpsProtocols, string(protocol))
1078			}
1079		}
1080
1081		if isGREASEValue(extension) {
1082			m.hasGREASEExtension = true
1083		}
1084	}
1085
1086	return true
1087}
1088
1089type serverHelloMsg struct {
1090	raw                   []byte
1091	isDTLS                bool
1092	vers                  uint16
1093	versOverride          uint16
1094	supportedVersOverride uint16
1095	omitSupportedVers     bool
1096	random                []byte
1097	sessionID             []byte
1098	cipherSuite           uint16
1099	hasKeyShare           bool
1100	keyShare              keyShareEntry
1101	hasPSKIdentity        bool
1102	pskIdentity           uint16
1103	compressionMethod     uint8
1104	customExtension       string
1105	unencryptedALPN       string
1106	omitExtensions        bool
1107	emptyExtensions       bool
1108	extensions            serverExtensions
1109}
1110
1111func (m *serverHelloMsg) marshal() []byte {
1112	if m.raw != nil {
1113		return m.raw
1114	}
1115
1116	handshakeMsg := newByteBuilder()
1117	handshakeMsg.addU8(typeServerHello)
1118	hello := handshakeMsg.addU24LengthPrefixed()
1119
1120	// m.vers is used both to determine the format of the rest of the
1121	// ServerHello and to override the value, so include a second version
1122	// field.
1123	vers, ok := wireToVersion(m.vers, m.isDTLS)
1124	if !ok {
1125		panic("unknown version")
1126	}
1127	if m.versOverride != 0 {
1128		hello.addU16(m.versOverride)
1129	} else if vers >= VersionTLS13 {
1130		hello.addU16(VersionTLS12)
1131	} else {
1132		hello.addU16(m.vers)
1133	}
1134
1135	hello.addBytes(m.random)
1136	sessionID := hello.addU8LengthPrefixed()
1137	sessionID.addBytes(m.sessionID)
1138	hello.addU16(m.cipherSuite)
1139	hello.addU8(m.compressionMethod)
1140
1141	extensions := hello.addU16LengthPrefixed()
1142
1143	if vers >= VersionTLS13 {
1144		if m.hasKeyShare {
1145			extensions.addU16(extensionKeyShare)
1146			keyShare := extensions.addU16LengthPrefixed()
1147			keyShare.addU16(uint16(m.keyShare.group))
1148			keyExchange := keyShare.addU16LengthPrefixed()
1149			keyExchange.addBytes(m.keyShare.keyExchange)
1150		}
1151		if m.hasPSKIdentity {
1152			extensions.addU16(extensionPreSharedKey)
1153			extensions.addU16(2) // Length
1154			extensions.addU16(m.pskIdentity)
1155		}
1156		if !m.omitSupportedVers {
1157			extensions.addU16(extensionSupportedVersions)
1158			extensions.addU16(2) // Length
1159			if m.supportedVersOverride != 0 {
1160				extensions.addU16(m.supportedVersOverride)
1161			} else {
1162				extensions.addU16(m.vers)
1163			}
1164		}
1165		if len(m.customExtension) > 0 {
1166			extensions.addU16(extensionCustom)
1167			customExt := extensions.addU16LengthPrefixed()
1168			customExt.addBytes([]byte(m.customExtension))
1169		}
1170		if len(m.unencryptedALPN) > 0 {
1171			extensions.addU16(extensionALPN)
1172			extension := extensions.addU16LengthPrefixed()
1173
1174			protocolNameList := extension.addU16LengthPrefixed()
1175			protocolName := protocolNameList.addU8LengthPrefixed()
1176			protocolName.addBytes([]byte(m.unencryptedALPN))
1177		}
1178	} else {
1179		m.extensions.marshal(extensions)
1180		if m.omitExtensions || m.emptyExtensions {
1181			// Silently erasing server extensions will break the handshake. Instead,
1182			// assert that tests which use this field also disable all features which
1183			// would write an extension.
1184			if extensions.len() != 0 {
1185				panic(fmt.Sprintf("ServerHello unexpectedly contained extensions: %x, %+v", extensions.data(), m))
1186			}
1187			hello.discardChild()
1188			if m.emptyExtensions {
1189				hello.addU16(0)
1190			}
1191		}
1192	}
1193
1194	m.raw = handshakeMsg.finish()
1195	return m.raw
1196}
1197
1198func (m *serverHelloMsg) unmarshal(data []byte) bool {
1199	m.raw = data
1200	reader := byteReader(data[4:])
1201	if !reader.readU16(&m.vers) ||
1202		!reader.readBytes(&m.random, 32) {
1203		return false
1204	}
1205	vers, ok := wireToVersion(m.vers, m.isDTLS)
1206	if !ok {
1207		return false
1208	}
1209	if !reader.readU8LengthPrefixedBytes(&m.sessionID) ||
1210		!reader.readU16(&m.cipherSuite) ||
1211		!reader.readU8(&m.compressionMethod) {
1212		return false
1213	}
1214
1215	if len(reader) == 0 && m.vers < VersionTLS13 {
1216		// Extension data is optional before TLS 1.3.
1217		m.extensions = serverExtensions{}
1218		m.omitExtensions = true
1219		return true
1220	}
1221
1222	var extensions byteReader
1223	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 || !checkDuplicateExtensions(extensions) {
1224		return false
1225	}
1226
1227	// Parse out the version from supported_versions if available.
1228	if m.vers == VersionTLS12 {
1229		extensionsCopy := extensions
1230		for len(extensionsCopy) > 0 {
1231			var extension uint16
1232			var body byteReader
1233			if !extensionsCopy.readU16(&extension) ||
1234				!extensionsCopy.readU16LengthPrefixed(&body) {
1235				return false
1236			}
1237			if extension == extensionSupportedVersions {
1238				if !body.readU16(&m.vers) || len(body) != 0 {
1239					return false
1240				}
1241				vers, ok = wireToVersion(m.vers, m.isDTLS)
1242				if !ok {
1243					return false
1244				}
1245			}
1246		}
1247	}
1248
1249	if vers >= VersionTLS13 {
1250		for len(extensions) > 0 {
1251			var extension uint16
1252			var body byteReader
1253			if !extensions.readU16(&extension) ||
1254				!extensions.readU16LengthPrefixed(&body) {
1255				return false
1256			}
1257			switch extension {
1258			case extensionKeyShare:
1259				m.hasKeyShare = true
1260				var group uint16
1261				if !body.readU16(&group) ||
1262					!body.readU16LengthPrefixedBytes(&m.keyShare.keyExchange) ||
1263					len(body) != 0 {
1264					return false
1265				}
1266				m.keyShare.group = CurveID(group)
1267			case extensionPreSharedKey:
1268				if !body.readU16(&m.pskIdentity) || len(body) != 0 {
1269					return false
1270				}
1271				m.hasPSKIdentity = true
1272			case extensionSupportedVersions:
1273				// Parsed above.
1274			default:
1275				// Only allow the 3 extensions that are sent in
1276				// the clear in TLS 1.3.
1277				return false
1278			}
1279		}
1280	} else if !m.extensions.unmarshal(extensions, vers) {
1281		return false
1282	}
1283
1284	return true
1285}
1286
1287// marshalForECHConf marshals |m|, but zeroes out the last 8 bytes of the
1288// ServerHello.random.
1289func (m *serverHelloMsg) marshalForECHConf() []byte {
1290	serverHelloECHConf := *m
1291	serverHelloECHConf.raw = nil
1292	serverHelloECHConf.random = make([]byte, 32)
1293	copy(serverHelloECHConf.random[:24], m.random)
1294	return serverHelloECHConf.marshal()
1295}
1296
1297type encryptedExtensionsMsg struct {
1298	raw        []byte
1299	extensions serverExtensions
1300	empty      bool
1301}
1302
1303func (m *encryptedExtensionsMsg) marshal() []byte {
1304	if m.raw != nil {
1305		return m.raw
1306	}
1307
1308	encryptedExtensionsMsg := newByteBuilder()
1309	encryptedExtensionsMsg.addU8(typeEncryptedExtensions)
1310	encryptedExtensions := encryptedExtensionsMsg.addU24LengthPrefixed()
1311	if !m.empty {
1312		extensions := encryptedExtensions.addU16LengthPrefixed()
1313		m.extensions.marshal(extensions)
1314	}
1315
1316	m.raw = encryptedExtensionsMsg.finish()
1317	return m.raw
1318}
1319
1320func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool {
1321	m.raw = data
1322	reader := byteReader(data[4:])
1323	var extensions byteReader
1324	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 {
1325		return false
1326	}
1327	return m.extensions.unmarshal(extensions, VersionTLS13)
1328}
1329
1330type serverExtensions struct {
1331	nextProtoNeg              bool
1332	nextProtos                []string
1333	ocspStapling              bool
1334	ticketSupported           bool
1335	secureRenegotiation       []byte
1336	alpnProtocol              string
1337	alpnProtocolEmpty         bool
1338	duplicateExtension        bool
1339	channelIDRequested        bool
1340	tokenBindingParams        []byte
1341	tokenBindingVersion       uint16
1342	extendedMasterSecret      bool
1343	srtpProtectionProfile     uint16
1344	srtpMasterKeyIdentifier   string
1345	sctList                   []byte
1346	customExtension           string
1347	npnAfterAlpn              bool
1348	hasKeyShare               bool
1349	hasEarlyData              bool
1350	keyShare                  keyShareEntry
1351	supportedVersion          uint16
1352	supportedPoints           []uint8
1353	supportedCurves           []CurveID
1354	quicTransportParams       []byte
1355	quicTransportParamsLegacy []byte
1356	serverNameAck             bool
1357	applicationSettings       []byte
1358	hasApplicationSettings    bool
1359	echRetryConfigs           []byte
1360}
1361
1362func (m *serverExtensions) marshal(extensions *byteBuilder) {
1363	if m.duplicateExtension {
1364		// Add a duplicate bogus extension at the beginning and end.
1365		extensions.addU16(extensionDuplicate)
1366		extensions.addU16(0) // length = 0 for empty extension
1367	}
1368	if m.nextProtoNeg && !m.npnAfterAlpn {
1369		extensions.addU16(extensionNextProtoNeg)
1370		extension := extensions.addU16LengthPrefixed()
1371
1372		for _, v := range m.nextProtos {
1373			if len(v) > 255 {
1374				v = v[:255]
1375			}
1376			npn := extension.addU8LengthPrefixed()
1377			npn.addBytes([]byte(v))
1378		}
1379	}
1380	if m.ocspStapling {
1381		extensions.addU16(extensionStatusRequest)
1382		extensions.addU16(0)
1383	}
1384	if m.ticketSupported {
1385		extensions.addU16(extensionSessionTicket)
1386		extensions.addU16(0)
1387	}
1388	if m.secureRenegotiation != nil {
1389		extensions.addU16(extensionRenegotiationInfo)
1390		extension := extensions.addU16LengthPrefixed()
1391		secureRenego := extension.addU8LengthPrefixed()
1392		secureRenego.addBytes(m.secureRenegotiation)
1393	}
1394	if len(m.alpnProtocol) > 0 || m.alpnProtocolEmpty {
1395		extensions.addU16(extensionALPN)
1396		extension := extensions.addU16LengthPrefixed()
1397
1398		protocolNameList := extension.addU16LengthPrefixed()
1399		protocolName := protocolNameList.addU8LengthPrefixed()
1400		protocolName.addBytes([]byte(m.alpnProtocol))
1401	}
1402	if m.channelIDRequested {
1403		extensions.addU16(extensionChannelID)
1404		extensions.addU16(0)
1405	}
1406	if m.tokenBindingParams != nil {
1407		extensions.addU16(extensionTokenBinding)
1408		tokbindExtension := extensions.addU16LengthPrefixed()
1409		tokbindExtension.addU16(m.tokenBindingVersion)
1410		tokbindParams := tokbindExtension.addU8LengthPrefixed()
1411		tokbindParams.addBytes(m.tokenBindingParams)
1412	}
1413	if m.duplicateExtension {
1414		// Add a duplicate bogus extension at the beginning and end.
1415		extensions.addU16(extensionDuplicate)
1416		extensions.addU16(0)
1417	}
1418	if m.extendedMasterSecret {
1419		extensions.addU16(extensionExtendedMasterSecret)
1420		extensions.addU16(0)
1421	}
1422	if m.srtpProtectionProfile != 0 {
1423		extensions.addU16(extensionUseSRTP)
1424		extension := extensions.addU16LengthPrefixed()
1425
1426		srtpProtectionProfiles := extension.addU16LengthPrefixed()
1427		srtpProtectionProfiles.addU16(m.srtpProtectionProfile)
1428		srtpMki := extension.addU8LengthPrefixed()
1429		srtpMki.addBytes([]byte(m.srtpMasterKeyIdentifier))
1430	}
1431	if m.sctList != nil {
1432		extensions.addU16(extensionSignedCertificateTimestamp)
1433		extension := extensions.addU16LengthPrefixed()
1434		extension.addBytes(m.sctList)
1435	}
1436	if l := len(m.customExtension); l > 0 {
1437		extensions.addU16(extensionCustom)
1438		customExt := extensions.addU16LengthPrefixed()
1439		customExt.addBytes([]byte(m.customExtension))
1440	}
1441	if m.nextProtoNeg && m.npnAfterAlpn {
1442		extensions.addU16(extensionNextProtoNeg)
1443		extension := extensions.addU16LengthPrefixed()
1444
1445		for _, v := range m.nextProtos {
1446			if len(v) > 255 {
1447				v = v[0:255]
1448			}
1449			npn := extension.addU8LengthPrefixed()
1450			npn.addBytes([]byte(v))
1451		}
1452	}
1453	if m.hasKeyShare {
1454		extensions.addU16(extensionKeyShare)
1455		keyShare := extensions.addU16LengthPrefixed()
1456		keyShare.addU16(uint16(m.keyShare.group))
1457		keyExchange := keyShare.addU16LengthPrefixed()
1458		keyExchange.addBytes(m.keyShare.keyExchange)
1459	}
1460	if m.supportedVersion != 0 {
1461		extensions.addU16(extensionSupportedVersions)
1462		extensions.addU16(2) // Length
1463		extensions.addU16(m.supportedVersion)
1464	}
1465	if len(m.supportedPoints) > 0 {
1466		// http://tools.ietf.org/html/rfc4492#section-5.1.2
1467		extensions.addU16(extensionSupportedPoints)
1468		supportedPointsList := extensions.addU16LengthPrefixed()
1469		supportedPoints := supportedPointsList.addU8LengthPrefixed()
1470		supportedPoints.addBytes(m.supportedPoints)
1471	}
1472	if len(m.supportedCurves) > 0 {
1473		// https://tools.ietf.org/html/rfc8446#section-4.2.7
1474		extensions.addU16(extensionSupportedCurves)
1475		supportedCurvesList := extensions.addU16LengthPrefixed()
1476		supportedCurves := supportedCurvesList.addU16LengthPrefixed()
1477		for _, curve := range m.supportedCurves {
1478			supportedCurves.addU16(uint16(curve))
1479		}
1480	}
1481	if len(m.quicTransportParams) > 0 {
1482		extensions.addU16(extensionQUICTransportParams)
1483		params := extensions.addU16LengthPrefixed()
1484		params.addBytes(m.quicTransportParams)
1485	}
1486	if len(m.quicTransportParamsLegacy) > 0 {
1487		extensions.addU16(extensionQUICTransportParamsLegacy)
1488		params := extensions.addU16LengthPrefixed()
1489		params.addBytes(m.quicTransportParamsLegacy)
1490	}
1491	if m.hasEarlyData {
1492		extensions.addU16(extensionEarlyData)
1493		extensions.addBytes([]byte{0, 0})
1494	}
1495	if m.serverNameAck {
1496		extensions.addU16(extensionServerName)
1497		extensions.addU16(0) // zero length
1498	}
1499	if m.hasApplicationSettings {
1500		extensions.addU16(extensionApplicationSettings)
1501		extensions.addU16LengthPrefixed().addBytes(m.applicationSettings)
1502	}
1503	if len(m.echRetryConfigs) > 0 {
1504		extensions.addU16(extensionEncryptedClientHello)
1505		body := extensions.addU16LengthPrefixed()
1506		echConfigs := body.addU16LengthPrefixed()
1507		echConfigs.addBytes(m.echRetryConfigs)
1508	}
1509}
1510
1511func (m *serverExtensions) unmarshal(data byteReader, version uint16) bool {
1512	// Reset all fields.
1513	*m = serverExtensions{}
1514
1515	if !checkDuplicateExtensions(data) {
1516		return false
1517	}
1518
1519	for len(data) > 0 {
1520		var extension uint16
1521		var body byteReader
1522		if !data.readU16(&extension) ||
1523			!data.readU16LengthPrefixed(&body) {
1524			return false
1525		}
1526		switch extension {
1527		case extensionNextProtoNeg:
1528			m.nextProtoNeg = true
1529			for len(body) > 0 {
1530				var protocol []byte
1531				if !body.readU8LengthPrefixedBytes(&protocol) {
1532					return false
1533				}
1534				m.nextProtos = append(m.nextProtos, string(protocol))
1535			}
1536		case extensionStatusRequest:
1537			if len(body) != 0 {
1538				return false
1539			}
1540			m.ocspStapling = true
1541		case extensionSessionTicket:
1542			if len(body) != 0 {
1543				return false
1544			}
1545			m.ticketSupported = true
1546		case extensionRenegotiationInfo:
1547			if !body.readU8LengthPrefixedBytes(&m.secureRenegotiation) || len(body) != 0 {
1548				return false
1549			}
1550		case extensionALPN:
1551			var protocols, protocol byteReader
1552			if !body.readU16LengthPrefixed(&protocols) ||
1553				len(body) != 0 ||
1554				!protocols.readU8LengthPrefixed(&protocol) ||
1555				len(protocols) != 0 {
1556				return false
1557			}
1558			m.alpnProtocol = string(protocol)
1559			m.alpnProtocolEmpty = len(protocol) == 0
1560		case extensionChannelID:
1561			if len(body) != 0 {
1562				return false
1563			}
1564			m.channelIDRequested = true
1565		case extensionTokenBinding:
1566			if !body.readU16(&m.tokenBindingVersion) ||
1567				!body.readU8LengthPrefixedBytes(&m.tokenBindingParams) ||
1568				len(m.tokenBindingParams) != 1 ||
1569				len(body) != 0 {
1570				return false
1571			}
1572		case extensionExtendedMasterSecret:
1573			if len(body) != 0 {
1574				return false
1575			}
1576			m.extendedMasterSecret = true
1577		case extensionUseSRTP:
1578			var profiles, mki byteReader
1579			if !body.readU16LengthPrefixed(&profiles) ||
1580				!profiles.readU16(&m.srtpProtectionProfile) ||
1581				len(profiles) != 0 ||
1582				!body.readU8LengthPrefixed(&mki) ||
1583				len(body) != 0 {
1584				return false
1585			}
1586			m.srtpMasterKeyIdentifier = string(mki)
1587		case extensionSignedCertificateTimestamp:
1588			m.sctList = []byte(body)
1589		case extensionCustom:
1590			m.customExtension = string(body)
1591		case extensionServerName:
1592			if len(body) != 0 {
1593				return false
1594			}
1595			m.serverNameAck = true
1596		case extensionSupportedPoints:
1597			// supported_points is illegal in TLS 1.3.
1598			if version >= VersionTLS13 {
1599				return false
1600			}
1601			// http://tools.ietf.org/html/rfc4492#section-5.5.2
1602			if !body.readU8LengthPrefixedBytes(&m.supportedPoints) || len(body) != 0 {
1603				return false
1604			}
1605		case extensionSupportedCurves:
1606			// The server can only send supported_curves in TLS 1.3.
1607			if version < VersionTLS13 {
1608				return false
1609			}
1610		case extensionQUICTransportParams:
1611			m.quicTransportParams = body
1612		case extensionQUICTransportParamsLegacy:
1613			m.quicTransportParamsLegacy = body
1614		case extensionEarlyData:
1615			if version < VersionTLS13 || len(body) != 0 {
1616				return false
1617			}
1618			m.hasEarlyData = true
1619		case extensionApplicationSettings:
1620			m.hasApplicationSettings = true
1621			m.applicationSettings = body
1622		case extensionEncryptedClientHello:
1623			var echConfigs byteReader
1624			if !body.readU16LengthPrefixed(&echConfigs) {
1625				return false
1626			}
1627			for len(echConfigs) > 0 {
1628				// Validate the ECHConfig with a top-level parse.
1629				echConfigReader := echConfigs
1630				var version uint16
1631				var contents byteReader
1632				if !echConfigReader.readU16(&version) ||
1633					!echConfigReader.readU16LengthPrefixed(&contents) {
1634					return false
1635				}
1636
1637				m.echRetryConfigs = contents
1638			}
1639			if len(body) > 0 {
1640				return false
1641			}
1642		default:
1643			// Unknown extensions are illegal from the server.
1644			return false
1645		}
1646	}
1647
1648	return true
1649}
1650
1651type clientEncryptedExtensionsMsg struct {
1652	raw                    []byte
1653	applicationSettings    []byte
1654	hasApplicationSettings bool
1655	customExtension        []byte
1656}
1657
1658func (m *clientEncryptedExtensionsMsg) marshal() (x []byte) {
1659	if m.raw != nil {
1660		return m.raw
1661	}
1662
1663	builder := newByteBuilder()
1664	builder.addU8(typeEncryptedExtensions)
1665	body := builder.addU24LengthPrefixed()
1666	extensions := body.addU16LengthPrefixed()
1667	if m.hasApplicationSettings {
1668		extensions.addU16(extensionApplicationSettings)
1669		extensions.addU16LengthPrefixed().addBytes(m.applicationSettings)
1670	}
1671	if len(m.customExtension) > 0 {
1672		extensions.addU16(extensionCustom)
1673		extensions.addU16LengthPrefixed().addBytes(m.customExtension)
1674	}
1675
1676	m.raw = builder.finish()
1677	return m.raw
1678}
1679
1680func (m *clientEncryptedExtensionsMsg) unmarshal(data []byte) bool {
1681	m.raw = data
1682	reader := byteReader(data[4:])
1683
1684	var extensions byteReader
1685	if !reader.readU16LengthPrefixed(&extensions) ||
1686		len(reader) != 0 {
1687		return false
1688	}
1689
1690	if !checkDuplicateExtensions(extensions) {
1691		return false
1692	}
1693
1694	for len(extensions) > 0 {
1695		var extension uint16
1696		var body byteReader
1697		if !extensions.readU16(&extension) ||
1698			!extensions.readU16LengthPrefixed(&body) {
1699			return false
1700		}
1701		switch extension {
1702		case extensionApplicationSettings:
1703			m.hasApplicationSettings = true
1704			m.applicationSettings = body
1705		default:
1706			// Unknown extensions are illegal in EncryptedExtensions.
1707			return false
1708		}
1709	}
1710	return true
1711}
1712
1713type helloRetryRequestMsg struct {
1714	raw                 []byte
1715	vers                uint16
1716	isServerHello       bool
1717	sessionID           []byte
1718	cipherSuite         uint16
1719	compressionMethod   uint8
1720	hasSelectedGroup    bool
1721	selectedGroup       CurveID
1722	cookie              []byte
1723	customExtension     string
1724	duplicateExtensions bool
1725}
1726
1727func (m *helloRetryRequestMsg) marshal() []byte {
1728	if m.raw != nil {
1729		return m.raw
1730	}
1731
1732	retryRequestMsg := newByteBuilder()
1733	retryRequestMsg.addU8(typeServerHello)
1734	retryRequest := retryRequestMsg.addU24LengthPrefixed()
1735	retryRequest.addU16(VersionTLS12)
1736	retryRequest.addBytes(tls13HelloRetryRequest)
1737	sessionID := retryRequest.addU8LengthPrefixed()
1738	sessionID.addBytes(m.sessionID)
1739	retryRequest.addU16(m.cipherSuite)
1740	retryRequest.addU8(m.compressionMethod)
1741
1742	extensions := retryRequest.addU16LengthPrefixed()
1743
1744	count := 1
1745	if m.duplicateExtensions {
1746		count = 2
1747	}
1748
1749	for i := 0; i < count; i++ {
1750		extensions.addU16(extensionSupportedVersions)
1751		extensions.addU16(2) // Length
1752		extensions.addU16(m.vers)
1753		if m.hasSelectedGroup {
1754			extensions.addU16(extensionKeyShare)
1755			extensions.addU16(2) // length
1756			extensions.addU16(uint16(m.selectedGroup))
1757		}
1758		// m.cookie may be a non-nil empty slice for empty cookie tests.
1759		if m.cookie != nil {
1760			extensions.addU16(extensionCookie)
1761			body := extensions.addU16LengthPrefixed()
1762			body.addU16LengthPrefixed().addBytes(m.cookie)
1763		}
1764		if len(m.customExtension) > 0 {
1765			extensions.addU16(extensionCustom)
1766			extensions.addU16LengthPrefixed().addBytes([]byte(m.customExtension))
1767		}
1768	}
1769
1770	m.raw = retryRequestMsg.finish()
1771	return m.raw
1772}
1773
1774func (m *helloRetryRequestMsg) unmarshal(data []byte) bool {
1775	m.raw = data
1776	reader := byteReader(data[4:])
1777	if !reader.readU16(&m.vers) {
1778		return false
1779	}
1780	if m.isServerHello {
1781		var random []byte
1782		var compressionMethod byte
1783		if !reader.readBytes(&random, 32) ||
1784			!reader.readU8LengthPrefixedBytes(&m.sessionID) ||
1785			!reader.readU16(&m.cipherSuite) ||
1786			!reader.readU8(&compressionMethod) ||
1787			compressionMethod != 0 {
1788			return false
1789		}
1790	} else if !reader.readU16(&m.cipherSuite) {
1791		return false
1792	}
1793	var extensions byteReader
1794	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 {
1795		return false
1796	}
1797	extensionsCopy := extensions
1798	for len(extensionsCopy) > 0 {
1799		var extension uint16
1800		var body byteReader
1801		if !extensionsCopy.readU16(&extension) ||
1802			!extensionsCopy.readU16LengthPrefixed(&body) {
1803			return false
1804		}
1805		switch extension {
1806		case extensionSupportedVersions:
1807			if !m.isServerHello ||
1808				!body.readU16(&m.vers) ||
1809				len(body) != 0 {
1810				return false
1811			}
1812		default:
1813		}
1814	}
1815	for len(extensions) > 0 {
1816		var extension uint16
1817		var body byteReader
1818		if !extensions.readU16(&extension) ||
1819			!extensions.readU16LengthPrefixed(&body) {
1820			return false
1821		}
1822		switch extension {
1823		case extensionSupportedVersions:
1824			// Parsed above.
1825		case extensionKeyShare:
1826			var v uint16
1827			if !body.readU16(&v) || len(body) != 0 {
1828				return false
1829			}
1830			m.hasSelectedGroup = true
1831			m.selectedGroup = CurveID(v)
1832		case extensionCookie:
1833			if !body.readU16LengthPrefixedBytes(&m.cookie) || len(body) != 0 {
1834				return false
1835			}
1836		default:
1837			// Unknown extensions are illegal from the server.
1838			return false
1839		}
1840	}
1841	return true
1842}
1843
1844type certificateEntry struct {
1845	data                []byte
1846	ocspResponse        []byte
1847	sctList             []byte
1848	duplicateExtensions bool
1849	extraExtension      []byte
1850	delegatedCredential *delegatedCredential
1851}
1852
1853type delegatedCredential struct {
1854	// https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3
1855	signedBytes            []byte
1856	lifetimeSecs           uint32
1857	expectedCertVerifyAlgo signatureAlgorithm
1858	pkixPublicKey          []byte
1859	algorithm              signatureAlgorithm
1860	signature              []byte
1861}
1862
1863type certificateMsg struct {
1864	raw               []byte
1865	hasRequestContext bool
1866	requestContext    []byte
1867	certificates      []certificateEntry
1868}
1869
1870func (m *certificateMsg) marshal() (x []byte) {
1871	if m.raw != nil {
1872		return m.raw
1873	}
1874
1875	certMsg := newByteBuilder()
1876	certMsg.addU8(typeCertificate)
1877	certificate := certMsg.addU24LengthPrefixed()
1878	if m.hasRequestContext {
1879		context := certificate.addU8LengthPrefixed()
1880		context.addBytes(m.requestContext)
1881	}
1882	certificateList := certificate.addU24LengthPrefixed()
1883	for _, cert := range m.certificates {
1884		certEntry := certificateList.addU24LengthPrefixed()
1885		certEntry.addBytes(cert.data)
1886		if m.hasRequestContext {
1887			extensions := certificateList.addU16LengthPrefixed()
1888			count := 1
1889			if cert.duplicateExtensions {
1890				count = 2
1891			}
1892
1893			for i := 0; i < count; i++ {
1894				if cert.ocspResponse != nil {
1895					extensions.addU16(extensionStatusRequest)
1896					body := extensions.addU16LengthPrefixed()
1897					body.addU8(statusTypeOCSP)
1898					response := body.addU24LengthPrefixed()
1899					response.addBytes(cert.ocspResponse)
1900				}
1901
1902				if cert.sctList != nil {
1903					extensions.addU16(extensionSignedCertificateTimestamp)
1904					extension := extensions.addU16LengthPrefixed()
1905					extension.addBytes(cert.sctList)
1906				}
1907			}
1908			if cert.extraExtension != nil {
1909				extensions.addBytes(cert.extraExtension)
1910			}
1911		}
1912	}
1913
1914	m.raw = certMsg.finish()
1915	return m.raw
1916}
1917
1918func (m *certificateMsg) unmarshal(data []byte) bool {
1919	m.raw = data
1920	reader := byteReader(data[4:])
1921
1922	if m.hasRequestContext && !reader.readU8LengthPrefixedBytes(&m.requestContext) {
1923		return false
1924	}
1925
1926	var certs byteReader
1927	if !reader.readU24LengthPrefixed(&certs) || len(reader) != 0 {
1928		return false
1929	}
1930	m.certificates = nil
1931	for len(certs) > 0 {
1932		var cert certificateEntry
1933		if !certs.readU24LengthPrefixedBytes(&cert.data) {
1934			return false
1935		}
1936		if m.hasRequestContext {
1937			var extensions byteReader
1938			if !certs.readU16LengthPrefixed(&extensions) || !checkDuplicateExtensions(extensions) {
1939				return false
1940			}
1941			for len(extensions) > 0 {
1942				var extension uint16
1943				var body byteReader
1944				if !extensions.readU16(&extension) ||
1945					!extensions.readU16LengthPrefixed(&body) {
1946					return false
1947				}
1948				switch extension {
1949				case extensionStatusRequest:
1950					var statusType byte
1951					if !body.readU8(&statusType) ||
1952						statusType != statusTypeOCSP ||
1953						!body.readU24LengthPrefixedBytes(&cert.ocspResponse) ||
1954						len(body) != 0 {
1955						return false
1956					}
1957				case extensionSignedCertificateTimestamp:
1958					cert.sctList = []byte(body)
1959				case extensionDelegatedCredentials:
1960					// https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3
1961					if cert.delegatedCredential != nil {
1962						return false
1963					}
1964
1965					dc := new(delegatedCredential)
1966					origBody := body
1967					var expectedCertVerifyAlgo, algorithm uint16
1968
1969					if !body.readU32(&dc.lifetimeSecs) ||
1970						!body.readU16(&expectedCertVerifyAlgo) ||
1971						!body.readU24LengthPrefixedBytes(&dc.pkixPublicKey) ||
1972						!body.readU16(&algorithm) ||
1973						!body.readU16LengthPrefixedBytes(&dc.signature) ||
1974						len(body) != 0 {
1975						return false
1976					}
1977
1978					dc.expectedCertVerifyAlgo = signatureAlgorithm(expectedCertVerifyAlgo)
1979					dc.algorithm = signatureAlgorithm(algorithm)
1980					dc.signedBytes = []byte(origBody)[:4+2+3+len(dc.pkixPublicKey)]
1981					cert.delegatedCredential = dc
1982				default:
1983					return false
1984				}
1985			}
1986		}
1987		m.certificates = append(m.certificates, cert)
1988	}
1989
1990	return true
1991}
1992
1993type compressedCertificateMsg struct {
1994	raw                []byte
1995	algID              uint16
1996	uncompressedLength uint32
1997	compressed         []byte
1998}
1999
2000func (m *compressedCertificateMsg) marshal() (x []byte) {
2001	if m.raw != nil {
2002		return m.raw
2003	}
2004
2005	certMsg := newByteBuilder()
2006	certMsg.addU8(typeCompressedCertificate)
2007	certificate := certMsg.addU24LengthPrefixed()
2008	certificate.addU16(m.algID)
2009	certificate.addU24(int(m.uncompressedLength))
2010	compressed := certificate.addU24LengthPrefixed()
2011	compressed.addBytes(m.compressed)
2012
2013	m.raw = certMsg.finish()
2014	return m.raw
2015}
2016
2017func (m *compressedCertificateMsg) unmarshal(data []byte) bool {
2018	m.raw = data
2019	reader := byteReader(data[4:])
2020
2021	if !reader.readU16(&m.algID) ||
2022		!reader.readU24(&m.uncompressedLength) ||
2023		!reader.readU24LengthPrefixedBytes(&m.compressed) ||
2024		len(reader) != 0 {
2025		return false
2026	}
2027
2028	if m.uncompressedLength >= 1<<17 {
2029		return false
2030	}
2031
2032	return true
2033}
2034
2035type serverKeyExchangeMsg struct {
2036	raw []byte
2037	key []byte
2038}
2039
2040func (m *serverKeyExchangeMsg) marshal() []byte {
2041	if m.raw != nil {
2042		return m.raw
2043	}
2044	msg := newByteBuilder()
2045	msg.addU8(typeServerKeyExchange)
2046	msg.addU24LengthPrefixed().addBytes(m.key)
2047	m.raw = msg.finish()
2048	return m.raw
2049}
2050
2051func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool {
2052	m.raw = data
2053	if len(data) < 4 {
2054		return false
2055	}
2056	m.key = data[4:]
2057	return true
2058}
2059
2060type certificateStatusMsg struct {
2061	raw        []byte
2062	statusType uint8
2063	response   []byte
2064}
2065
2066func (m *certificateStatusMsg) marshal() []byte {
2067	if m.raw != nil {
2068		return m.raw
2069	}
2070
2071	var x []byte
2072	if m.statusType == statusTypeOCSP {
2073		msg := newByteBuilder()
2074		msg.addU8(typeCertificateStatus)
2075		body := msg.addU24LengthPrefixed()
2076		body.addU8(statusTypeOCSP)
2077		body.addU24LengthPrefixed().addBytes(m.response)
2078		x = msg.finish()
2079	} else {
2080		x = []byte{typeCertificateStatus, 0, 0, 1, m.statusType}
2081	}
2082
2083	m.raw = x
2084	return x
2085}
2086
2087func (m *certificateStatusMsg) unmarshal(data []byte) bool {
2088	m.raw = data
2089	reader := byteReader(data[4:])
2090	if !reader.readU8(&m.statusType) ||
2091		m.statusType != statusTypeOCSP ||
2092		!reader.readU24LengthPrefixedBytes(&m.response) ||
2093		len(reader) != 0 {
2094		return false
2095	}
2096	return true
2097}
2098
2099type serverHelloDoneMsg struct{}
2100
2101func (m *serverHelloDoneMsg) marshal() []byte {
2102	x := make([]byte, 4)
2103	x[0] = typeServerHelloDone
2104	return x
2105}
2106
2107func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
2108	return len(data) == 4
2109}
2110
2111type clientKeyExchangeMsg struct {
2112	raw        []byte
2113	ciphertext []byte
2114}
2115
2116func (m *clientKeyExchangeMsg) marshal() []byte {
2117	if m.raw != nil {
2118		return m.raw
2119	}
2120	msg := newByteBuilder()
2121	msg.addU8(typeClientKeyExchange)
2122	msg.addU24LengthPrefixed().addBytes(m.ciphertext)
2123	m.raw = msg.finish()
2124	return m.raw
2125}
2126
2127func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool {
2128	m.raw = data
2129	if len(data) < 4 {
2130		return false
2131	}
2132	l := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
2133	if l != len(data)-4 {
2134		return false
2135	}
2136	m.ciphertext = data[4:]
2137	return true
2138}
2139
2140type finishedMsg struct {
2141	raw        []byte
2142	verifyData []byte
2143}
2144
2145func (m *finishedMsg) marshal() []byte {
2146	if m.raw != nil {
2147		return m.raw
2148	}
2149
2150	msg := newByteBuilder()
2151	msg.addU8(typeFinished)
2152	msg.addU24LengthPrefixed().addBytes(m.verifyData)
2153	m.raw = msg.finish()
2154	return m.raw
2155}
2156
2157func (m *finishedMsg) unmarshal(data []byte) bool {
2158	m.raw = data
2159	if len(data) < 4 {
2160		return false
2161	}
2162	m.verifyData = data[4:]
2163	return true
2164}
2165
2166type nextProtoMsg struct {
2167	raw   []byte
2168	proto string
2169}
2170
2171func (m *nextProtoMsg) marshal() []byte {
2172	if m.raw != nil {
2173		return m.raw
2174	}
2175
2176	padding := 32 - (len(m.proto)+2)%32
2177
2178	msg := newByteBuilder()
2179	msg.addU8(typeNextProtocol)
2180	body := msg.addU24LengthPrefixed()
2181	body.addU8LengthPrefixed().addBytes([]byte(m.proto))
2182	body.addU8LengthPrefixed().addBytes(make([]byte, padding))
2183	m.raw = msg.finish()
2184	return m.raw
2185}
2186
2187func (m *nextProtoMsg) unmarshal(data []byte) bool {
2188	m.raw = data
2189	reader := byteReader(data[4:])
2190	var proto, padding []byte
2191	if !reader.readU8LengthPrefixedBytes(&proto) ||
2192		!reader.readU8LengthPrefixedBytes(&padding) ||
2193		len(reader) != 0 {
2194		return false
2195	}
2196	m.proto = string(proto)
2197
2198	// Padding is not meant to be checked normally, but as this is a testing
2199	// implementation, we check the padding is as expected.
2200	if len(padding) != 32-(len(m.proto)+2)%32 {
2201		return false
2202	}
2203	for _, v := range padding {
2204		if v != 0 {
2205			return false
2206		}
2207	}
2208
2209	return true
2210}
2211
2212type certificateRequestMsg struct {
2213	raw  []byte
2214	vers uint16
2215	// hasSignatureAlgorithm indicates whether this message includes a list
2216	// of signature and hash functions. This change was introduced with TLS
2217	// 1.2.
2218	hasSignatureAlgorithm bool
2219	// hasRequestContext indicates whether this message includes a context
2220	// field instead of certificateTypes. This change was introduced with
2221	// TLS 1.3.
2222	hasRequestContext bool
2223
2224	certificateTypes        []byte
2225	requestContext          []byte
2226	signatureAlgorithms     []signatureAlgorithm
2227	signatureAlgorithmsCert []signatureAlgorithm
2228	certificateAuthorities  [][]byte
2229	hasCAExtension          bool
2230	customExtension         uint16
2231}
2232
2233func (m *certificateRequestMsg) marshal() []byte {
2234	if m.raw != nil {
2235		return m.raw
2236	}
2237
2238	// See http://tools.ietf.org/html/rfc4346#section-7.4.4
2239	builder := newByteBuilder()
2240	builder.addU8(typeCertificateRequest)
2241	body := builder.addU24LengthPrefixed()
2242
2243	if m.hasRequestContext {
2244		requestContext := body.addU8LengthPrefixed()
2245		requestContext.addBytes(m.requestContext)
2246		extensions := newByteBuilder()
2247		extensions = body.addU16LengthPrefixed()
2248		if m.hasSignatureAlgorithm {
2249			extensions.addU16(extensionSignatureAlgorithms)
2250			signatureAlgorithms := extensions.addU16LengthPrefixed().addU16LengthPrefixed()
2251			for _, sigAlg := range m.signatureAlgorithms {
2252				signatureAlgorithms.addU16(uint16(sigAlg))
2253			}
2254		}
2255		if len(m.signatureAlgorithmsCert) > 0 {
2256			extensions.addU16(extensionSignatureAlgorithmsCert)
2257			signatureAlgorithmsCert := extensions.addU16LengthPrefixed().addU16LengthPrefixed()
2258			for _, sigAlg := range m.signatureAlgorithmsCert {
2259				signatureAlgorithmsCert.addU16(uint16(sigAlg))
2260			}
2261		}
2262		if len(m.certificateAuthorities) > 0 {
2263			extensions.addU16(extensionCertificateAuthorities)
2264			certificateAuthorities := extensions.addU16LengthPrefixed().addU16LengthPrefixed()
2265			for _, ca := range m.certificateAuthorities {
2266				caEntry := certificateAuthorities.addU16LengthPrefixed()
2267				caEntry.addBytes(ca)
2268			}
2269		}
2270
2271		if m.customExtension > 0 {
2272			extensions.addU16(m.customExtension)
2273			extensions.addU16LengthPrefixed()
2274		}
2275	} else {
2276		certificateTypes := body.addU8LengthPrefixed()
2277		certificateTypes.addBytes(m.certificateTypes)
2278
2279		if m.hasSignatureAlgorithm {
2280			signatureAlgorithms := body.addU16LengthPrefixed()
2281			for _, sigAlg := range m.signatureAlgorithms {
2282				signatureAlgorithms.addU16(uint16(sigAlg))
2283			}
2284		}
2285
2286		certificateAuthorities := body.addU16LengthPrefixed()
2287		for _, ca := range m.certificateAuthorities {
2288			caEntry := certificateAuthorities.addU16LengthPrefixed()
2289			caEntry.addBytes(ca)
2290		}
2291	}
2292
2293	m.raw = builder.finish()
2294	return m.raw
2295}
2296
2297func parseCAs(reader *byteReader, out *[][]byte) bool {
2298	var cas byteReader
2299	if !reader.readU16LengthPrefixed(&cas) {
2300		return false
2301	}
2302	for len(cas) > 0 {
2303		var ca []byte
2304		if !cas.readU16LengthPrefixedBytes(&ca) {
2305			return false
2306		}
2307		*out = append(*out, ca)
2308	}
2309	return true
2310}
2311
2312func (m *certificateRequestMsg) unmarshal(data []byte) bool {
2313	m.raw = data
2314	reader := byteReader(data[4:])
2315
2316	if m.hasRequestContext {
2317		var extensions byteReader
2318		if !reader.readU8LengthPrefixedBytes(&m.requestContext) ||
2319			!reader.readU16LengthPrefixed(&extensions) ||
2320			len(reader) != 0 ||
2321			!checkDuplicateExtensions(extensions) {
2322			return false
2323		}
2324		for len(extensions) > 0 {
2325			var extension uint16
2326			var body byteReader
2327			if !extensions.readU16(&extension) ||
2328				!extensions.readU16LengthPrefixed(&body) {
2329				return false
2330			}
2331			switch extension {
2332			case extensionSignatureAlgorithms:
2333				if !parseSignatureAlgorithms(&body, &m.signatureAlgorithms, false) || len(body) != 0 {
2334					return false
2335				}
2336			case extensionSignatureAlgorithmsCert:
2337				if !parseSignatureAlgorithms(&body, &m.signatureAlgorithmsCert, false) || len(body) != 0 {
2338					return false
2339				}
2340			case extensionCertificateAuthorities:
2341				if !parseCAs(&body, &m.certificateAuthorities) || len(body) != 0 {
2342					return false
2343				}
2344				m.hasCAExtension = true
2345			}
2346		}
2347	} else {
2348		if !reader.readU8LengthPrefixedBytes(&m.certificateTypes) {
2349			return false
2350		}
2351		// In TLS 1.2, the supported_signature_algorithms field in
2352		// CertificateRequest may be empty.
2353		if m.hasSignatureAlgorithm && !parseSignatureAlgorithms(&reader, &m.signatureAlgorithms, true) {
2354			return false
2355		}
2356		if !parseCAs(&reader, &m.certificateAuthorities) ||
2357			len(reader) != 0 {
2358			return false
2359		}
2360	}
2361
2362	return true
2363}
2364
2365type certificateVerifyMsg struct {
2366	raw                   []byte
2367	hasSignatureAlgorithm bool
2368	signatureAlgorithm    signatureAlgorithm
2369	signature             []byte
2370}
2371
2372func (m *certificateVerifyMsg) marshal() (x []byte) {
2373	if m.raw != nil {
2374		return m.raw
2375	}
2376
2377	// See http://tools.ietf.org/html/rfc4346#section-7.4.8
2378	siglength := len(m.signature)
2379	length := 2 + siglength
2380	if m.hasSignatureAlgorithm {
2381		length += 2
2382	}
2383	x = make([]byte, 4+length)
2384	x[0] = typeCertificateVerify
2385	x[1] = uint8(length >> 16)
2386	x[2] = uint8(length >> 8)
2387	x[3] = uint8(length)
2388	y := x[4:]
2389	if m.hasSignatureAlgorithm {
2390		y[0] = byte(m.signatureAlgorithm >> 8)
2391		y[1] = byte(m.signatureAlgorithm)
2392		y = y[2:]
2393	}
2394	y[0] = uint8(siglength >> 8)
2395	y[1] = uint8(siglength)
2396	copy(y[2:], m.signature)
2397
2398	m.raw = x
2399
2400	return
2401}
2402
2403func (m *certificateVerifyMsg) unmarshal(data []byte) bool {
2404	m.raw = data
2405
2406	if len(data) < 6 {
2407		return false
2408	}
2409
2410	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
2411	if uint32(len(data))-4 != length {
2412		return false
2413	}
2414
2415	data = data[4:]
2416	if m.hasSignatureAlgorithm {
2417		m.signatureAlgorithm = signatureAlgorithm(data[0])<<8 | signatureAlgorithm(data[1])
2418		data = data[2:]
2419	}
2420
2421	if len(data) < 2 {
2422		return false
2423	}
2424	siglength := int(data[0])<<8 + int(data[1])
2425	data = data[2:]
2426	if len(data) != siglength {
2427		return false
2428	}
2429
2430	m.signature = data
2431
2432	return true
2433}
2434
2435type newSessionTicketMsg struct {
2436	raw                         []byte
2437	vers                        uint16
2438	isDTLS                      bool
2439	ticketLifetime              uint32
2440	ticketAgeAdd                uint32
2441	ticketNonce                 []byte
2442	ticket                      []byte
2443	maxEarlyDataSize            uint32
2444	customExtension             string
2445	duplicateEarlyDataExtension bool
2446	hasGREASEExtension          bool
2447}
2448
2449func (m *newSessionTicketMsg) marshal() []byte {
2450	if m.raw != nil {
2451		return m.raw
2452	}
2453
2454	version, ok := wireToVersion(m.vers, m.isDTLS)
2455	if !ok {
2456		panic("unknown version")
2457	}
2458
2459	// See http://tools.ietf.org/html/rfc5077#section-3.3
2460	ticketMsg := newByteBuilder()
2461	ticketMsg.addU8(typeNewSessionTicket)
2462	body := ticketMsg.addU24LengthPrefixed()
2463	body.addU32(m.ticketLifetime)
2464	if version >= VersionTLS13 {
2465		body.addU32(m.ticketAgeAdd)
2466		body.addU8LengthPrefixed().addBytes(m.ticketNonce)
2467	}
2468
2469	ticket := body.addU16LengthPrefixed()
2470	ticket.addBytes(m.ticket)
2471
2472	if version >= VersionTLS13 {
2473		extensions := body.addU16LengthPrefixed()
2474		if m.maxEarlyDataSize > 0 {
2475			extensions.addU16(extensionEarlyData)
2476			extensions.addU16LengthPrefixed().addU32(m.maxEarlyDataSize)
2477			if m.duplicateEarlyDataExtension {
2478				extensions.addU16(extensionEarlyData)
2479				extensions.addU16LengthPrefixed().addU32(m.maxEarlyDataSize)
2480			}
2481		}
2482		if len(m.customExtension) > 0 {
2483			extensions.addU16(extensionCustom)
2484			extensions.addU16LengthPrefixed().addBytes([]byte(m.customExtension))
2485		}
2486	}
2487
2488	m.raw = ticketMsg.finish()
2489	return m.raw
2490}
2491
2492func (m *newSessionTicketMsg) unmarshal(data []byte) bool {
2493	m.raw = data
2494
2495	version, ok := wireToVersion(m.vers, m.isDTLS)
2496	if !ok {
2497		panic("unknown version")
2498	}
2499
2500	if len(data) < 8 {
2501		return false
2502	}
2503	m.ticketLifetime = uint32(data[4])<<24 | uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
2504	data = data[8:]
2505
2506	if version >= VersionTLS13 {
2507		if len(data) < 4 {
2508			return false
2509		}
2510		m.ticketAgeAdd = uint32(data[0])<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
2511		data = data[4:]
2512		nonceLen := int(data[0])
2513		data = data[1:]
2514		if len(data) < nonceLen {
2515			return false
2516		}
2517		m.ticketNonce = data[:nonceLen]
2518		data = data[nonceLen:]
2519	}
2520
2521	if len(data) < 2 {
2522		return false
2523	}
2524	ticketLen := int(data[0])<<8 + int(data[1])
2525	data = data[2:]
2526	if len(data) < ticketLen {
2527		return false
2528	}
2529
2530	if version >= VersionTLS13 && ticketLen == 0 {
2531		return false
2532	}
2533
2534	m.ticket = data[:ticketLen]
2535	data = data[ticketLen:]
2536
2537	if version >= VersionTLS13 {
2538		if len(data) < 2 {
2539			return false
2540		}
2541
2542		extensionsLength := int(data[0])<<8 | int(data[1])
2543		data = data[2:]
2544		if extensionsLength != len(data) {
2545			return false
2546		}
2547
2548		for len(data) != 0 {
2549			if len(data) < 4 {
2550				return false
2551			}
2552			extension := uint16(data[0])<<8 | uint16(data[1])
2553			length := int(data[2])<<8 | int(data[3])
2554			data = data[4:]
2555			if len(data) < length {
2556				return false
2557			}
2558
2559			switch extension {
2560			case extensionEarlyData:
2561				if length != 4 {
2562					return false
2563				}
2564				m.maxEarlyDataSize = uint32(data[0])<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
2565			default:
2566				if isGREASEValue(extension) {
2567					m.hasGREASEExtension = true
2568				}
2569			}
2570
2571			data = data[length:]
2572		}
2573	}
2574
2575	if len(data) > 0 {
2576		return false
2577	}
2578
2579	return true
2580}
2581
2582type v2ClientHelloMsg struct {
2583	raw          []byte
2584	vers         uint16
2585	cipherSuites []uint16
2586	sessionID    []byte
2587	challenge    []byte
2588}
2589
2590func (m *v2ClientHelloMsg) marshal() []byte {
2591	if m.raw != nil {
2592		return m.raw
2593	}
2594
2595	length := 1 + 2 + 2 + 2 + 2 + len(m.cipherSuites)*3 + len(m.sessionID) + len(m.challenge)
2596
2597	x := make([]byte, length)
2598	x[0] = 1
2599	x[1] = uint8(m.vers >> 8)
2600	x[2] = uint8(m.vers)
2601	x[3] = uint8((len(m.cipherSuites) * 3) >> 8)
2602	x[4] = uint8(len(m.cipherSuites) * 3)
2603	x[5] = uint8(len(m.sessionID) >> 8)
2604	x[6] = uint8(len(m.sessionID))
2605	x[7] = uint8(len(m.challenge) >> 8)
2606	x[8] = uint8(len(m.challenge))
2607	y := x[9:]
2608	for i, spec := range m.cipherSuites {
2609		y[i*3] = 0
2610		y[i*3+1] = uint8(spec >> 8)
2611		y[i*3+2] = uint8(spec)
2612	}
2613	y = y[len(m.cipherSuites)*3:]
2614	copy(y, m.sessionID)
2615	y = y[len(m.sessionID):]
2616	copy(y, m.challenge)
2617
2618	m.raw = x
2619
2620	return x
2621}
2622
2623type helloVerifyRequestMsg struct {
2624	raw    []byte
2625	vers   uint16
2626	cookie []byte
2627}
2628
2629func (m *helloVerifyRequestMsg) marshal() []byte {
2630	if m.raw != nil {
2631		return m.raw
2632	}
2633
2634	length := 2 + 1 + len(m.cookie)
2635
2636	x := make([]byte, 4+length)
2637	x[0] = typeHelloVerifyRequest
2638	x[1] = uint8(length >> 16)
2639	x[2] = uint8(length >> 8)
2640	x[3] = uint8(length)
2641	vers := m.vers
2642	x[4] = uint8(vers >> 8)
2643	x[5] = uint8(vers)
2644	x[6] = uint8(len(m.cookie))
2645	copy(x[7:7+len(m.cookie)], m.cookie)
2646
2647	return x
2648}
2649
2650func (m *helloVerifyRequestMsg) unmarshal(data []byte) bool {
2651	if len(data) < 4+2+1 {
2652		return false
2653	}
2654	m.raw = data
2655	m.vers = uint16(data[4])<<8 | uint16(data[5])
2656	cookieLen := int(data[6])
2657	if cookieLen > 32 || len(data) != 7+cookieLen {
2658		return false
2659	}
2660	m.cookie = data[7 : 7+cookieLen]
2661
2662	return true
2663}
2664
2665type channelIDMsg struct {
2666	raw       []byte
2667	channelID []byte
2668}
2669
2670func (m *channelIDMsg) marshal() []byte {
2671	if m.raw != nil {
2672		return m.raw
2673	}
2674
2675	length := 2 + 2 + len(m.channelID)
2676
2677	x := make([]byte, 4+length)
2678	x[0] = typeChannelID
2679	x[1] = uint8(length >> 16)
2680	x[2] = uint8(length >> 8)
2681	x[3] = uint8(length)
2682	x[4] = uint8(extensionChannelID >> 8)
2683	x[5] = uint8(extensionChannelID & 0xff)
2684	x[6] = uint8(len(m.channelID) >> 8)
2685	x[7] = uint8(len(m.channelID) & 0xff)
2686	copy(x[8:], m.channelID)
2687
2688	return x
2689}
2690
2691func (m *channelIDMsg) unmarshal(data []byte) bool {
2692	if len(data) != 4+2+2+128 {
2693		return false
2694	}
2695	m.raw = data
2696	if (uint16(data[4])<<8)|uint16(data[5]) != extensionChannelID {
2697		return false
2698	}
2699	if int(data[6])<<8|int(data[7]) != 128 {
2700		return false
2701	}
2702	m.channelID = data[4+2+2:]
2703
2704	return true
2705}
2706
2707type helloRequestMsg struct {
2708}
2709
2710func (*helloRequestMsg) marshal() []byte {
2711	return []byte{typeHelloRequest, 0, 0, 0}
2712}
2713
2714func (*helloRequestMsg) unmarshal(data []byte) bool {
2715	return len(data) == 4
2716}
2717
2718type keyUpdateMsg struct {
2719	raw              []byte
2720	keyUpdateRequest byte
2721}
2722
2723func (m *keyUpdateMsg) marshal() []byte {
2724	if m.raw != nil {
2725		return m.raw
2726	}
2727
2728	return []byte{typeKeyUpdate, 0, 0, 1, m.keyUpdateRequest}
2729}
2730
2731func (m *keyUpdateMsg) unmarshal(data []byte) bool {
2732	m.raw = data
2733
2734	if len(data) != 5 {
2735		return false
2736	}
2737
2738	length := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
2739	if len(data)-4 != length {
2740		return false
2741	}
2742
2743	m.keyUpdateRequest = data[4]
2744	return m.keyUpdateRequest == keyUpdateNotRequested || m.keyUpdateRequest == keyUpdateRequested
2745}
2746
2747type endOfEarlyDataMsg struct {
2748	nonEmpty bool
2749}
2750
2751func (m *endOfEarlyDataMsg) marshal() []byte {
2752	if m.nonEmpty {
2753		return []byte{typeEndOfEarlyData, 0, 0, 1, 42}
2754	}
2755	return []byte{typeEndOfEarlyData, 0, 0, 0}
2756}
2757
2758func (*endOfEarlyDataMsg) unmarshal(data []byte) bool {
2759	return len(data) == 4
2760}
2761
2762// ssl3NoCertificateMsg is a dummy message to handle SSL 3.0 using a warning
2763// alert in the handshake.
2764type ssl3NoCertificateMsg struct{}
2765