handshake_messages.go 43 KB
Newer Older
Adam Langley's avatar
Adam Langley committed
1
2
3
4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5
package runner
Adam Langley's avatar
Adam Langley committed
6
7
8

import "bytes"

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
func writeLen(buf []byte, v, size int) {
	for i := 0; i < size; i++ {
		buf[size-i-1] = byte(v)
		v >>= 8
	}
	if v != 0 {
		panic("length is too long")
	}
}

type byteBuilder struct {
	buf       *[]byte
	start     int
	prefixLen int
	child     *byteBuilder
}

func newByteBuilder() *byteBuilder {
	buf := make([]byte, 0, 32)
	return &byteBuilder{buf: &buf}
}

func (bb *byteBuilder) len() int {
	return len(*bb.buf) - bb.start - bb.prefixLen
}

func (bb *byteBuilder) flush() {
	if bb.child == nil {
		return
	}
	bb.child.flush()
	writeLen((*bb.buf)[bb.child.start:], bb.child.len(), bb.child.prefixLen)
	bb.child = nil
	return
}

func (bb *byteBuilder) finish() []byte {
	bb.flush()
	return *bb.buf
}

func (bb *byteBuilder) addU8(u uint8) {
	bb.flush()
	*bb.buf = append(*bb.buf, u)
}

func (bb *byteBuilder) addU16(u uint16) {
	bb.flush()
	*bb.buf = append(*bb.buf, byte(u>>8), byte(u))
}

func (bb *byteBuilder) addU24(u int) {
	bb.flush()
	*bb.buf = append(*bb.buf, byte(u>>16), byte(u>>8), byte(u))
}

func (bb *byteBuilder) addU32(u uint32) {
	bb.flush()
	*bb.buf = append(*bb.buf, byte(u>>24), byte(u>>16), byte(u>>8), byte(u))
}

func (bb *byteBuilder) addU8LengthPrefixed() *byteBuilder {
	return bb.createChild(1)
}

func (bb *byteBuilder) addU16LengthPrefixed() *byteBuilder {
	return bb.createChild(2)
}

func (bb *byteBuilder) addU24LengthPrefixed() *byteBuilder {
	return bb.createChild(3)
}

func (bb *byteBuilder) addBytes(b []byte) {
	bb.flush()
	*bb.buf = append(*bb.buf, b...)
}

func (bb *byteBuilder) createChild(lengthPrefixSize int) *byteBuilder {
	bb.flush()
	bb.child = &byteBuilder{
		buf:       bb.buf,
		start:     len(*bb.buf),
		prefixLen: lengthPrefixSize,
	}
	for i := 0; i < lengthPrefixSize; i++ {
		*bb.buf = append(*bb.buf, 0)
	}
	return bb.child
}

func (bb *byteBuilder) discardChild() {
	if bb.child != nil {
		return
	}
	bb.child = nil
	*bb.buf = (*bb.buf)[:bb.start]
}

108
109
110
111
112
type keyShareEntry struct {
	group       CurveID
	keyExchange []byte
}

Adam Langley's avatar
Adam Langley committed
113
type clientHelloMsg struct {
114
115
116
117
118
119
120
	raw       []byte
	isDTLS    bool
	vers      uint16
	random    []byte
	sessionId []byte
	// TODO(davidben): Add support for TLS 1.3 cookies which are larger and
	// use an extension.
David Benjamin's avatar
David Benjamin committed
121
122
123
124
125
126
127
128
	cookie                  []byte
	cipherSuites            []uint16
	compressionMethods      []uint8
	nextProtoNeg            bool
	serverName              string
	ocspStapling            bool
	supportedCurves         []CurveID
	supportedPoints         []uint8
129
130
131
132
	keyShares               []keyShareEntry
	pskIdentities           [][]uint8
	hasEarlyData            bool
	earlyDataContext        []byte
David Benjamin's avatar
David Benjamin committed
133
134
	ticketSupported         bool
	sessionTicket           []uint8
135
	signatureAlgorithms     []signatureAlgorithm
David Benjamin's avatar
David Benjamin committed
136
137
138
139
140
141
142
143
	secureRenegotiation     []byte
	alpnProtocols           []string
	duplicateExtension      bool
	channelIDSupported      bool
	npnLast                 bool
	extendedMasterSecret    bool
	srtpProtectionProfiles  []uint16
	srtpMasterKeyIdentifier string
144
	sctListSupported        bool
Adam Langley's avatar
Adam Langley committed
145
	customExtension         string
Adam Langley's avatar
Adam Langley committed
146
147
148
149
150
151
152
153
154
}

func (m *clientHelloMsg) equal(i interface{}) bool {
	m1, ok := i.(*clientHelloMsg)
	if !ok {
		return false
	}

	return bytes.Equal(m.raw, m1.raw) &&
155
		m.isDTLS == m1.isDTLS &&
Adam Langley's avatar
Adam Langley committed
156
157
158
		m.vers == m1.vers &&
		bytes.Equal(m.random, m1.random) &&
		bytes.Equal(m.sessionId, m1.sessionId) &&
159
		bytes.Equal(m.cookie, m1.cookie) &&
Adam Langley's avatar
Adam Langley committed
160
161
162
163
164
165
166
		eqUint16s(m.cipherSuites, m1.cipherSuites) &&
		bytes.Equal(m.compressionMethods, m1.compressionMethods) &&
		m.nextProtoNeg == m1.nextProtoNeg &&
		m.serverName == m1.serverName &&
		m.ocspStapling == m1.ocspStapling &&
		eqCurveIDs(m.supportedCurves, m1.supportedCurves) &&
		bytes.Equal(m.supportedPoints, m1.supportedPoints) &&
167
168
169
170
		eqKeyShareEntryLists(m.keyShares, m1.keyShares) &&
		eqByteSlices(m.pskIdentities, m1.pskIdentities) &&
		m.hasEarlyData == m1.hasEarlyData &&
		bytes.Equal(m.earlyDataContext, m1.earlyDataContext) &&
Adam Langley's avatar
Adam Langley committed
171
172
		m.ticketSupported == m1.ticketSupported &&
		bytes.Equal(m.sessionTicket, m1.sessionTicket) &&
173
		eqSignatureAlgorithms(m.signatureAlgorithms, m1.signatureAlgorithms) &&
Adam Langley's avatar
Adam Langley committed
174
175
		bytes.Equal(m.secureRenegotiation, m1.secureRenegotiation) &&
		(m.secureRenegotiation == nil) == (m1.secureRenegotiation == nil) &&
David Benjamin's avatar
David Benjamin committed
176
		eqStrings(m.alpnProtocols, m1.alpnProtocols) &&
177
		m.duplicateExtension == m1.duplicateExtension &&
178
		m.channelIDSupported == m1.channelIDSupported &&
Adam Langley's avatar
Adam Langley committed
179
		m.npnLast == m1.npnLast &&
David Benjamin's avatar
David Benjamin committed
180
181
		m.extendedMasterSecret == m1.extendedMasterSecret &&
		eqUint16s(m.srtpProtectionProfiles, m1.srtpProtectionProfiles) &&
182
		m.srtpMasterKeyIdentifier == m1.srtpMasterKeyIdentifier &&
Adam Langley's avatar
Adam Langley committed
183
184
		m.sctListSupported == m1.sctListSupported &&
		m.customExtension == m1.customExtension
Adam Langley's avatar
Adam Langley committed
185
186
187
188
189
190
191
}

