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 qtls
6
7import (
8	"fmt"
9	"strings"
10
11	"golang.org/x/crypto/cryptobyte"
12)
13
14// The marshalingFunction type is an adapter to allow the use of ordinary
15// functions as cryptobyte.MarshalingValue.
16type marshalingFunction func(b *cryptobyte.Builder) error
17
18func (f marshalingFunction) Marshal(b *cryptobyte.Builder) error {
19	return f(b)
20}
21
22// addBytesWithLength appends a sequence of bytes to the cryptobyte.Builder. If
23// the length of the sequence is not the value specified, it produces an error.
24func addBytesWithLength(b *cryptobyte.Builder, v []byte, n int) {
25	b.AddValue(marshalingFunction(func(b *cryptobyte.Builder) error {
26		if len(v) != n {
27			return fmt.Errorf("invalid value length: expected %d, got %d", n, len(v))
28		}
29		b.AddBytes(v)
30		return nil
31	}))
32}
33
34// addUint64 appends a big-endian, 64-bit value to the cryptobyte.Builder.
35func addUint64(b *cryptobyte.Builder, v uint64) {
36	b.AddUint32(uint32(v >> 32))
37	b.AddUint32(uint32(v))
38}
39
40// readUint64 decodes a big-endian, 64-bit value into out and advances over it.
41// It reports whether the read was successful.
42func readUint64(s *cryptobyte.String, out *uint64) bool {
43	var hi, lo uint32
44	if !s.ReadUint32(&hi) || !s.ReadUint32(&lo) {
45		return false
46	}
47	*out = uint64(hi)<<32 | uint64(lo)
48	return true
49}
50
51// readUint8LengthPrefixed acts like s.ReadUint8LengthPrefixed, but targets a
52// []byte instead of a cryptobyte.String.
53func readUint8LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
54	return s.ReadUint8LengthPrefixed((*cryptobyte.String)(out))
55}
56
57// readUint16LengthPrefixed acts like s.ReadUint16LengthPrefixed, but targets a
58// []byte instead of a cryptobyte.String.
59func readUint16LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
60	return s.ReadUint16LengthPrefixed((*cryptobyte.String)(out))
61}
62
63// readUint24LengthPrefixed acts like s.ReadUint24LengthPrefixed, but targets a
64// []byte instead of a cryptobyte.String.
65func readUint24LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
66	return s.ReadUint24LengthPrefixed((*cryptobyte.String)(out))
67}
68
69type clientHelloMsg struct {
70	raw                              []byte
71	vers                             uint16
72	random                           []byte
73	sessionId                        []byte
74	cipherSuites                     []uint16
75	compressionMethods               []uint8
76	serverName                       string
77	ocspStapling                     bool
78	supportedCurves                  []CurveID
79	supportedPoints                  []uint8
80	ticketSupported                  bool
81	sessionTicket                    []uint8
82	supportedSignatureAlgorithms     []SignatureScheme
83	supportedSignatureAlgorithmsCert []SignatureScheme
84	secureRenegotiationSupported     bool
85	secureRenegotiation              []byte
86	alpnProtocols                    []string
87	scts                             bool
88	supportedVersions                []uint16
89	cookie                           []byte
90	keyShares                        []keyShare
91	earlyData                        bool
92	pskModes                         []uint8
93	pskIdentities                    []pskIdentity
94	pskBinders                       [][]byte
95	additionalExtensions             []Extension
96}
97
98func (m *clientHelloMsg) marshal() []byte {
99	if m.raw != nil {
100		return m.raw
101	}
102
103	var b cryptobyte.Builder
104	b.AddUint8(typeClientHello)
105	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
106		b.AddUint16(m.vers)
107		addBytesWithLength(b, m.random, 32)
108		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
109			b.AddBytes(m.sessionId)
110		})
111		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
112			for _, suite := range m.cipherSuites {
113				b.AddUint16(suite)
114			}
115		})
116		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
117			b.AddBytes(m.compressionMethods)
118		})
119
120		// If extensions aren't present, omit them.
121		var extensionsPresent bool
122		bWithoutExtensions := *b
123
124		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
125			if len(m.serverName) > 0 {
126				// RFC 6066, Section 3
127				b.AddUint16(extensionServerName)
128				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
129					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
130						b.AddUint8(0) // name_type = host_name
131						b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
132							b.AddBytes([]byte(m.serverName))
133						})
134					})
135				})
136			}
137			if m.ocspStapling {
138				// RFC 4366, Section 3.6
139				b.AddUint16(extensionStatusRequest)
140				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
141					b.AddUint8(1)  // status_type = ocsp
142					b.AddUint16(0) // empty responder_id_list
143					b.AddUint16(0) // empty request_extensions
144				})
145			}
146			if len(m.supportedCurves) > 0 {
147				// RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7
148				b.AddUint16(extensionSupportedCurves)
149				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
150					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
151						for _, curve := range m.supportedCurves {
152							b.AddUint16(uint16(curve))
153						}
154					})
155				})
156			}
157			if len(m.supportedPoints) > 0 {
158				// RFC 4492, Section 5.1.2
159				b.AddUint16(extensionSupportedPoints)
160				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
161					b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
162						b.AddBytes(m.supportedPoints)
163					})
164				})
165			}
166			if m.ticketSupported {
167				// RFC 5077, Section 3.2
168				b.AddUint16(extensionSessionTicket)
169				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
170					b.AddBytes(m.sessionTicket)
171				})
172			}
173			if len(m.supportedSignatureAlgorithms) > 0 {
174				// RFC 5246, Section 7.4.1.4.1
175				b.AddUint16(extensionSignatureAlgorithms)
176				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
177					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
178						for _, sigAlgo := range m.supportedSignatureAlgorithms {
179							b.AddUint16(uint16(sigAlgo))
180						}
181					})
182				})
183			}
184			if len(m.supportedSignatureAlgorithmsCert) > 0 {
185				// RFC 8446, Section 4.2.3
186				b.AddUint16(extensionSignatureAlgorithmsCert)
187				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
188					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
189						for _, sigAlgo := range m.supportedSignatureAlgorithmsCert {
190							b.AddUint16(uint16(sigAlgo))
191						}
192					})
193				})
194			}
195			if m.secureRenegotiationSupported {
196				// RFC 5746, Section 3.2
197				b.AddUint16(extensionRenegotiationInfo)
198				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
199					b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
200						b.AddBytes(m.secureRenegotiation)
201					})
202				})
203			}
204			if len(m.alpnProtocols) > 0 {
205				// RFC 7301, Section 3.1
206				b.AddUint16(extensionALPN)
207				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
208					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
209						for _, proto := range m.alpnProtocols {
210							b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
211								b.AddBytes([]byte(proto))
212							})
213						}
214					})
215				})
216			}
217			if m.scts {
218				// RFC 6962, Section 3.3.1
219				b.AddUint16(extensionSCT)
220				b.AddUint16(0) // empty extension_data
221			}
222			if len(m.supportedVersions) > 0 {
223				// RFC 8446, Section 4.2.1
224				b.AddUint16(extensionSupportedVersions)
225				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
226					b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
227						for _, vers := range m.supportedVersions {
228							b.AddUint16(vers)
229						}
230					})
231				})
232			}
233			if len(m.cookie) > 0 {
234				// RFC 8446, Section 4.2.2
235				b.AddUint16(extensionCookie)
236				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
237					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
238						b.AddBytes(m.cookie)
239					})
240				})
241			}
242			if len(m.keyShares) > 0 {
243				// RFC 8446, Section 4.2.8
244				b.AddUint16(extensionKeyShare)
245				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
246					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
247						for _, ks := range m.keyShares {
248							b.AddUint16(uint16(ks.group))
249							b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
250								b.AddBytes(ks.data)
251							})
252						}
253					})
254				})
255			}
256			if m.earlyData {
257				// RFC 8446, Section 4.2.10
258				b.AddUint16(extensionEarlyData)
259				b.AddUint16(0) // empty extension_data
260			}
261			if len(m.pskModes) > 0 {
262				// RFC 8446, Section 4.2.9
263				b.AddUint16(extensionPSKModes)
264				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
265					b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
266						b.AddBytes(m.pskModes)
267					})
268				})
269			}
270			for _, ext := range m.additionalExtensions {
271				b.AddUint16(ext.Type)
272				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
273					b.AddBytes(ext.Data)
274				})
275			}
276			if len(m.pskIdentities) > 0 { // pre_shared_key must be the last extension
277				// RFC 8446, Section 4.2.11
278				b.AddUint16(extensionPreSharedKey)
279				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
280					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
281						for _, psk := range m.pskIdentities {
282							b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
283								b.AddBytes(psk.label)
284							})
285							b.AddUint32(psk.obfuscatedTicketAge)
286						}
287					})
288					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
289						for _, binder := range m.pskBinders {
290							b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
291								b.AddBytes(binder)
292							})
293						}
294					})
295				})
296			}
297
298			extensionsPresent = len(b.BytesOrPanic()) > 2
299		})
300
301		if !extensionsPresent {
302			*b = bWithoutExtensions
303		}
304	})
305
306	m.raw = b.BytesOrPanic()
307	return m.raw
308}
309
310// marshalWithoutBinders returns the ClientHello through the
311// PreSharedKeyExtension.identities field, according to RFC 8446, Section
312// 4.2.11.2. Note that m.pskBinders must be set to slices of the correct length.
313func (m *clientHelloMsg) marshalWithoutBinders() []byte {
314	bindersLen := 2 // uint16 length prefix
315	for _, binder := range m.pskBinders {
316		bindersLen += 1 // uint8 length prefix
317		bindersLen += len(binder)
318	}
319
320	fullMessage := m.marshal()
321	return fullMessage[:len(fullMessage)-bindersLen]
322}
323
324// updateBinders updates the m.pskBinders field, if necessary updating the
325// cached marshaled representation. The supplied binders must have the same
326// length as the current m.pskBinders.
327func (m *clientHelloMsg) updateBinders(pskBinders [][]byte) {
328	if len(pskBinders) != len(m.pskBinders) {
329		panic("tls: internal error: pskBinders length mismatch")
330	}
331	for i := range m.pskBinders {
332		if len(pskBinders[i]) != len(m.pskBinders[i]) {
333			panic("tls: internal error: pskBinders length mismatch")
334		}
335	}
336	m.pskBinders = pskBinders
337	if m.raw != nil {
338		lenWithoutBinders := len(m.marshalWithoutBinders())
339		// TODO(filippo): replace with NewFixedBuilder once CL 148882 is imported.
340		b := cryptobyte.NewBuilder(m.raw[:lenWithoutBinders])
341		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
342			for _, binder := range m.pskBinders {
343				b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
344					b.AddBytes(binder)
345				})
346			}
347		})
348		if len(b.BytesOrPanic()) != len(m.raw) {
349			panic("tls: internal error: failed to update binders")
350		}
351	}
352}
353
354func (m *clientHelloMsg) unmarshal(data []byte) bool {
355	*m = clientHelloMsg{raw: data}
356	s := cryptobyte.String(data)
357
358	if !s.Skip(4) || // message type and uint24 length field
359		!s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) ||
360		!readUint8LengthPrefixed(&s, &m.sessionId) {
361		return false
362	}
363
364	var cipherSuites cryptobyte.String
365	if !s.ReadUint16LengthPrefixed(&cipherSuites) {
366		return false
367	}
368	m.cipherSuites = []uint16{}
369	m.secureRenegotiationSupported = false
370	for !cipherSuites.Empty() {
371		var suite uint16
372		if !cipherSuites.ReadUint16(&suite) {
373			return false
374		}
375		if suite == scsvRenegotiation {
376			m.secureRenegotiationSupported = true
377		}
378		m.cipherSuites = append(m.cipherSuites, suite)
379	}
380
381	if !readUint8LengthPrefixed(&s, &m.compressionMethods) {
382		return false
383	}
384
385	if s.Empty() {
386		// ClientHello is optionally followed by extension data
387		return true
388	}
389
390	var extensions cryptobyte.String
391	if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
392		return false
393	}
394
395	for !extensions.Empty() {
396		var ext uint16
397		var extData cryptobyte.String
398		if !extensions.ReadUint16(&ext) ||
399			!extensions.ReadUint16LengthPrefixed(&extData) {
400			return false
401		}
402
403		switch ext {
404		case extensionServerName:
405			// RFC 6066, Section 3
406			var nameList cryptobyte.String
407			if !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() {
408				return false
409			}
410			for !nameList.Empty() {
411				var nameType uint8
412				var serverName cryptobyte.String
413				if !nameList.ReadUint8(&nameType) ||
414					!nameList.ReadUint16LengthPrefixed(&serverName) ||
415					serverName.Empty() {
416					return false
417				}
418				if nameType != 0 {
419					continue
420				}
421				if len(m.serverName) != 0 {
422					// Multiple names of the same name_type are prohibited.
423					return false
424				}
425				m.serverName = string(serverName)
426				// An SNI value may not include a trailing dot.
427				if strings.HasSuffix(m.serverName, ".") {
428					return false
429				}
430			}
431		case extensionStatusRequest:
432			// RFC 4366, Section 3.6
433			var statusType uint8
434			var ignored cryptobyte.String
435			if !extData.ReadUint8(&statusType) ||
436				!extData.ReadUint16LengthPrefixed(&ignored) ||
437				!extData.ReadUint16LengthPrefixed(&ignored) {
438				return false
439			}
440			m.ocspStapling = statusType == statusTypeOCSP
441		case extensionSupportedCurves:
442			// RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7
443			var curves cryptobyte.String
444			if !extData.ReadUint16LengthPrefixed(&curves) || curves.Empty() {
445				return false
446			}
447			for !curves.Empty() {
448				var curve uint16
449				if !curves.ReadUint16(&curve) {
450					return false
451				}
452				m.supportedCurves = append(m.supportedCurves, CurveID(curve))
453			}
454		case extensionSupportedPoints:
455			// RFC 4492, Section 5.1.2
456			if !readUint8LengthPrefixed(&extData, &m.supportedPoints) ||
457				len(m.supportedPoints) == 0 {
458				return false
459			}
460		case extensionSessionTicket:
461			// RFC 5077, Section 3.2
462			m.ticketSupported = true
463			extData.ReadBytes(&m.sessionTicket, len(extData))
464		case extensionSignatureAlgorithms:
465			// RFC 5246, Section 7.4.1.4.1
466			var sigAndAlgs cryptobyte.String
467			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
468				return false
469			}
470			for !sigAndAlgs.Empty() {
471				var sigAndAlg uint16
472				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
473					return false
474				}
475				m.supportedSignatureAlgorithms = append(
476					m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg))
477			}
478		case extensionSignatureAlgorithmsCert:
479			// RFC 8446, Section 4.2.3
480			var sigAndAlgs cryptobyte.String
481			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
482				return false
483			}
484			for !sigAndAlgs.Empty() {
485				var sigAndAlg uint16
486				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
487					return false
488				}
489				m.supportedSignatureAlgorithmsCert = append(
490					m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg))
491			}
492		case extensionRenegotiationInfo:
493			// RFC 5746, Section 3.2
494			if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) {
495				return false
496			}
497			m.secureRenegotiationSupported = true
498		case extensionALPN:
499			// RFC 7301, Section 3.1
500			var protoList cryptobyte.String
501			if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
502				return false
503			}
504			for !protoList.Empty() {
505				var proto cryptobyte.String
506				if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {
507					return false
508				}
509				m.alpnProtocols = append(m.alpnProtocols, string(proto))
510			}
511		case extensionSCT:
512			// RFC 6962, Section 3.3.1
513			m.scts = true
514		case extensionSupportedVersions:
515			// RFC 8446, Section 4.2.1
516			var versList cryptobyte.String
517			if !extData.ReadUint8LengthPrefixed(&versList) || versList.Empty() {
518				return false
519			}
520			for !versList.Empty() {
521				var vers uint16
522				if !versList.ReadUint16(&vers) {
523					return false
524				}
525				m.supportedVersions = append(m.supportedVersions, vers)
526			}
527		case extensionCookie:
528			// RFC 8446, Section 4.2.2
529			if !readUint16LengthPrefixed(&extData, &m.cookie) ||
530				len(m.cookie) == 0 {
531				return false
532			}
533		case extensionKeyShare:
534			// RFC 8446, Section 4.2.8
535			var clientShares cryptobyte.String
536			if !extData.ReadUint16LengthPrefixed(&clientShares) {
537				return false
538			}
539			for !clientShares.Empty() {
540				var ks keyShare
541				if !clientShares.ReadUint16((*uint16)(&ks.group)) ||
542					!readUint16LengthPrefixed(&clientShares, &ks.data) ||
543					len(ks.data) == 0 {
544					return false
545				}
546				m.keyShares = append(m.keyShares, ks)
547			}
548		case extensionEarlyData:
549			// RFC 8446, Section 4.2.10
550			m.earlyData = true
551		case extensionPSKModes:
552			// RFC 8446, Section 4.2.9
553			if !readUint8LengthPrefixed(&extData, &m.pskModes) {
554				return false
555			}
556		case extensionPreSharedKey:
557			// RFC 8446, Section 4.2.11
558			if !extensions.Empty() {
559				return false // pre_shared_key must be the last extension
560			}
561			var identities cryptobyte.String
562			if !extData.ReadUint16LengthPrefixed(&identities) || identities.Empty() {
563				return false
564			}
565			for !identities.Empty() {
566				var psk pskIdentity
567				if !readUint16LengthPrefixed(&identities, &psk.label) ||
568					!identities.ReadUint32(&psk.obfuscatedTicketAge) ||
569					len(psk.label) == 0 {
570					return false
571				}
572				m.pskIdentities = append(m.pskIdentities, psk)
573			}
574			var binders cryptobyte.String
575			if !extData.ReadUint16LengthPrefixed(&binders) || binders.Empty() {
576				return false
577			}
578			for !binders.Empty() {
579				var binder []byte
580				if !readUint8LengthPrefixed(&binders, &binder) ||
581					len(binder) == 0 {
582					return false
583				}
584				m.pskBinders = append(m.pskBinders, binder)
585			}
586		default:
587			m.additionalExtensions = append(m.additionalExtensions, Extension{Type: ext, Data: extData})
588			continue
589		}
590
591		if !extData.Empty() {
592			return false
593		}
594	}
595
596	return true
597}
598
599type serverHelloMsg struct {
600	raw                          []byte
601	vers                         uint16
602	random                       []byte
603	sessionId                    []byte
604	cipherSuite                  uint16
605	compressionMethod            uint8
606	ocspStapling                 bool
607	ticketSupported              bool
608	secureRenegotiationSupported bool
609	secureRenegotiation          []byte
610	alpnProtocol                 string
611	scts                         [][]byte
612	supportedVersion             uint16
613	serverShare                  keyShare
614	selectedIdentityPresent      bool
615	selectedIdentity             uint16
616	supportedPoints              []uint8
617
618	// HelloRetryRequest extensions
619	cookie        []byte
620	selectedGroup CurveID
621}
622
623func (m *serverHelloMsg) marshal() []byte {
624	if m.raw != nil {
625		return m.raw
626	}
627
628	var b cryptobyte.Builder
629	b.AddUint8(typeServerHello)
630	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
631		b.AddUint16(m.vers)
632		addBytesWithLength(b, m.random, 32)
633		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
634			b.AddBytes(m.sessionId)
635		})
636		b.AddUint16(m.cipherSuite)
637		b.AddUint8(m.compressionMethod)
638
639		// If extensions aren't present, omit them.
640		var extensionsPresent bool
641		bWithoutExtensions := *b
642
643		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
644			if m.ocspStapling {
645				b.AddUint16(extensionStatusRequest)
646				b.AddUint16(0) // empty extension_data
647			}
648			if m.ticketSupported {
649				b.AddUint16(extensionSessionTicket)
650				b.AddUint16(0) // empty extension_data
651			}
652			if m.secureRenegotiationSupported {
653				b.AddUint16(extensionRenegotiationInfo)
654				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
655					b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
656						b.AddBytes(m.secureRenegotiation)
657					})
658				})
659			}
660			if len(m.alpnProtocol) > 0 {
661				b.AddUint16(extensionALPN)
662				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
663					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
664						b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
665							b.AddBytes([]byte(m.alpnProtocol))
666						})
667					})
668				})
669			}
670			if len(m.scts) > 0 {
671				b.AddUint16(extensionSCT)
672				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
673					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
674						for _, sct := range m.scts {
675							b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
676								b.AddBytes(sct)
677							})
678						}
679					})
680				})
681			}
682			if m.supportedVersion != 0 {
683				b.AddUint16(extensionSupportedVersions)
684				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
685					b.AddUint16(m.supportedVersion)
686				})
687			}
688			if m.serverShare.group != 0 {
689				b.AddUint16(extensionKeyShare)
690				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
691					b.AddUint16(uint16(m.serverShare.group))
692					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
693						b.AddBytes(m.serverShare.data)
694					})
695				})
696			}
697			if m.selectedIdentityPresent {
698				b.AddUint16(extensionPreSharedKey)
699				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
700					b.AddUint16(m.selectedIdentity)
701				})
702			}
703
704			if len(m.cookie) > 0 {
705				b.AddUint16(extensionCookie)
706				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
707					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
708						b.AddBytes(m.cookie)
709					})
710				})
711			}
712			if m.selectedGroup != 0 {
713				b.AddUint16(extensionKeyShare)
714				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
715					b.AddUint16(uint16(m.selectedGroup))
716				})
717			}
718			if len(m.supportedPoints) > 0 {
719				b.AddUint16(extensionSupportedPoints)
720				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
721					b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
722						b.AddBytes(m.supportedPoints)
723					})
724				})
725			}
726
727			extensionsPresent = len(b.BytesOrPanic()) > 2
728		})
729
730		if !extensionsPresent {
731			*b = bWithoutExtensions
732		}
733	})
734
735	m.raw = b.BytesOrPanic()
736	return m.raw
737}
738
739func (m *serverHelloMsg) unmarshal(data []byte) bool {
740	*m = serverHelloMsg{raw: data}
741	s := cryptobyte.String(data)
742
743	if !s.Skip(4) || // message type and uint24 length field
744		!s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) ||
745		!readUint8LengthPrefixed(&s, &m.sessionId) ||
746		!s.ReadUint16(&m.cipherSuite) ||
747		!s.ReadUint8(&m.compressionMethod) {
748		return false
749	}
750
751	if s.Empty() {
752		// ServerHello is optionally followed by extension data
753		return true
754	}
755
756	var extensions cryptobyte.String
757	if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
758		return false
759	}
760
761	for !extensions.Empty() {
762		var extension uint16
763		var extData cryptobyte.String
764		if !extensions.ReadUint16(&extension) ||
765			!extensions.ReadUint16LengthPrefixed(&extData) {
766			return false
767		}
768
769		switch extension {
770		case extensionStatusRequest:
771			m.ocspStapling = true
772		case extensionSessionTicket:
773			m.ticketSupported = true
774		case extensionRenegotiationInfo:
775			if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) {
776				return false
777			}
778			m.secureRenegotiationSupported = true
779		case extensionALPN:
780			var protoList cryptobyte.String
781			if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
782				return false
783			}
784			var proto cryptobyte.String
785			if !protoList.ReadUint8LengthPrefixed(&proto) ||
786				proto.Empty() || !protoList.Empty() {
787				return false
788			}
789			m.alpnProtocol = string(proto)
790		case extensionSCT:
791			var sctList cryptobyte.String
792			if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() {
793				return false
794			}
795			for !sctList.Empty() {
796				var sct []byte
797				if !readUint16LengthPrefixed(&sctList, &sct) ||
798					len(sct) == 0 {
799					return false
800				}
801				m.scts = append(m.scts, sct)
802			}
803		case extensionSupportedVersions:
804			if !extData.ReadUint16(&m.supportedVersion) {
805				return false
806			}
807		case extensionCookie:
808			if !readUint16LengthPrefixed(&extData, &m.cookie) ||
809				len(m.cookie) == 0 {
810				return false
811			}
812		case extensionKeyShare:
813			// This extension has different formats in SH and HRR, accept either
814			// and let the handshake logic decide. See RFC 8446, Section 4.2.8.
815			if len(extData) == 2 {
816				if !extData.ReadUint16((*uint16)(&m.selectedGroup)) {
817					return false
818				}
819			} else {
820				if !extData.ReadUint16((*uint16)(&m.serverShare.group)) ||
821					!readUint16LengthPrefixed(&extData, &m.serverShare.data) {
822					return false
823				}
824			}
825		case extensionPreSharedKey:
826			m.selectedIdentityPresent = true
827			if !extData.ReadUint16(&m.selectedIdentity) {
828				return false
829			}
830		case extensionSupportedPoints:
831			// RFC 4492, Section 5.1.2
832			if !readUint8LengthPrefixed(&extData, &m.supportedPoints) ||
833				len(m.supportedPoints) == 0 {
834				return false
835			}
836		default:
837			// Ignore unknown extensions.
838			continue
839		}
840
841		if !extData.Empty() {
842			return false
843		}
844	}
845
846	return true
847}
848
849type encryptedExtensionsMsg struct {
850	raw          []byte
851	alpnProtocol string
852	earlyData    bool
853
854	additionalExtensions []Extension
855}
856
857func (m *encryptedExtensionsMsg) marshal() []byte {
858	if m.raw != nil {
859		return m.raw
860	}
861
862	var b cryptobyte.Builder
863	b.AddUint8(typeEncryptedExtensions)
864	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
865		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
866			if len(m.alpnProtocol) > 0 {
867				b.AddUint16(extensionALPN)
868				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
869					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
870						b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
871							b.AddBytes([]byte(m.alpnProtocol))
872						})
873					})
874				})
875			}
876			if m.earlyData {
877				// RFC 8446, Section 4.2.10
878				b.AddUint16(extensionEarlyData)
879				b.AddUint16(0) // empty extension_data
880			}
881			for _, ext := range m.additionalExtensions {
882				b.AddUint16(ext.Type)
883				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
884					b.AddBytes(ext.Data)
885				})
886			}
887		})
888	})
889
890	m.raw = b.BytesOrPanic()
891	return m.raw
892}
893
894func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool {
895	*m = encryptedExtensionsMsg{raw: data}
896	s := cryptobyte.String(data)
897
898	var extensions cryptobyte.String
899	if !s.Skip(4) || // message type and uint24 length field
900		!s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
901		return false
902	}
903
904	for !extensions.Empty() {
905		var ext uint16
906		var extData cryptobyte.String
907		if !extensions.ReadUint16(&ext) ||
908			!extensions.ReadUint16LengthPrefixed(&extData) {
909			return false
910		}
911
912		switch ext {
913		case extensionALPN:
914			var protoList cryptobyte.String
915			if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
916				return false
917			}
918			var proto cryptobyte.String
919			if !protoList.ReadUint8LengthPrefixed(&proto) ||
920				proto.Empty() || !protoList.Empty() {
921				return false
922			}
923			m.alpnProtocol = string(proto)
924		case extensionEarlyData:
925			m.earlyData = true
926		default:
927			m.additionalExtensions = append(m.additionalExtensions, Extension{Type: ext, Data: extData})
928			continue
929		}
930
931		if !extData.Empty() {
932			return false
933		}
934	}
935
936	return true
937}
938
939type endOfEarlyDataMsg struct{}
940
941func (m *endOfEarlyDataMsg) marshal() []byte {
942	x := make([]byte, 4)
943	x[0] = typeEndOfEarlyData
944	return x
945}
946
947func (m *endOfEarlyDataMsg) unmarshal(data []byte) bool {
948	return len(data) == 4
949}
950
951type keyUpdateMsg struct {
952	raw             []byte
953	updateRequested bool
954}
955
956func (m *keyUpdateMsg) marshal() []byte {
957	if m.raw != nil {
958		return m.raw
959	}
960
961	var b cryptobyte.Builder
962	b.AddUint8(typeKeyUpdate)
963	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
964		if m.updateRequested {
965			b.AddUint8(1)
966		} else {
967			b.AddUint8(0)
968		}
969	})
970
971	m.raw = b.BytesOrPanic()
972	return m.raw
973}
974
975func (m *keyUpdateMsg) unmarshal(data []byte) bool {
976	m.raw = data
977	s := cryptobyte.String(data)
978
979	var updateRequested uint8
980	if !s.Skip(4) || // message type and uint24 length field
981		!s.ReadUint8(&updateRequested) || !s.Empty() {
982		return false
983	}
984	switch updateRequested {
985	case 0:
986		m.updateRequested = false
987	case 1:
988		m.updateRequested = true
989	default:
990		return false
991	}
992	return true
993}
994
995type newSessionTicketMsgTLS13 struct {
996	raw          []byte
997	lifetime     uint32
998	ageAdd       uint32
999	nonce        []byte
1000	label        []byte
1001	maxEarlyData uint32
1002}
1003
1004func (m *newSessionTicketMsgTLS13) marshal() []byte {
1005	if m.raw != nil {
1006		return m.raw
1007	}
1008
1009	var b cryptobyte.Builder
1010	b.AddUint8(typeNewSessionTicket)
1011	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1012		b.AddUint32(m.lifetime)
1013		b.AddUint32(m.ageAdd)
1014		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
1015			b.AddBytes(m.nonce)
1016		})
1017		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1018			b.AddBytes(m.label)
1019		})
1020
1021		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1022			if m.maxEarlyData > 0 {
1023				b.AddUint16(extensionEarlyData)
1024				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1025					b.AddUint32(m.maxEarlyData)
1026				})
1027			}
1028		})
1029	})
1030
1031	m.raw = b.BytesOrPanic()
1032	return m.raw
1033}
1034
1035func (m *newSessionTicketMsgTLS13) unmarshal(data []byte) bool {
1036	*m = newSessionTicketMsgTLS13{raw: data}
1037	s := cryptobyte.String(data)
1038
1039	var extensions cryptobyte.String
1040	if !s.Skip(4) || // message type and uint24 length field
1041		!s.ReadUint32(&m.lifetime) ||
1042		!s.ReadUint32(&m.ageAdd) ||
1043		!readUint8LengthPrefixed(&s, &m.nonce) ||
1044		!readUint16LengthPrefixed(&s, &m.label) ||
1045		!s.ReadUint16LengthPrefixed(&extensions) ||
1046		!s.Empty() {
1047		return false
1048	}
1049
1050	for !extensions.Empty() {
1051		var extension uint16
1052		var extData cryptobyte.String
1053		if !extensions.ReadUint16(&extension) ||
1054			!extensions.ReadUint16LengthPrefixed(&extData) {
1055			return false
1056		}
1057
1058		switch extension {
1059		case extensionEarlyData:
1060			if !extData.ReadUint32(&m.maxEarlyData) {
1061				return false
1062			}
1063		default:
1064			// Ignore unknown extensions.
1065			continue
1066		}
1067
1068		if !extData.Empty() {
1069			return false
1070		}
1071	}
1072
1073	return true
1074}
1075
1076type certificateRequestMsgTLS13 struct {
1077	raw                              []byte
1078	ocspStapling                     bool
1079	scts                             bool
1080	supportedSignatureAlgorithms     []SignatureScheme
1081	supportedSignatureAlgorithmsCert []SignatureScheme
1082	certificateAuthorities           [][]byte
1083}
1084
1085func (m *certificateRequestMsgTLS13) marshal() []byte {
1086	if m.raw != nil {
1087		return m.raw
1088	}
1089
1090	var b cryptobyte.Builder
1091	b.AddUint8(typeCertificateRequest)
1092	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1093		// certificate_request_context (SHALL be zero length unless used for
1094		// post-handshake authentication)
1095		b.AddUint8(0)
1096
1097		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1098			if m.ocspStapling {
1099				b.AddUint16(extensionStatusRequest)
1100				b.AddUint16(0) // empty extension_data
1101			}
1102			if m.scts {
1103				// RFC 8446, Section 4.4.2.1 makes no mention of
1104				// signed_certificate_timestamp in CertificateRequest, but
1105				// "Extensions in the Certificate message from the client MUST
1106				// correspond to extensions in the CertificateRequest message
1107				// from the server." and it appears in the table in Section 4.2.
1108				b.AddUint16(extensionSCT)
1109				b.AddUint16(0) // empty extension_data
1110			}
1111			if len(m.supportedSignatureAlgorithms) > 0 {
1112				b.AddUint16(extensionSignatureAlgorithms)
1113				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1114					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1115						for _, sigAlgo := range m.supportedSignatureAlgorithms {
1116							b.AddUint16(uint16(sigAlgo))
1117						}
1118					})
1119				})
1120			}
1121			if len(m.supportedSignatureAlgorithmsCert) > 0 {
1122				b.AddUint16(extensionSignatureAlgorithmsCert)
1123				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1124					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1125						for _, sigAlgo := range m.supportedSignatureAlgorithmsCert {
1126							b.AddUint16(uint16(sigAlgo))
1127						}
1128					})
1129				})
1130			}
1131			if len(m.certificateAuthorities) > 0 {
1132				b.AddUint16(extensionCertificateAuthorities)
1133				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1134					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1135						for _, ca := range m.certificateAuthorities {
1136							b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1137								b.AddBytes(ca)
1138							})
1139						}
1140					})
1141				})
1142			}
1143		})
1144	})
1145
1146	m.raw = b.BytesOrPanic()
1147	return m.raw
1148}
1149
1150func (m *certificateRequestMsgTLS13) unmarshal(data []byte) bool {
1151	*m = certificateRequestMsgTLS13{raw: data}
1152	s := cryptobyte.String(data)
1153
1154	var context, extensions cryptobyte.String
1155	if !s.Skip(4) || // message type and uint24 length field
1156		!s.ReadUint8LengthPrefixed(&context) || !context.Empty() ||
1157		!s.ReadUint16LengthPrefixed(&extensions) ||
1158		!s.Empty() {
1159		return false
1160	}
1161
1162	for !extensions.Empty() {
1163		var extension uint16
1164		var extData cryptobyte.String
1165		if !extensions.ReadUint16(&extension) ||
1166			!extensions.ReadUint16LengthPrefixed(&extData) {
1167			return false
1168		}
1169
1170		switch extension {
1171		case extensionStatusRequest:
1172			m.ocspStapling = true
1173		case extensionSCT:
1174			m.scts = true
1175		case extensionSignatureAlgorithms:
1176			var sigAndAlgs cryptobyte.String
1177			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
1178				return false
1179			}
1180			for !sigAndAlgs.Empty() {
1181				var sigAndAlg uint16
1182				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
1183					return false
1184				}
1185				m.supportedSignatureAlgorithms = append(
1186					m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg))
1187			}
1188		case extensionSignatureAlgorithmsCert:
1189			var sigAndAlgs cryptobyte.String
1190			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
1191				return false
1192			}
1193			for !sigAndAlgs.Empty() {
1194				var sigAndAlg uint16
1195				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
1196					return false
1197				}
1198				m.supportedSignatureAlgorithmsCert = append(
1199					m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg))
1200			}
1201		case extensionCertificateAuthorities:
1202			var auths cryptobyte.String
1203			if !extData.ReadUint16LengthPrefixed(&auths) || auths.Empty() {
1204				return false
1205			}
1206			for !auths.Empty() {
1207				var ca []byte
1208				if !readUint16LengthPrefixed(&auths, &ca) || len(ca) == 0 {
1209					return false
1210				}
1211				m.certificateAuthorities = append(m.certificateAuthorities, ca)
1212			}
1213		default:
1214			// Ignore unknown extensions.
1215			continue
1216		}
1217
1218		if !extData.Empty() {
1219			return false
1220		}
1221	}
1222
1223	return true
1224}
1225
1226type certificateMsg struct {
1227	raw          []byte
1228	certificates [][]byte
1229}
1230
1231func (m *certificateMsg) marshal() (x []byte) {
1232	if m.raw != nil {
1233		return m.raw
1234	}
1235
1236	var i int
1237	for _, slice := range m.certificates {
1238		i += len(slice)
1239	}
1240
1241	length := 3 + 3*len(m.certificates) + i
1242	x = make([]byte, 4+length)
1243	x[0] = typeCertificate
1244	x[1] = uint8(length >> 16)
1245	x[2] = uint8(length >> 8)
1246	x[3] = uint8(length)
1247
1248	certificateOctets := length - 3
1249	x[4] = uint8(certificateOctets >> 16)
1250	x[5] = uint8(certificateOctets >> 8)
1251	x[6] = uint8(certificateOctets)
1252
1253	y := x[7:]
1254	for _, slice := range m.certificates {
1255		y[0] = uint8(len(slice) >> 16)
1256		y[1] = uint8(len(slice) >> 8)
1257		y[2] = uint8(len(slice))
1258		copy(y[3:], slice)
1259		y = y[3+len(slice):]
1260	}
1261
1262	m.raw = x
1263	return
1264}
1265
1266func (m *certificateMsg) unmarshal(data []byte) bool {
1267	if len(data) < 7 {
1268		return false
1269	}
1270
1271	m.raw = data
1272	certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6])
1273	if uint32(len(data)) != certsLen+7 {
1274		return false
1275	}
1276
1277	numCerts := 0
1278	d := data[7:]
1279	for certsLen > 0 {
1280		if len(d) < 4 {
1281			return false
1282		}
1283		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
1284		if uint32(len(d)) < 3+certLen {
1285			return false
1286		}
1287		d = d[3+certLen:]
1288		certsLen -= 3 + certLen
1289		numCerts++
1290	}
1291
1292	m.certificates = make([][]byte, numCerts)
1293	d = data[7:]
1294	for i := 0; i < numCerts; i++ {
1295		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
1296		m.certificates[i] = d[3 : 3+certLen]
1297		d = d[3+certLen:]
1298	}
1299
1300	return true
1301}
1302
1303type certificateMsgTLS13 struct {
1304	raw          []byte
1305	certificate  Certificate
1306	ocspStapling bool
1307	scts         bool
1308}
1309
1310func (m *certificateMsgTLS13) marshal() []byte {
1311	if m.raw != nil {
1312		return m.raw
1313	}
1314
1315	var b cryptobyte.Builder
1316	b.AddUint8(typeCertificate)
1317	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1318		b.AddUint8(0) // certificate_request_context
1319
1320		certificate := m.certificate
1321		if !m.ocspStapling {
1322			certificate.OCSPStaple = nil
1323		}
1324		if !m.scts {
1325			certificate.SignedCertificateTimestamps = nil
1326		}
1327		marshalCertificate(b, certificate)
1328	})
1329
1330	m.raw = b.BytesOrPanic()
1331	return m.raw
1332}
1333
1334func marshalCertificate(b *cryptobyte.Builder, certificate Certificate) {
1335	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1336		for i, cert := range certificate.Certificate {
1337			b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1338				b.AddBytes(cert)
1339			})
1340			b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1341				if i > 0 {
1342					// This library only supports OCSP and SCT for leaf certificates.
1343					return
1344				}
1345				if certificate.OCSPStaple != nil {
1346					b.AddUint16(extensionStatusRequest)
1347					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1348						b.AddUint8(statusTypeOCSP)
1349						b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1350							b.AddBytes(certificate.OCSPStaple)
1351						})
1352					})
1353				}
1354				if certificate.SignedCertificateTimestamps != nil {
1355					b.AddUint16(extensionSCT)
1356					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1357						b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1358							for _, sct := range certificate.SignedCertificateTimestamps {
1359								b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1360									b.AddBytes(sct)
1361								})
1362							}
1363						})
1364					})
1365				}
1366			})
1367		}
1368	})
1369}
1370
1371func (m *certificateMsgTLS13) unmarshal(data []byte) bool {
1372	*m = certificateMsgTLS13{raw: data}
1373	s := cryptobyte.String(data)
1374
1375	var context cryptobyte.String
1376	if !s.Skip(4) || // message type and uint24 length field
1377		!s.ReadUint8LengthPrefixed(&context) || !context.Empty() ||
1378		!unmarshalCertificate(&s, &m.certificate) ||
1379		!s.Empty() {
1380		return false
1381	}
1382
1383	m.scts = m.certificate.SignedCertificateTimestamps != nil
1384	m.ocspStapling = m.certificate.OCSPStaple != nil
1385
1386	return true
1387}
1388
1389func unmarshalCertificate(s *cryptobyte.String, certificate *Certificate) bool {
1390	var certList cryptobyte.String
1391	if !s.ReadUint24LengthPrefixed(&certList) {
1392		return false
1393	}
1394	for !certList.Empty() {
1395		var cert []byte
1396		var extensions cryptobyte.String
1397		if !readUint24LengthPrefixed(&certList, &cert) ||
1398			!certList.ReadUint16LengthPrefixed(&extensions) {
1399			return false
1400		}
1401		certificate.Certificate = append(certificate.Certificate, cert)
1402		for !extensions.Empty() {
1403			var extension uint16
1404			var extData cryptobyte.String
1405			if !extensions.ReadUint16(&extension) ||
1406				!extensions.ReadUint16LengthPrefixed(&extData) {
1407				return false
1408			}
1409			if len(certificate.Certificate) > 1 {
1410				// This library only supports OCSP and SCT for leaf certificates.
1411				continue
1412			}
1413
1414			switch extension {
1415			case extensionStatusRequest:
1416				var statusType uint8
1417				if !extData.ReadUint8(&statusType) || statusType != statusTypeOCSP ||
1418					!readUint24LengthPrefixed(&extData, &certificate.OCSPStaple) ||
1419					len(certificate.OCSPStaple) == 0 {
1420					return false
1421				}
1422			case extensionSCT:
1423				var sctList cryptobyte.String
1424				if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() {
1425					return false
1426				}
1427				for !sctList.Empty() {
1428					var sct []byte
1429					if !readUint16LengthPrefixed(&sctList, &sct) ||
1430						len(sct) == 0 {
1431						return false
1432					}
1433					certificate.SignedCertificateTimestamps = append(
1434						certificate.SignedCertificateTimestamps, sct)
1435				}
1436			default:
1437				// Ignore unknown extensions.
1438				continue
1439			}
1440
1441			if !extData.Empty() {
1442				return false
1443			}
1444		}
1445	}
1446	return true
1447}
1448
1449type serverKeyExchangeMsg struct {
1450	raw []byte
1451	key []byte
1452}
1453
1454func (m *serverKeyExchangeMsg) marshal() []byte {
1455	if m.raw != nil {
1456		return m.raw
1457	}
1458	length := len(m.key)
1459	x := make([]byte, length+4)
1460	x[0] = typeServerKeyExchange
1461	x[1] = uint8(length >> 16)
1462	x[2] = uint8(length >> 8)
1463	x[3] = uint8(length)
1464	copy(x[4:], m.key)
1465
1466	m.raw = x
1467	return x
1468}
1469
1470func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool {
1471	m.raw = data
1472	if len(data) < 4 {
1473		return false
1474	}
1475	m.key = data[4:]
1476	return true
1477}
1478
1479type certificateStatusMsg struct {
1480	raw      []byte
1481	response []byte
1482}
1483
1484func (m *certificateStatusMsg) marshal() []byte {
1485	if m.raw != nil {
1486		return m.raw
1487	}
1488
1489	var b cryptobyte.Builder
1490	b.AddUint8(typeCertificateStatus)
1491	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1492		b.AddUint8(statusTypeOCSP)
1493		b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1494			b.AddBytes(m.response)
1495		})
1496	})
1497
1498	m.raw = b.BytesOrPanic()
1499	return m.raw
1500}
1501
1502func (m *certificateStatusMsg) unmarshal(data []byte) bool {
1503	m.raw = data
1504	s := cryptobyte.String(data)
1505
1506	var statusType uint8
1507	if !s.Skip(4) || // message type and uint24 length field
1508		!s.ReadUint8(&statusType) || statusType != statusTypeOCSP ||
1509		!readUint24LengthPrefixed(&s, &m.response) ||
1510		len(m.response) == 0 || !s.Empty() {
1511		return false
1512	}
1513	return true
1514}
1515
1516type serverHelloDoneMsg struct{}
1517
1518func (m *serverHelloDoneMsg) marshal() []byte {
1519	x := make([]byte, 4)
1520	x[0] = typeServerHelloDone
1521	return x
1522}
1523
1524func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
1525	return len(data) == 4
1526}
1527
1528type clientKeyExchangeMsg struct {
1529	raw        []byte
1530	ciphertext []byte
1531}
1532
1533func (m *clientKeyExchangeMsg) marshal() []byte {
1534	if m.raw != nil {
1535		return m.raw
1536	}
1537	length := len(m.ciphertext)
1538	x := make([]byte, length+4)
1539	x[0] = typeClientKeyExchange
1540	x[1] = uint8(length >> 16)
1541	x[2] = uint8(length >> 8)
1542	x[3] = uint8(length)
1543	copy(x[4:], m.ciphertext)
1544
1545	m.raw = x
1546	return x
1547}
1548
1549func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool {
1550	m.raw = data
1551	if len(data) < 4 {
1552		return false
1553	}
1554	l := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
1555	if l != len(data)-4 {
1556		return false
1557	}
1558	m.ciphertext = data[4:]
1559	return true
1560}
1561
1562type finishedMsg struct {
1563	raw        []byte
1564	verifyData []byte
1565}
1566
1567func (m *finishedMsg) marshal() []byte {
1568	if m.raw != nil {
1569		return m.raw
1570	}
1571
1572	var b cryptobyte.Builder
1573	b.AddUint8(typeFinished)
1574	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1575		b.AddBytes(m.verifyData)
1576	})
1577
1578	m.raw = b.BytesOrPanic()
1579	return m.raw
1580}
1581
1582func (m *finishedMsg) unmarshal(data []byte) bool {
1583	m.raw = data
1584	s := cryptobyte.String(data)
1585	return s.Skip(1) &&
1586		readUint24LengthPrefixed(&s, &m.verifyData) &&
1587		s.Empty()
1588}
1589
1590type certificateRequestMsg struct {
1591	raw []byte
1592	// hasSignatureAlgorithm indicates whether this message includes a list of
1593	// supported signature algorithms. This change was introduced with TLS 1.2.
1594	hasSignatureAlgorithm bool
1595
1596	certificateTypes             []byte
1597	supportedSignatureAlgorithms []SignatureScheme
1598	certificateAuthorities       [][]byte
1599}
1600
1601func (m *certificateRequestMsg) marshal() (x []byte) {
1602	if m.raw != nil {
1603		return m.raw
1604	}
1605
1606	// See RFC 4346, Section 7.4.4.
1607	length := 1 + len(m.certificateTypes) + 2
1608	casLength := 0
1609	for _, ca := range m.certificateAuthorities {
1610		casLength += 2 + len(ca)
1611	}
1612	length += casLength
1613
1614	if m.hasSignatureAlgorithm {
1615		length += 2 + 2*len(m.supportedSignatureAlgorithms)
1616	}
1617
1618	x = make([]byte, 4+length)
1619	x[0] = typeCertificateRequest
1620	x[1] = uint8(length >> 16)
1621	x[2] = uint8(length >> 8)
1622	x[3] = uint8(length)
1623
1624	x[4] = uint8(len(m.certificateTypes))
1625
1626	copy(x[5:], m.certificateTypes)
1627	y := x[5+len(m.certificateTypes):]
1628
1629	if m.hasSignatureAlgorithm {
1630		n := len(m.supportedSignatureAlgorithms) * 2
1631		y[0] = uint8(n >> 8)
1632		y[1] = uint8(n)
1633		y = y[2:]
1634		for _, sigAlgo := range m.supportedSignatureAlgorithms {
1635			y[0] = uint8(sigAlgo >> 8)
1636			y[1] = uint8(sigAlgo)
1637			y = y[2:]
1638		}
1639	}
1640
1641	y[0] = uint8(casLength >> 8)
1642	y[1] = uint8(casLength)
1643	y = y[2:]
1644	for _, ca := range m.certificateAuthorities {
1645		y[0] = uint8(len(ca) >> 8)
1646		y[1] = uint8(len(ca))
1647		y = y[2:]
1648		copy(y, ca)
1649		y = y[len(ca):]
1650	}
1651
1652	m.raw = x
1653	return
1654}
1655
1656func (m *certificateRequestMsg) unmarshal(data []byte) bool {
1657	m.raw = data
1658
1659	if len(data) < 5 {
1660		return false
1661	}
1662
1663	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
1664	if uint32(len(data))-4 != length {
1665		return false
1666	}
1667
1668	numCertTypes := int(data[4])
1669	data = data[5:]
1670	if numCertTypes == 0 || len(data) <= numCertTypes {
1671		return false
1672	}
1673
1674	m.certificateTypes = make([]byte, numCertTypes)
1675	if copy(m.certificateTypes, data) != numCertTypes {
1676		return false
1677	}
1678
1679	data = data[numCertTypes:]
1680
1681	if m.hasSignatureAlgorithm {
1682		if len(data) < 2 {
1683			return false
1684		}
1685		sigAndHashLen := uint16(data[0])<<8 | uint16(data[1])
1686		data = data[2:]
1687		if sigAndHashLen&1 != 0 {
1688			return false
1689		}
1690		if len(data) < int(sigAndHashLen) {
1691			return false
1692		}
1693		numSigAlgos := sigAndHashLen / 2
1694		m.supportedSignatureAlgorithms = make([]SignatureScheme, numSigAlgos)
1695		for i := range m.supportedSignatureAlgorithms {
1696			m.supportedSignatureAlgorithms[i] = SignatureScheme(data[0])<<8 | SignatureScheme(data[1])
1697			data = data[2:]
1698		}
1699	}
1700
1701	if len(data) < 2 {
1702		return false
1703	}
1704	casLength := uint16(data[0])<<8 | uint16(data[1])
1705	data = data[2:]
1706	if len(data) < int(casLength) {
1707		return false
1708	}
1709	cas := make([]byte, casLength)
1710	copy(cas, data)
1711	data = data[casLength:]
1712
1713	m.certificateAuthorities = nil
1714	for len(cas) > 0 {
1715		if len(cas) < 2 {
1716			return false
1717		}
1718		caLen := uint16(cas[0])<<8 | uint16(cas[1])
1719		cas = cas[2:]
1720
1721		if len(cas) < int(caLen) {
1722			return false
1723		}
1724
1725		m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen])
1726		cas = cas[caLen:]
1727	}
1728
1729	return len(data) == 0
1730}
1731
1732type certificateVerifyMsg struct {
1733	raw                   []byte
1734	hasSignatureAlgorithm bool // format change introduced in TLS 1.2
1735	signatureAlgorithm    SignatureScheme
1736	signature             []byte
1737}
1738
1739func (m *certificateVerifyMsg) marshal() (x []byte) {
1740	if m.raw != nil {
1741		return m.raw
1742	}
1743
1744	var b cryptobyte.Builder
1745	b.AddUint8(typeCertificateVerify)
1746	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
1747		if m.hasSignatureAlgorithm {
1748			b.AddUint16(uint16(m.signatureAlgorithm))
1749		}
1750		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
1751			b.AddBytes(m.signature)
1752		})
1753	})
1754
1755	m.raw = b.BytesOrPanic()
1756	return m.raw
1757}
1758
1759func (m *certificateVerifyMsg) unmarshal(data []byte) bool {
1760	m.raw = data
1761	s := cryptobyte.String(data)
1762
1763	if !s.Skip(4) { // message type and uint24 length field
1764		return false
1765	}
1766	if m.hasSignatureAlgorithm {
1767		if !s.ReadUint16((*uint16)(&m.signatureAlgorithm)) {
1768			return false
1769		}
1770	}
1771	return readUint16LengthPrefixed(&s, &m.signature) && s.Empty()
1772}
1773
1774type newSessionTicketMsg struct {
1775	raw    []byte
1776	ticket []byte
1777}
1778
1779func (m *newSessionTicketMsg) marshal() (x []byte) {
1780	if m.raw != nil {
1781		return m.raw
1782	}
1783
1784	// See RFC 5077, Section 3.3.
1785	ticketLen := len(m.ticket)
1786	length := 2 + 4 + ticketLen
1787	x = make([]byte, 4+length)
1788	x[0] = typeNewSessionTicket
1789	x[1] = uint8(length >> 16)
1790	x[2] = uint8(length >> 8)
1791	x[3] = uint8(length)
1792	x[8] = uint8(ticketLen >> 8)
1793	x[9] = uint8(ticketLen)
1794	copy(x[10:], m.ticket)
1795
1796	m.raw = x
1797
1798	return
1799}
1800
1801func (m *newSessionTicketMsg) unmarshal(data []byte) bool {
1802	m.raw = data
1803
1804	if len(data) < 10 {
1805		return false
1806	}
1807
1808	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
1809	if uint32(len(data))-4 != length {
1810		return false
1811	}
1812
1813	ticketLen := int(data[8])<<8 + int(data[9])
1814	if len(data)-10 != ticketLen {
1815		return false
1816	}
1817
1818	m.ticket = data[10:]
1819
1820	return true
1821}
1822
1823type helloRequestMsg struct {
1824}
1825
1826func (*helloRequestMsg) marshal() []byte {
1827	return []byte{typeHelloRequest, 0, 0, 0}
1828}
1829
1830func (*helloRequestMsg) unmarshal(data []byte) bool {
1831	return len(data) == 4
1832}
1833