func (m *clientHelloMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}

192
193
194
	handshakeMsg := newByteBuilder()
	handshakeMsg.addU8(typeClientHello)
	hello := handshakeMsg.addU24LengthPrefixed()
195
	vers := versionToWire(m.vers, m.isDTLS)
196
197
198
199
	hello.addU16(vers)
	hello.addBytes(m.random)
	sessionId := hello.addU8LengthPrefixed()
	sessionId.addBytes(m.sessionId)
200
	if m.isDTLS {
201
202
		cookie := hello.addU8LengthPrefixed()
		cookie.addBytes(m.cookie)
Adam Langley's avatar
Adam Langley committed
203
	}
204
205
206
	cipherSuites := hello.addU16LengthPrefixed()
	for _, suite := range m.cipherSuites {
		cipherSuites.addU16(suite)
Adam Langley's avatar
Adam Langley committed
207
	}
208
209
210
211
	compressionMethods := hello.addU8LengthPrefixed()
	compressionMethods.addBytes(m.compressionMethods)

	extensions := hello.addU16LengthPrefixed()
212
213
	if m.duplicateExtension {
		// Add a duplicate bogus extension at the beginning and end.
214
215
		extensions.addU16(0xffff)
		extensions.addU16(0) // 0-length for empty extension
216
	}
217
	if m.nextProtoNeg && !m.npnLast {
218
219
		extensions.addU16(extensionNextProtoNeg)
		extensions.addU16(0) // The length is always 0
Adam Langley's avatar
Adam Langley committed
220
221
	}
	if len(m.serverName) > 0 {
222
223
		extensions.addU16(extensionServerName)
		serverNameList := extensions.addU16LengthPrefixed()
Adam Langley's avatar
Adam Langley committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243

		// RFC 3546, section 3.1
		//
		// struct {
		//     NameType name_type;
		//     select (name_type) {
		//         case host_name: HostName;
		//     } name;
		// } ServerName;
		//
		// enum {
		//     host_name(0), (255)
		// } NameType;
		//
		// opaque HostName<1..2^16-1>;
		//
		// struct {
		//     ServerName server_name_list<1..2^16-1>
		// } ServerNameList;

244
245
246
247
		serverName := serverNameList.addU16LengthPrefixed()
		serverName.addU8(0) // NameType host_name(0)
		hostName := serverName.addU16LengthPrefixed()
		hostName.addBytes([]byte(m.serverName))
Adam Langley's avatar
Adam Langley committed
248
249
	}
	if m.ocspStapling {
250
251
252
		extensions.addU16(extensionStatusRequest)
		certificateStatusRequest := extensions.addU16LengthPrefixed()

Adam Langley's avatar
Adam Langley committed
253
		// RFC 4366, section 3.6
254
		certificateStatusRequest.addU8(1) // OCSP type
Adam Langley's avatar
Adam Langley committed
255
		// Two zero valued uint16s for the two lengths.
256
257
		certificateStatusRequest.addU16(0) // ResponderID length
		certificateStatusRequest.addU16(0) // Extensions length
Adam Langley's avatar
Adam Langley committed
258
259
	}
	if len(m.supportedCurves) > 0 {
260
261
262
263
		// http://tools.ietf.org/html/rfc4492#section-5.1.1
		extensions.addU16(extensionSupportedCurves)
		supportedCurvesList := extensions.addU16LengthPrefixed()
		supportedCurves := supportedCurvesList.addU16LengthPrefixed()
Adam Langley's avatar
Adam Langley committed
264
		for _, curve := range m.supportedCurves {
265
			supportedCurves.addU16(uint16(curve))
Adam Langley's avatar
Adam Langley committed
266
267
268
		}
	}
	if len(m.supportedPoints) > 0 {
269
270
271
272
		// http://tools.ietf.org/html/rfc4492#section-5.1.2
		extensions.addU16(extensionSupportedPoints)
		supportedPointsList := extensions.addU16LengthPrefixed()
		supportedPoints := supportedPointsList.addU8LengthPrefixed()
Adam Langley's avatar
Adam Langley committed
273
		for _, pointFormat := range m.supportedPoints {
274
			supportedPoints.addU8(pointFormat)
Adam Langley's avatar
Adam Langley committed
275
276
		}
	}
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
	if len(m.keyShares) > 0 {
		extensions.addU16(extensionKeyShare)
		keyShareList := extensions.addU16LengthPrefixed()

		keyShares := keyShareList.addU16LengthPrefixed()
		for _, keyShare := range m.keyShares {
			keyShares.addU16(uint16(keyShare.group))
			keyExchange := keyShares.addU16LengthPrefixed()
			keyExchange.addBytes(keyShare.keyExchange)
		}
	}
	if len(m.pskIdentities) > 0 {
		extensions.addU16(extensionPreSharedKey)
		pskExtension := extensions.addU16LengthPrefixed()

		pskIdentities := pskExtension.addU16LengthPrefixed()
		for _, psk := range m.pskIdentities {
			pskIdentity := pskIdentities.addU16LengthPrefixed()
			pskIdentity.addBytes(psk)
		}
	}
	if m.hasEarlyData {
		extensions.addU16(extensionEarlyData)
		earlyDataIndication := extensions.addU16LengthPrefixed()

		context := earlyDataIndication.addU8LengthPrefixed()
		context.addBytes(m.earlyDataContext)
	}
Adam Langley's avatar
Adam Langley committed
305
306
	if m.ticketSupported {
		// http://tools.ietf.org/html/rfc5077#section-3.2
307
308
309
		extensions.addU16(extensionSessionTicket)
		sessionTicketExtension := extensions.addU16LengthPrefixed()
		sessionTicketExtension.addBytes(m.sessionTicket)
Adam Langley's avatar
Adam Langley committed
310
	}
311
	if len(m.signatureAlgorithms) > 0 {
Adam Langley's avatar
Adam Langley committed
312
		// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
313
314
315
		extensions.addU16(extensionSignatureAlgorithms)
		signatureAlgorithmsExtension := extensions.addU16LengthPrefixed()
		signatureAlgorithms := signatureAlgorithmsExtension.addU16LengthPrefixed()
316
		for _, sigAlg := range m.signatureAlgorithms {
317
			signatureAlgorithms.addU16(uint16(sigAlg))
Adam Langley's avatar
Adam Langley committed
318
319
		}
	}
Adam Langley's avatar
Adam Langley committed
320
	if m.secureRenegotiation != nil {
321
322
323
324
		extensions.addU16(extensionRenegotiationInfo)
		secureRenegoExt := extensions.addU16LengthPrefixed()
		secureRenego := secureRenegoExt.addU8LengthPrefixed()
		secureRenego.addBytes(m.secureRenegotiation)
Adam Langley's avatar
Adam Langley committed
325
	}
David Benjamin's avatar
David Benjamin committed
326
	if len(m.alpnProtocols) > 0 {
327
328
329
		// https://tools.ietf.org/html/rfc7301#section-3.1
		extensions.addU16(extensionALPN)
		alpnExtension := extensions.addU16LengthPrefixed()
David Benjamin's avatar
David Benjamin committed
330

331
		protocolNameList := alpnExtension.addU16LengthPrefixed()
David Benjamin's avatar
David Benjamin committed
332
		for _, s := range m.alpnProtocols {
333
334
			protocolName := protocolNameList.addU8LengthPrefixed()
			protocolName.addBytes([]byte(s))
David Benjamin's avatar
David Benjamin committed
335
336
		}
	}
337
	if m.channelIDSupported {
338
339
		extensions.addU16(extensionChannelID)
		extensions.addU16(0) // Length is always 0
340
	}
341
	if m.nextProtoNeg && m.npnLast {
342
343
		extensions.addU16(extensionNextProtoNeg)
		extensions.addU16(0) // Length is always 0
344
	}
345
346
	if m.duplicateExtension {
		// Add a duplicate bogus extension at the beginning and end.
347
348
		extensions.addU16(0xffff)
		extensions.addU16(0)
349
	}
Adam Langley's avatar
Adam Langley committed
350
	if m.extendedMasterSecret {
351
		// https://tools.ietf.org/html/rfc7627
352
353
		extensions.addU16(extensionExtendedMasterSecret)
		extensions.addU16(0) // Length is always 0
Adam Langley's avatar
Adam Langley committed
354
	}
David Benjamin's avatar
David Benjamin committed
355
	if len(m.srtpProtectionProfiles) > 0 {
356
357
358
359
360
		// https://tools.ietf.org/html/rfc5764#section-4.1.1
		extensions.addU16(extensionUseSRTP)
		useSrtpExt := extensions.addU16LengthPrefixed()

		srtpProtectionProfiles := useSrtpExt.addU16LengthPrefixed()
David Benjamin's avatar
David Benjamin committed
361
		for _, p := range m.srtpProtectionProfiles {
362
363
364
365
366
			// An SRTPProtectionProfile is defined as uint8[2],
			// not uint16. For some reason, we're storing it
			// as a uint16.
			srtpProtectionProfiles.addU8(byte(p >> 8))
			srtpProtectionProfiles.addU8(byte(p))
David Benjamin's avatar
David Benjamin committed
367
		}
368
369
		srtpMki := useSrtpExt.addU8LengthPrefixed()
		srtpMki.addBytes([]byte(m.srtpMasterKeyIdentifier))
David Benjamin's avatar
David Benjamin committed
370
	}
371
	if m.sctListSupported {
372
373
		extensions.addU16(extensionSignedCertificateTimestamp)
		extensions.addU16(0) // Length is always 0
374
	}
Adam Langley's avatar
Adam Langley committed
375
	if l := len(m.customExtension); l > 0 {
376
377
378
		extensions.addU16(extensionCustom)
		customExt := extensions.addU16LengthPrefixed()
		customExt.addBytes([]byte(m.customExtension))
Adam Langley's avatar
Adam Langley committed
379
	}
Adam Langley's avatar
Adam Langley committed
380

381
382
383
	if extensions.len() == 0 {
		hello.discardChild()
	}
Adam Langley's avatar
Adam Langley committed
384

385
386
	m.raw = handshakeMsg.finish()
	return m.raw
Adam Langley's avatar
Adam Langley committed
387
388
389
390
391
392
393
}

func (m *clientHelloMsg) unmarshal(data []byte) bool {
	if len(data) < 42 {
		return false
	}
	m.raw = data
394
	m.vers = wireToVersion(uint16(data[4])<<8|uint16(data[5]), m.isDTLS)
Adam Langley's avatar
Adam Langley committed
395
396
397
398
399
400
401
	m.random = data[6:38]
	sessionIdLen := int(data[38])
	if sessionIdLen > 32 || len(data) < 39+sessionIdLen {
		return false
	}
	m.sessionId = data[39 : 39+sessionIdLen]
	data = data[39+sessionIdLen:]
402
403
404
405
406
407
408
409
410
411
412
	if m.isDTLS {
		if len(data) < 1 {
			return false
		}
		cookieLen := int(data[0])
		if cookieLen > 32 || len(data) < 1+cookieLen {
			return false
		}
		m.cookie = data[1 : 1+cookieLen]
		data = data[1+cookieLen:]
	}
Adam Langley's avatar
Adam Langley committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
	if len(data) < 2 {
		return false
	}
	// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
	// they are uint16s, the number must be even.
	cipherSuiteLen := int(data[0])<<8 | int(data[1])
	if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
		return false
	}
	numCipherSuites := cipherSuiteLen / 2
	m.cipherSuites = make([]uint16, numCipherSuites)
	for i := 0; i < numCipherSuites; i++ {
		m.cipherSuites[i] = uint16(data[2+2*i])<<8 | uint16(data[3+2*i])
		if m.cipherSuites[i] == scsvRenegotiation {
Adam Langley's avatar
Adam Langley committed
427
			m.secureRenegotiation = []byte{}
Adam Langley's avatar
Adam Langley committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
		}
	}
	data = data[2+cipherSuiteLen:]
	if len(data) < 1 {
		return false
	}
	compressionMethodsLen := int(data[0])
	if len(data) < 1+compressionMethodsLen {
		return false
	}
	m.compressionMethods = data[1 : 1+compressionMethodsLen]

	data = data[1+compressionMethodsLen:]

	m.nextProtoNeg = false
	m.serverName = ""
	m.ocspStapling = false
445
446
447
448
	m.keyShares = nil
	m.pskIdentities = nil
	m.hasEarlyData = false
	m.earlyDataContext = nil
Adam Langley's avatar
Adam Langley committed
449
450
	m.ticketSupported = false
	m.sessionTicket = nil
451
	m.signatureAlgorithms = nil
David Benjamin's avatar
David Benjamin committed
452
	m.alpnProtocols = nil
Adam Langley's avatar
Adam Langley committed
453
	m.extendedMasterSecret = false
Adam Langley's avatar
Adam Langley committed
454
	m.customExtension = ""
Adam Langley's avatar
Adam Langley committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541

	if len(data) == 0 {
		// ClientHello is optionally followed by extension data
		return true
	}
	if len(data) < 2 {
		return false
	}

	extensionsLength := int(data[0])<<8 | int(data[1])
	data = data[2:]
	if extensionsLength != len(data) {
		return false
	}

	for len(data) != 0 {
		if len(data) < 4 {
			return false
		}
		extension := uint16(data[0])<<8 | uint16(data[1])
		length := int(data[2])<<8 | int(data[3])
		data = data[4:]
		if len(data) < length {
			return false
		}

		switch extension {
		case extensionServerName:
			if length < 2 {
				return false
			}
			numNames := int(data[0])<<8 | int(data[1])
			d := data[2:]
			for i := 0; i < numNames; i++ {
				if len(d) < 3 {
					return false
				}
				nameType := d[0]
				nameLen := int(d[1])<<8 | int(d[2])
				d = d[3:]
				if len(d) < nameLen {
					return false
				}
				if nameType == 0 {
					m.serverName = string(d[0:nameLen])
					break
				}
				d = d[nameLen:]
			}
		case extensionNextProtoNeg:
			if length > 0 {
				return false
			}
			m.nextProtoNeg = true
		case extensionStatusRequest:
			m.ocspStapling = length > 0 && data[0] == statusTypeOCSP
		case extensionSupportedCurves:
			// http://tools.ietf.org/html/rfc4492#section-5.5.1
			if length < 2 {
				return false
			}
			l := int(data[0])<<8 | int(data[1])
			if l%2 == 1 || length != l+2 {
				return false
			}
			numCurves := l / 2
			m.supportedCurves = make([]CurveID, numCurves)
			d := data[2:]
			for i := 0; i < numCurves; i++ {
				m.supportedCurves[i] = CurveID(d[0])<<8 | CurveID(d[1])
				d = d[2:]
			}
		case extensionSupportedPoints:
			// http://tools.ietf.org/html/rfc4492#section-5.5.2
			if length < 1 {
				return false
			}
			l := int(data[0])
			if length != l+1 {
				return false
			}
			m.supportedPoints = make([]uint8, l)
			copy(m.supportedPoints, data[1:])
		case extensionSessionTicket:
			// http://tools.ietf.org/html/rfc5077#section-3.2
			m.ticketSupported = true
			m.sessionTicket = data[:length]
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
		case extensionKeyShare:
			// draft-ietf-tls-tls13 section 6.3.2.3
			if length < 2 {
				return false
			}
			l := int(data[0])<<8 | int(data[1])
			if l != length-2 {
				return false
			}
			d := data[2:length]
			for len(d) > 0 {
				// The next KeyShareEntry contains a NamedGroup (2 bytes) and a
				// key_exchange (2-byte length prefix with at least 1 byte of content).
				if len(d) < 5 {
					return false
				}
				entry := keyShareEntry{}
				entry.group = CurveID(d[0])<<8 | CurveID(d[1])
				keyExchLen := int(d[2])<<8 | int(d[3])
				d = d[4:]
				if len(d) < keyExchLen {
					return false
				}
				entry.keyExchange = d[:keyExchLen]
				d = d[keyExchLen:]
				m.keyShares = append(m.keyShares, entry)
			}
		case extensionPreSharedKey:
			// draft-ietf-tls-tls13 section 6.3.2.4
			if length < 2 {
				return false
			}
			l := int(data[0])<<8 | int(data[1])
			if l != length-2 {
				return false
			}
			d := data[2:length]
			for len(d) > 0 {
				if len(d) < 2 {
					return false
				}
				pskLen := int(d[0])<<8 | int(d[1])
				d = d[2:]
				if len(d) < pskLen {
					return false
				}
				psk := d[:pskLen]
				m.pskIdentities = append(m.pskIdentities, psk)
				d = d[pskLen:]
			}
		case extensionEarlyData:
			// draft-ietf-tls-tls13 section 6.3.2.5
			if length < 1 {
				return false
			}
			l := int(data[0])
			if length != l+1 {
				return false
			}
			m.hasEarlyData = true
			m.earlyDataContext = data[1:length]
Adam Langley's avatar
Adam Langley committed
603
604
605
606
607
608
609
610
611
612
613
		case extensionSignatureAlgorithms:
			// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
			if length < 2 || length&1 != 0 {
				return false
			}
			l := int(data[0])<<8 | int(data[1])
			if l != length-2 {
				return false
			}
			n := l / 2
			d := data[2:]
614
615
616
			m.signatureAlgorithms = make([]signatureAlgorithm, n)
			for i := range m.signatureAlgorithms {
				m.signatureAlgorithms[i] = signatureAlgorithm(d[0])<<8 | signatureAlgorithm(d[1])
Adam Langley's avatar
Adam Langley committed
617
618
				d = d[2:]
			}
Adam Langley's avatar
Adam Langley committed
619
620
		case extensionRenegotiationInfo:
			if length < 1 || length != int(data[0])+1 {
Adam Langley's avatar
Adam Langley committed
621
622
				return false
			}
Adam Langley's avatar
Adam Langley committed
623
			m.secureRenegotiation = data[1:length]
David Benjamin's avatar
David Benjamin committed
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
		case extensionALPN:
			if length < 2 {
				return false
			}
			l := int(data[0])<<8 | int(data[1])
			if l != length-2 {
				return false
			}
			d := data[2:length]
			for len(d) != 0 {
				stringLen := int(d[0])
				d = d[1:]
				if stringLen == 0 || stringLen > len(d) {
					return false
				}
				m.alpnProtocols = append(m.alpnProtocols, string(d[:stringLen]))
				d = d[stringLen:]
			}
642
643
644
645
646
		case extensionChannelID:
			if length > 0 {
				return false
			}
			m.channelIDSupported = true
Adam Langley's avatar
Adam Langley committed
647
648
649
650
651
		case extensionExtendedMasterSecret:
			if length != 0 {
				return false
			}
			m.extendedMasterSecret = true
David Benjamin's avatar
David Benjamin committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
		case extensionUseSRTP:
			if length < 2 {
				return false
			}
			l := int(data[0])<<8 | int(data[1])
			if l > length-2 || l%2 != 0 {
				return false
			}
			n := l / 2
			m.srtpProtectionProfiles = make([]uint16, n)
			d := data[2:length]
			for i := 0; i < n; i++ {
				m.srtpProtectionProfiles[i] = uint16(d[0])<<8 | uint16(d[1])
				d = d[2:]
			}
			if len(d) < 1 || int(d[0]) != len(d)-1 {
				return false
			}
			m.srtpMasterKeyIdentifier = string(d[1:])
671
672
673
674
675
		case extensionSignedCertificateTimestamp:
			if length != 0 {
				return false
			}
			m.sctListSupported = true
Adam Langley's avatar
Adam Langley committed
676
677
		case extensionCustom:
			m.customExtension = string(data[:length])
Adam Langley's avatar
Adam Langley committed
678
679
680
681
682
683
684
685
		}
		data = data[length:]
	}

	return true
}

type serverHelloMsg struct {
686
687
688
689
690
691
692
693
694
695
696
697
698
	raw                 []byte
	isDTLS              bool
	vers                uint16
	random              []byte
	sessionId           []byte
	cipherSuite         uint16
	hasKeyShare         bool
	keyShare            keyShareEntry
	hasPSKIdentity      bool
	pskIdentity         uint16
	earlyDataIndication bool
	compressionMethod   uint8
	extensions          serverExtensions
Adam Langley's avatar
Adam Langley committed
699
700
701
702
703
704
705
}

func (m *serverHelloMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}

706
707
708
	handshakeMsg := newByteBuilder()
	handshakeMsg.addU8(typeServerHello)
	hello := handshakeMsg.addU24LengthPrefixed()
709
	vers := versionToWire(m.vers, m.isDTLS)
710
711
	hello.addU16(vers)
	hello.addBytes(m.random)
712
713
714
715
	if m.vers < VersionTLS13 || !enableTLS13Handshake {
		sessionId := hello.addU8LengthPrefixed()
		sessionId.addBytes(m.sessionId)
	}
716
	hello.addU16(m.cipherSuite)
717
718
719
	if m.vers < VersionTLS13 || !enableTLS13Handshake {
		hello.addU8(m.compressionMethod)
	}
720
721

	extensions := hello.addU16LengthPrefixed()
722

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
	if m.vers >= VersionTLS13 && enableTLS13Handshake {
		if m.hasKeyShare {
			extensions.addU16(extensionKeyShare)
			keyShare := extensions.addU16LengthPrefixed()
			keyShare.addU16(uint16(m.keyShare.group))
			keyExchange := keyShare.addU16LengthPrefixed()
			keyExchange.addBytes(m.keyShare.keyExchange)
		}
		if m.hasPSKIdentity {
			extensions.addU16(extensionPreSharedKey)
			extensions.addU16(2) // Length
			extensions.addU16(m.pskIdentity)
		}
		if m.earlyDataIndication {
			extensions.addU16(extensionEarlyData)
			extensions.addU16(0) // Length
		}
	} else {
741
		m.extensions.marshal(extensions, m.vers)
742
743
744
		if extensions.len() == 0 {
			hello.discardChild()
		}
745
746
747
748
749
750
751
752
753
754
755
756
757
	}

	m.raw = handshakeMsg.finish()
	return m.raw
}

func (m *serverHelloMsg) unmarshal(data []byte) bool {
	if len(data) < 42 {
		return false
	}
	m.raw = data
	m.vers = wireToVersion(uint16(data[4])<<8|uint16(data[5]), m.isDTLS)
	m.random = data[6:38]
758
759
760
761
762
763
764
765
	data = data[38:]
	if m.vers < VersionTLS13 || !enableTLS13Handshake {
		sessionIdLen := int(data[0])
		if sessionIdLen > 32 || len(data) < 1+sessionIdLen {
			return false
		}
		m.sessionId = data[1 : 1+sessionIdLen]
		data = data[1+sessionIdLen:]
766
	}
767
	if len(data) < 2 {
768
769
770
		return false
	}
	m.cipherSuite = uint16(data[0])<<8 | uint16(data[1])
771
772
773
774
775
776
777
778
	data = data[2:]
	if m.vers < VersionTLS13 || !enableTLS13Handshake {
		if len(data) < 1 {
			return false
		}
		m.compressionMethod = data[0]
		data = data[1:]
	}
779

780
781
	if len(data) == 0 && (m.vers < VersionTLS13 || enableTLS13Handshake) {
		// Extension data is optional before TLS 1.3.
782
783
784
785
786
787
788
789
790
791
792
793
794
		m.extensions = serverExtensions{}
		return true
	}
	if len(data) < 2 {
		return false
	}

	extensionsLength := int(data[0])<<8 | int(data[1])
	data = data[2:]
	if len(data) != extensionsLength {
		return false
	}

795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
	if m.vers >= VersionTLS13 && enableTLS13Handshake {
		for len(data) != 0 {
			if len(data) < 4 {
				return false
			}
			extension := uint16(data[0])<<8 | uint16(data[1])
			length := int(data[2])<<8 | int(data[3])
			data = data[4:]

			if len(data) < length {
				return false
			}
			d := data[:length]
			data = data[length:]

			switch extension {
			case extensionKeyShare:
				m.hasKeyShare = true
				if len(d) < 4 {
					return false
				}
				m.keyShare.group = CurveID(uint16(d[0])<<8 | uint16(d[1]))
				keyExchLen := int(d[2])<<8 | int(d[3])
				if keyExchLen != len(d)-4 {
					return false
				}
				m.keyShare.keyExchange = make([]byte, keyExchLen)
				copy(m.keyShare.keyExchange, d[4:])
			case extensionPreSharedKey:
				if len(d) != 2 {
					return false
				}
				m.pskIdentity = uint16(d[0])<<8 | uint16(d[1])
				m.hasPSKIdentity = true
			case extensionEarlyData:
				if len(d) != 0 {
					return false
				}
				m.earlyDataIndication = true
			default:
				// Only allow the 3 extensions that are sent in
				// the clear in TLS 1.3.
				return false
			}
		}
840
	} else if !m.extensions.unmarshal(data, m.vers) {
841
842
843
844
845
846
		return false
	}

	return true
}

847
848
849
850
851
852
853
854
855
856
857
858
859
860
type encryptedExtensionsMsg struct {
	raw        []byte
	extensions serverExtensions
}

func (m *encryptedExtensionsMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}

	encryptedExtensionsMsg := newByteBuilder()
	encryptedExtensionsMsg.addU8(typeEncryptedExtensions)
	encryptedExtensions := encryptedExtensionsMsg.addU24LengthPrefixed()
	extensions := encryptedExtensions.addU16LengthPrefixed()
861
	m.extensions.marshal(extensions, VersionTLS13)
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883

	m.raw = encryptedExtensionsMsg.finish()
	return m.raw
}

func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool {
	if len(data) < 6 {
		return false
	}
	if data[0] != typeEncryptedExtensions {
		return false
	}
	msgLen := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
	data = data[4:]
	if len(data) != msgLen {
		return false
	}
	extLen := int(data[0])<<8 | int(data[1])
	data = data[2:]
	if extLen != len(data) {
		return false
	}
884
	return m.extensions.unmarshal(data, VersionTLS13)
885
886
}

887
888
889
890
type serverExtensions struct {
	nextProtoNeg            bool
	nextProtos              []string
	ocspStapling            bool
891
	ocspResponse            []byte
892
893
894
895
896
897
898
899
900
901
902
903
904
905
	ticketSupported         bool
	secureRenegotiation     []byte
	alpnProtocol            string
	alpnProtocolEmpty       bool
	duplicateExtension      bool
	channelIDRequested      bool
	extendedMasterSecret    bool
	srtpProtectionProfile   uint16
	srtpMasterKeyIdentifier string
	sctList                 []byte
	customExtension         string
	npnLast                 bool
}

906
func (m *serverExtensions) marshal(extensions *byteBuilder, version uint16) {
907
908
	if m.duplicateExtension {
		// Add a duplicate bogus extension at the beginning and end.
909
910
		extensions.addU16(0xffff)
		extensions.addU16(0) // length = 0 for empty extension
911
	}
912
	if m.nextProtoNeg && !m.npnLast {
913
914
		extensions.addU16(extensionNextProtoNeg)
		extension := extensions.addU16LengthPrefixed()
Adam Langley's avatar
Adam Langley committed
915
916

		for _, v := range m.nextProtos {
917
918
			if len(v) > 255 {
				v = v[:255]
Adam Langley's avatar
Adam Langley committed
919
			}
920
921
			npn := extension.addU8LengthPrefixed()
			npn.addBytes([]byte(v))
Adam Langley's avatar
Adam Langley committed
922
923
		}
	}
924
925
926
927
928
929
930
931
932
933
934
935
936
	if version >= VersionTLS13 && enableTLS13Handshake {
		if m.ocspResponse != nil {
			extensions.addU16(extensionStatusRequest)
			body := extensions.addU16LengthPrefixed()
			body.addU8(statusTypeOCSP)
			response := body.addU24LengthPrefixed()
			response.addBytes(m.ocspResponse)
		}
	} else {
		if m.ocspStapling {
			extensions.addU16(extensionStatusRequest)
			extensions.addU16(0)
		}
Adam Langley's avatar
Adam Langley committed
937
938
	}
	if m.ticketSupported {
939
940
		extensions.addU16(extensionSessionTicket)
		extensions.addU16(0)
Adam Langley's avatar
Adam Langley committed
941
	}
Adam Langley's avatar
Adam Langley committed
942
	if m.secureRenegotiation != nil {
943
944
945
946
947
948
949
950
951
952
953
954
		extensions.addU16(extensionRenegotiationInfo)
		extension := extensions.addU16LengthPrefixed()
		secureRenego := extension.addU8LengthPrefixed()
		secureRenego.addBytes(m.secureRenegotiation)
	}
	if len(m.alpnProtocol) > 0 || m.alpnProtocolEmpty {
		extensions.addU16(extensionALPN)
		extension := extensions.addU16LengthPrefixed()

		protocolNameList := extension.addU16LengthPrefixed()
		protocolName := protocolNameList.addU8LengthPrefixed()
		protocolName.addBytes([]byte(m.alpnProtocol))
David Benjamin's avatar
David Benjamin committed
955
	}
956
	if m.channelIDRequested {
957
958
		extensions.addU16(extensionChannelID)
		extensions.addU16(0)
959
	}
960
961
	if m.duplicateExtension {
		// Add a duplicate bogus extension at the beginning and end.
962
963
		extensions.addU16(0xffff)
		extensions.addU16(0)
964
	}
Adam Langley's avatar
Adam Langley committed
965
	if m.extendedMasterSecret {
966
967
		extensions.addU16(extensionExtendedMasterSecret)
		extensions.addU16(0)
Adam Langley's avatar
Adam Langley committed
968
	}
David Benjamin's avatar
David Benjamin committed
969
	if m.srtpProtectionProfile != 0 {
970
971
972
973
974
975
976
977
		extensions.addU16(extensionUseSRTP)
		extension := extensions.addU16LengthPrefixed()

		srtpProtectionProfiles := extension.addU16LengthPrefixed()
		srtpProtectionProfiles.addU8(byte(m.srtpProtectionProfile >> 8))
		srtpProtectionProfiles.addU8(byte(m.srtpProtectionProfile))
		srtpMki := extension.addU8LengthPrefixed()
		srtpMki.addBytes([]byte(m.srtpMasterKeyIdentifier))
David Benjamin's avatar
David Benjamin committed
978
	}
979
	if m.sctList != nil {
980
981
982
		extensions.addU16(extensionSignedCertificateTimestamp)
		extension := extensions.addU16LengthPrefixed()
		extension.addBytes(m.sctList)
983
	}
Adam Langley's avatar
Adam Langley committed
984
	if l := len(m.customExtension); l > 0 {
985
986
987
		extensions.addU16(extensionCustom)
		customExt := extensions.addU16LengthPrefixed()
		customExt.addBytes([]byte(m.customExtension))
Adam Langley's avatar
Adam Langley committed
988
	}
989
	if m.nextProtoNeg && m.npnLast {
990
991
		extensions.addU16(extensionNextProtoNeg)
		extension := extensions.addU16LengthPrefixed()
992
993

		for _, v := range m.nextProtos {
994
995
			if len(v) > 255 {
				v = v[0:255]
996
			}
997
998
			npn := extension.addU8LengthPrefixed()
			npn.addBytes([]byte(v))
999
1000
		}
	}
Adam Langley's avatar
Adam Langley committed
1001
1002
}

1003
func (m *serverExtensions) unmarshal(data []byte, version uint16) bool {
1004
1005
	// Reset all fields.
	*m = serverExtensions{}
Adam Langley's avatar
Adam Langley committed
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031

	for len(data) != 0 {
		if len(data) < 4 {
			return false
		}
		extension := uint16(data[0])<<8 | uint16(data[1])
		length := int(data[2])<<8 | int(data[3])
		data = data[4:]
		if len(data) < length {
			return false
		}

		switch extension {
		case extensionNextProtoNeg:
			m.nextProtoNeg = true
			d := data[:length]
			for len(d) > 0 {
				l := int(d[0])
				d = d[1:]
				if l == 0 || l > len(d) {
					return false
				}
				m.nextProtos = append(m.nextProtos, string(d[:l]))
				d = d[l:]
			}
		case extensionStatusRequest:
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
			if version >= VersionTLS13 && enableTLS13Handshake {
				if length < 4 {
					return false
				}
				d := data[:length]
				if d[0] != statusTypeOCSP {
					return false
				}
				respLen := int(d[1])<<16 | int(d[2])<<8 | int(d[3])
				if respLen+4 != len(d) || respLen == 0 {
					return false
				}
				m.ocspResponse = d[4:]
			} else {
				if length > 0 {
					return false
				}
				m.ocspStapling = true
Adam Langley's avatar
Adam Langley committed
1050
1051
1052
1053
1054
1055
1056
			}
		case extensionSessionTicket:
			if length > 0 {
				return false
			}
			m.ticketSupported = true
		case extensionRenegotiationInfo:
Adam Langley's avatar
Adam Langley committed
1057
			if length < 1 || length != int(data[0])+1 {
Adam Langley's avatar
Adam Langley committed
1058
1059
				return false
			}
Adam Langley's avatar
Adam Langley committed
1060
			m.secureRenegotiation = data[1:length]
David Benjamin's avatar
David Benjamin committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
		case extensionALPN:
			d := data[:length]
			if len(d) < 3 {
				return false
			}
			l := int(d[0])<<8 | int(d[1])
			if l != len(d)-2 {
				return false
			}
			d = d[2:]
			l = int(d[0])
			if l != len(d)-1 {
				return false
			}
			d = d[1:]
			m.alpnProtocol = string(d)
Adam Langley's avatar
Adam Langley committed
1077
			m.alpnProtocolEmpty = len(d) == 0
1078
1079
1080
1081
1082
		case extensionChannelID:
			if length > 0 {
				return false
			}
			m.channelIDRequested = true
Adam Langley's avatar
Adam Langley committed
1083
1084
1085
1086
1087
		case extensionExtendedMasterSecret:
			if length != 0 {
				return false
			}
			m.extendedMasterSecret = true
David Benjamin's avatar
David Benjamin committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
		case extensionUseSRTP:
			if length < 2+2+1 {
				return false
			}
			if data[0] != 0 || data[1] != 2 {
				return false
			}
			m.srtpProtectionProfile = uint16(data[2])<<8 | uint16(data[3])
			d := data[4:length]
			l := int(d[0])
			if l != len(d)-1 {
				return false
			}
			m.srtpMasterKeyIdentifier = string(d[1:])
1102
		case extensionSignedCertificateTimestamp:
1103
			m.sctList = data[:length]
Adam Langley's avatar
Adam Langley committed
1104
1105
		case extensionCustom:
			m.customExtension = string(data[:length])
Adam Langley's avatar
Adam Langley committed
1106
1107
1108
1109
1110
1111
1112
1113
		}
		data = data[length:]
	}

	return true
}

type certificateMsg struct {
1114
1115
1116
1117
	raw               []byte
	hasRequestContext bool
	requestContext    []byte
	certificates      [][]byte
Adam Langley's avatar
Adam Langley committed
1118
1119
1120
1121
1122
1123
1124
}

func (m *certificateMsg) marshal() (x []byte) {
	if m.raw != nil {
		return m.raw
	}

1125
1126
1127
	certMsg := newByteBuilder()
	certMsg.addU8(typeCertificate)
	certificate := certMsg.addU24LengthPrefixed()
1128
1129
1130
1131
	if m.hasRequestContext {
		context := certificate.addU8LengthPrefixed()
		context.addBytes(m.requestContext)
	}
1132
1133
1134
1135
	certificateList := certificate.addU24LengthPrefixed()
	for _, cert := range m.certificates {
		certEntry := certificateList.addU24LengthPrefixed()
		certEntry.addBytes(cert)
Adam Langley's avatar
Adam Langley committed
1136
1137
	}

1138
1139
	m.raw = certMsg.finish()
	return m.raw
Adam Langley's avatar
Adam Langley committed
1140
1141
1142
}

func (m *certificateMsg) unmarshal(data []byte) bool {
1143
	if len(data) < 4 {
Adam Langley's avatar
Adam Langley committed
1144
1145
1146
1147
		return false
	}

	m.raw = data
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
	data = data[4:]

	if m.hasRequestContext {
		if len(data) == 0 {
			return false
		}
		contextLen := int(data[0])
		if len(data) < 1+contextLen {
			return false
		}
		m.requestContext = make([]byte, contextLen)
		copy(m.requestContext, data[1:])
		data = data[1+contextLen:]
	}

	if len(data) < 3 {
		return false
	}
	certsLen := int(data[0])<<16 | int(data[1])<<8 | int(data[2])
	data = data[3:]
	if len(data) != certsLen {
Adam Langley's avatar
Adam Langley committed
1169
1170
1171
1172
		return false
	}

	numCerts := 0
1173
	d := data
Adam Langley's avatar
Adam Langley committed
1174
1175
1176
1177
	for certsLen > 0 {
		if len(d) < 4 {
			return false
		}
1178
1179
		certLen := int(d[0])<<16 | int(d[1])<<8 | int(d[2])
		if len(d) < 3+certLen {
Adam Langley's avatar
Adam Langley committed
1180
1181
1182
1183
1184
1185
1186
1187
			return false
		}
		d = d[3+certLen:]
		certsLen -= 3 + certLen
		numCerts++
	}

	m.certificates = make([][]byte, numCerts)
1188
	d = data
Adam Langley's avatar
Adam Langley committed
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
	for i := 0; i < numCerts; i++ {
		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
		m.certificates[i] = d[3 : 3+certLen]
		d = d[3+certLen:]
	}

	return true
}

type serverKeyExchangeMsg struct {
	raw []byte
	key []byte
}

func (m *serverKeyExchangeMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}
	length := len(m.key)
	x := make([]byte, length+4)
	x[0] = typeServerKeyExchange
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)
	copy(x[4:], m.key)

	m.raw = x
	return x
}

func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool {
	m.raw = data
	if len(data) < 4 {
		return false
	}
	m.key = data[4:]
	return true
}

type certificateStatusMsg struct {
	raw        []byte
	statusType uint8
	response   []byte
}

func (m *certificateStatusMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}

	var x []byte
	if m.statusType == statusTypeOCSP {
		x = make([]byte, 4+4+len(m.response))
		x[0] = typeCertificateStatus
		l := len(m.response) + 4
		x[1] = byte(l >> 16)
		x[2] = byte(l >> 8)
		x[3] = byte(l)
		x[4] = statusTypeOCSP

		l -= 4
		x[5] = byte(l >> 16)
		x[6] = byte(l >> 8)
		x[7] = byte(l)
		copy(x[8:], m.response)
	} else {
		x = []byte{typeCertificateStatus, 0, 0, 1, m.statusType}
	}

	m.raw = x
	return x
}

func (m *certificateStatusMsg) unmarshal(data []byte) bool {
	m.raw = data
	if len(data) < 5 {
		return false
	}
	m.statusType = data[4]

	m.response = nil
	if m.statusType == statusTypeOCSP {
		if len(data) < 8 {
			return false
		}
		respLen := uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
		if uint32(len(data)) != 4+4+respLen {
			return false
		}
		m.response = data[8:]
	}
	return true
}

type serverHelloDoneMsg struct{}

func (m *serverHelloDoneMsg) marshal() []byte {
	x := make([]byte, 4)
	x[0] = typeServerHelloDone
	return x
}

func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
	return len(data) == 4
}

type clientKeyExchangeMsg struct {
	raw        []byte
	ciphertext []byte
}

func (m *clientKeyExchangeMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}
	length := len(m.ciphertext)
	x := make([]byte, length+4)
	x[0] = typeClientKeyExchange
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)
	copy(x[4:], m.ciphertext)

	m.raw = x
	return x
}

func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool {
	m.raw = data
	if len(data) < 4 {
		return false
	}
	l := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
	if l != len(data)-4 {
		return false
	}
	m.ciphertext = data[4:]
	return true
}

type finishedMsg struct {
	raw        []byte
	verifyData []byte
}

func (m *finishedMsg) marshal() (x []byte) {
	if m.raw != nil {
		return m.raw
	}

	x = make([]byte, 4+len(m.verifyData))
	x[0] = typeFinished
	x[3] = byte(len(m.verifyData))
	copy(x[4:], m.verifyData)
	m.raw = x
	return
}

func (m *finishedMsg) unmarshal(data []byte) bool {
	m.raw = data
	if len(data) < 4 {
		return false
	}
	m.verifyData = data[4:]
	return true
}

type nextProtoMsg struct {
	raw   []byte
	proto string
}

func (m *nextProtoMsg) marshal() []byte {
	if m.raw != nil {
		return m.raw
	}
	l := len(m.proto)
	if l > 255 {
		l = 255
	}

	padding := 32 - (l+2)%32
	length := l + padding + 2
	x := make([]byte, length+4)
	x[0] = typeNextProtocol
	x[1] = uint8(length >> 16)
	x[2] = uint8(length >> 8)
	x[3] = uint8(length)

	y := x[4:]
	y[0] = byte(l)
	copy(y[1:], []byte(m.proto[0:l]))
	y = y[1+l:]
	y[0] = byte(padding)

	m.raw = x

	return x
}

func (m *nextProtoMsg) unmarshal(data []byte) bool {
	m.raw = data

	if len(data) < 5 {
		return false
	}
	data = data[4:]
	protoLen := int(data[0])
	data = data[1:]
	if len(data) < protoLen {
		return false
	}
	m.proto = string(data[0:protoLen])
	data = data[protoLen:]

	if len(data) < 1 {
		return false
	}
	paddingLen := int(data[0])
	data = data[1:]
	if len(data) != paddingLen {
		return false
	}

	return true
}

type certificateRequestMsg struct {
	raw []byte
1418
	// hasSignatureAlgorithm indicates whether this message includes a list
Adam Langley's avatar
Adam Langley committed
1419
1420
	// of signature and hash functions. This change was introduced with TLS
	// 1.2.
1421
	hasSignatureAlgorithm bool
1422
1423
1424
1425
	// hasRequestContext indicates whether this message includes a context
	// field instead of certificateTypes. This change was introduced with
	// TLS 1.3.
	hasRequestContext bool
Adam Langley's avatar
Adam Langley committed
1426
1427

	certificateTypes       []byte
1428
	requestContext         []byte
1429
	signatureAlgorithms    []signatureAlgorithm
Adam Langley's avatar
Adam Langley committed
1430
1431
1432
	certificateAuthorities [][]byte
}

1433
func (m *certificateRequestMsg) marshal() []byte {
Adam Langley's avatar
Adam Langley committed
1434
1435
1436
1437
1438
	if m.raw != nil {
		return m.raw
	}

	// See http://tools.ietf.org/html/rfc4346#section-7.4.4
1439
1440
1441
	builder := newByteBuilder()
	builder.addU8(typeCertificateRequest)
	body := builder.addU24LengthPrefixed()
Adam Langley's avatar
Adam Langley committed
1442

1443
1444
1445
1446
1447
1448
1449
	if m.hasRequestContext {
		requestContext := body.addU8LengthPrefixed()
		requestContext.addBytes(m.requestContext)
	} else {
		certificateTypes := body.addU8LengthPrefixed()
		certificateTypes.addBytes(m.certificateTypes)
	}
Adam Langley's avatar
Adam Langley committed
1450

1451
	if m.hasSignatureAlgorithm {
1452
		signatureAlgorithms := body.addU16LengthPrefixed()
1453
		for _, sigAlg := range m.signatureAlgorithms {
1454
			signatureAlgorithms.addU16(uint16(sigAlg))
Adam Langley's avatar
Adam Langley committed
1455
1456
1457
		}
	}

1458
	certificateAuthorities := body.addU16LengthPrefixed()
Adam Langley's avatar
Adam Langley committed
1459
	for _, ca := range m.certificateAuthorities {
1460
1461
		caEntry := certificateAuthorities.addU16LengthPrefixed()
		caEntry.addBytes(ca)
Adam Langley's avatar
Adam Langley committed
1462
1463
	}

1464
1465
1466
1467
1468
	if m.hasRequestContext {
		// Emit no certificate extensions.
		body.addU16(0)
	}

1469
1470
	m.raw = builder.finish()
	return m.raw
Adam Langley's avatar
Adam Langley committed
1471
1472
1473
1474
1475
1476
1477
1478
}

func (m *certificateRequestMsg) unmarshal(data []byte) bool {
	m.raw = data

	if len(data) < 5 {
		return false
	}
1479
	data = data[4:]
Adam Langley's avatar
Adam Langley committed
1480

1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
	if m.hasRequestContext {
		contextLen := int(data[0])
		if len(data) < 1+contextLen {
			return false
		}
		m.requestContext = make([]byte, contextLen)
		copy(m.requestContext, data[1:])
		data = data[1+contextLen:]
	} else {
		numCertTypes := int(data[0])
		if len(data) < 1+numCertTypes {
			return false
		}
		m.certificateTypes = make([]byte, numCertTypes)
		copy(m.certificateTypes, data[1:])
		data = data[1+numCertTypes:]
Adam Langley's avatar
Adam Langley committed
1497
1498
	}

1499
	if m.hasSignatureAlgorithm {
Adam Langley's avatar
Adam Langley committed
1500
1501
1502
		if len(data) < 2 {
			return false