handshake_client.go 39.3 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
	"crypto"
Adam Langley's avatar
Adam Langley committed
10
	"crypto/ecdsa"
11
	"crypto/elliptic"
Adam Langley's avatar
Adam Langley committed
12
13
14
15
16
17
	"crypto/rsa"
	"crypto/subtle"
	"crypto/x509"
	"errors"
	"fmt"
	"io"
18
	"math/big"
Adam Langley's avatar
Adam Langley committed
19
20
21
22
23
	"net"
	"strconv"
)

type clientHandshakeState struct {
24
25
26
27
28
	c             *Conn
	serverHello   *serverHelloMsg
	hello         *clientHelloMsg
	suite         *cipherSuite
	finishedHash  finishedHash
29
	keyShares     map[CurveID]ecdhCurve
30
31
32
	masterSecret  []byte
	session       *ClientSessionState
	finishedBytes []byte
Adam Langley's avatar
Adam Langley committed
33
34
35
36
37
38
39
40
41
42
43
}

func (c *Conn) clientHandshake() error {
	if c.config == nil {
		c.config = defaultConfig()
	}

	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
	}

44
45
46
	c.sendHandshakeSeq = 0
	c.recvHandshakeSeq = 0

David Benjamin's avatar
David Benjamin committed
47
48
	nextProtosLength := 0
	for _, proto := range c.config.NextProtos {
Adam Langley's avatar
Adam Langley committed
49
		if l := len(proto); l > 255 {
David Benjamin's avatar
David Benjamin committed
50
51
52
53
54
55
56
57
58
			return errors.New("tls: invalid NextProtos value")
		} else {
			nextProtosLength += 1 + l
		}
	}
	if nextProtosLength > 0xffff {
		return errors.New("tls: NextProtos values too large")
	}

Adam Langley's avatar
Adam Langley committed
59
	hello := &clientHelloMsg{
David Benjamin's avatar
David Benjamin committed
60
		isDTLS:                  c.isDTLS,
61
		vers:                    c.config.maxVersion(c.isDTLS),
David Benjamin's avatar
David Benjamin committed
62
63
64
		compressionMethods:      []uint8{compressionNone},
		random:                  make([]byte, 32),
		ocspStapling:            true,
65
		sctListSupported:        true,
David Benjamin's avatar
David Benjamin committed
66
67
68
69
70
71
72
73
74
		serverName:              c.config.ServerName,
		supportedCurves:         c.config.curvePreferences(),
		supportedPoints:         []uint8{pointFormatUncompressed},
		nextProtoNeg:            len(c.config.NextProtos) > 0,
		secureRenegotiation:     []byte{},
		alpnProtocols:           c.config.NextProtos,
		duplicateExtension:      c.config.Bugs.DuplicateExtension,
		channelIDSupported:      c.config.ChannelID != nil,
		npnLast:                 c.config.Bugs.SwapNPNAndALPN,
75
		extendedMasterSecret:    c.config.maxVersion(c.isDTLS) >= VersionTLS10,
David Benjamin's avatar
David Benjamin committed
76
77
		srtpProtectionProfiles:  c.config.SRTPProtectionProfiles,
		srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley's avatar
Adam Langley committed
78
		customExtension:         c.config.Bugs.CustomExtension,
Adam Langley's avatar
Adam Langley committed
79
80
	}

David Benjamin's avatar
David Benjamin committed
81
82
83
84
	if c.config.Bugs.SendClientVersion != 0 {
		hello.vers = c.config.Bugs.SendClientVersion
	}

Adam Langley's avatar
Adam Langley committed
85
86
87
88
	if c.config.Bugs.NoExtendedMasterSecret {
		hello.extendedMasterSecret = false
	}

89
90
91
92
	if c.config.Bugs.NoSupportedCurves {
		hello.supportedCurves = nil
	}

Adam Langley's avatar
Adam Langley committed
93
94
95
96
97
98
99
100
101
	if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
		if c.config.Bugs.BadRenegotiationInfo {
			hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
			hello.secureRenegotiation[0] ^= 0x80
		} else {
			hello.secureRenegotiation = c.clientVerify
		}
	}

102
	if c.noRenegotiationInfo() {
103
104
105
		hello.secureRenegotiation = nil
	}

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
	var keyShares map[CurveID]ecdhCurve
	if hello.vers >= VersionTLS13 && enableTLS13Handshake {
		// Offer every supported curve in the initial ClientHello.
		//
		// TODO(davidben): For real code, default to a more conservative
		// set like P-256 and X25519. Make it configurable for tests to
		// stress the HelloRetryRequest logic when implemented.
		keyShares = make(map[CurveID]ecdhCurve)
		for _, curveID := range hello.supportedCurves {
			curve, ok := curveForCurveID(curveID)
			if !ok {
				continue
			}
			publicKey, err := curve.offer(c.config.rand())
			if err != nil {
				return err
			}
			hello.keyShares = append(hello.keyShares, keyShareEntry{
				group:       curveID,
				keyExchange: publicKey,
			})
			keyShares[curveID] = curve
		}
	}

Adam Langley's avatar
Adam Langley committed
131
132
133
134
135
136
137
138
139
	possibleCipherSuites := c.config.cipherSuites()
	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))

NextCipherSuite:
	for _, suiteId := range possibleCipherSuites {
		for _, suite := range cipherSuites {
			if suite.id != suiteId {
				continue
			}
140
141
142
143
144
145
146
147
148
149
			if !c.config.Bugs.EnableAllCiphers {
				// Don't advertise TLS 1.2-only cipher suites unless
				// we're attempting TLS 1.2.
				if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
					continue
				}
				// Don't advertise non-DTLS cipher suites in DTLS.
				if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
					continue
				}
150
			}
Adam Langley's avatar
Adam Langley committed
151
152
153
154
155
			hello.cipherSuites = append(hello.cipherSuites, suiteId)
			continue NextCipherSuite
		}
	}

156
157
158
159
	if c.config.Bugs.SendRenegotiationSCSV {
		hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
	}

160
161
162
163
	if c.config.Bugs.SendFallbackSCSV {
		hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
	}

Adam Langley's avatar
Adam Langley committed
164
165
166
167
168
169
	_, err := io.ReadFull(c.config.rand(), hello.random)
	if err != nil {
		c.sendAlert(alertInternalError)
		return errors.New("tls: short read from Rand: " + err.Error())
	}

170
	if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
171
		hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
Adam Langley's avatar
Adam Langley committed
172
173
174
175
176
177
178
	}

	var session *ClientSessionState
	var cacheKey string
	sessionCache := c.config.ClientSessionCache

	if sessionCache != nil {
179
		hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley's avatar
Adam Langley committed
180
181
182
183
184
185

		// Try to resume a previously negotiated TLS session, if
		// available.
		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
		candidateSession, ok := sessionCache.Get(cacheKey)
		if ok {
186
187
			ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil

Adam Langley's avatar
Adam Langley committed
188
189
190
191
192
193
194
195
196
197
			// Check that the ciphersuite/version used for the
			// previous session are still valid.
			cipherSuiteOk := false
			for _, id := range hello.cipherSuites {
				if id == candidateSession.cipherSuite {
					cipherSuiteOk = true
					break
				}
			}

198
199
			versOk := candidateSession.vers >= c.config.minVersion(c.isDTLS) &&
				candidateSession.vers <= c.config.maxVersion(c.isDTLS)
200
			if ticketOk && versOk && cipherSuiteOk {
Adam Langley's avatar
Adam Langley committed
201
202
203
204
205
206
				session = candidateSession
			}
		}
	}

	if session != nil {
207
208
209
210
211
212
213
214
215
216
217
		if session.sessionTicket != nil {
			hello.sessionTicket = session.sessionTicket
			if c.config.Bugs.CorruptTicket {
				hello.sessionTicket = make([]byte, len(session.sessionTicket))
				copy(hello.sessionTicket, session.sessionTicket)
				if len(hello.sessionTicket) > 0 {
					offset := 40
					if offset > len(hello.sessionTicket) {
						offset = len(hello.sessionTicket) - 1
					}
					hello.sessionTicket[offset] ^= 0x40
218
219
				}
			}
220
221
222
223
224
225
226
227
228
229
230
231
232
233
			// A random session ID is used to detect when the
			// server accepted the ticket and is resuming a session
			// (see RFC 5077).
			sessionIdLen := 16
			if c.config.Bugs.OversizedSessionId {
				sessionIdLen = 33
			}
			hello.sessionId = make([]byte, sessionIdLen)
			if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
				c.sendAlert(alertInternalError)
				return errors.New("tls: short read from Rand: " + err.Error())
			}
		} else {
			hello.sessionId = session.sessionId
Adam Langley's avatar
Adam Langley committed
234
235
236
		}
	}

237
238
	var helloBytes []byte
	if c.config.Bugs.SendV2ClientHello {
239
240
		// Test that the peer left-pads random.
		hello.random[0] = 0
241
242
243
244
245
		v2Hello := &v2ClientHelloMsg{
			vers:         hello.vers,
			cipherSuites: hello.cipherSuites,
			// No session resumption for V2ClientHello.
			sessionId: nil,
246
			challenge: hello.random[1:],
247
248
249
250
251
252
253
		}
		helloBytes = v2Hello.marshal()
		c.writeV2Record(helloBytes)
	} else {
		helloBytes = hello.marshal()
		c.writeRecord(recordTypeHandshake, helloBytes)
	}
254
	c.flushHandshake()
Adam Langley's avatar
Adam Langley committed
255

256
257
258
	if err := c.simulatePacketLoss(nil); err != nil {
		return err
	}
Adam Langley's avatar
Adam Langley committed
259
260
261
262
	msg, err := c.readHandshake()
	if err != nil {
		return err
	}
263
264
265
266

	if c.isDTLS {
		helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
		if ok {
267
268
269
270
271
272
273
			if helloVerifyRequest.vers != VersionTLS10 {
				// Per RFC 6347, the version field in
				// HelloVerifyRequest SHOULD be always DTLS
				// 1.0. Enforce this for testing purposes.
				return errors.New("dtls: bad HelloVerifyRequest version")
			}

274
275
276
277
			hello.raw = nil
			hello.cookie = helloVerifyRequest.cookie
			helloBytes = hello.marshal()
			c.writeRecord(recordTypeHandshake, helloBytes)
278
			c.flushHandshake()
279

280
281
282
			if err := c.simulatePacketLoss(nil); err != nil {
				return err
			}
283
284
285
286
287
288
289
			msg, err = c.readHandshake()
			if err != nil {
				return err
			}
		}
	}

290
	// TODO(davidben): Handle HelloRetryRequest.
Adam Langley's avatar
Adam Langley committed
291
292
293
294
295
296
	serverHello, ok := msg.(*serverHelloMsg)
	if !ok {
		c.sendAlert(alertUnexpectedMessage)
		return unexpectedMessageError(serverHello, msg)
	}

297
	c.vers, ok = c.config.mutualVersion(serverHello.vers, c.isDTLS)
298
	if !ok {
Adam Langley's avatar
Adam Langley committed
299
300
301
302
303
		c.sendAlert(alertProtocolVersion)
		return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
	}
	c.haveVers = true

304
	// Check for downgrade signals in the server random, per
305
	// draft-ietf-tls-tls13-14, section 6.3.1.2.
306
	if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
307
		if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
308
309
310
311
312
			c.sendAlert(alertProtocolVersion)
			return errors.New("tls: downgrade from TLS 1.3 detected")
		}
	}
	if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
313
		if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
314
315
316
317
318
			c.sendAlert(alertProtocolVersion)
			return errors.New("tls: downgrade from TLS 1.2 detected")
		}
	}

Adam Langley's avatar
Adam Langley committed
319
320
321
322
323
324
325
326
327
328
329
330
	suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
	if suite == nil {
		c.sendAlert(alertHandshakeFailure)
		return fmt.Errorf("tls: server selected an unsupported cipher suite")
	}

	hs := &clientHandshakeState{
		c:            c,
		serverHello:  serverHello,
		hello:        hello,
		suite:        suite,
		finishedHash: newFinishedHash(c.vers, suite),
331
		keyShares:    keyShares,
Adam Langley's avatar
Adam Langley committed
332
333
334
		session:      session,
	}

335
336
	hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
	hs.writeServerHash(hs.serverHello.marshal())
Adam Langley's avatar
Adam Langley committed
337

338
339
340
341
342
343
344
345
346
	if c.vers >= VersionTLS13 && enableTLS13Handshake {
		if err := hs.doTLS13Handshake(); err != nil {
			return err
		}
	} else {
		if c.config.Bugs.EarlyChangeCipherSpec > 0 {
			hs.establishKeys()
			c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
		}
347

348
349
350
351
		if hs.serverHello.compressionMethod != compressionNone {
			c.sendAlert(alertUnexpectedMessage)
			return errors.New("tls: server selected unsupported compression format")
		}
352

353
354
355
356
		err = hs.processServerExtensions(&serverHello.extensions)
		if err != nil {
			return err
		}
357

358
359
360
361
		isResume, err := hs.processServerHello()
		if err != nil {
			return err
		}
Adam Langley's avatar
Adam Langley committed
362

363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
		if isResume {
			if c.config.Bugs.EarlyChangeCipherSpec == 0 {
				if err := hs.establishKeys(); err != nil {
					return err
				}
			}
			if err := hs.readSessionTicket(); err != nil {
				return err
			}
			if err := hs.readFinished(c.firstFinished[:]); err != nil {
				return err
			}
			if err := hs.sendFinished(nil, isResume); err != nil {
				return err
			}
		} else {
			if err := hs.doFullHandshake(); err != nil {
				return err
			}
382
383
384
			if err := hs.establishKeys(); err != nil {
				return err
			}
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
			if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
				return err
			}
			// Most retransmits are triggered by a timeout, but the final
			// leg of the handshake is retransmited upon re-receiving a
			// Finished.
			if err := c.simulatePacketLoss(func() {
				c.writeRecord(recordTypeHandshake, hs.finishedBytes)
				c.flushHandshake()
			}); err != nil {
				return err
			}
			if err := hs.readSessionTicket(); err != nil {
				return err
			}
			if err := hs.readFinished(nil); err != nil {
				return err
			}
Adam Langley's avatar
Adam Langley committed
403
		}
404
405
406
407
408
409

		if sessionCache != nil && hs.session != nil && session != hs.session {
			if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
				return errors.New("tls: new session used session IDs instead of tickets")
			}
			sessionCache.Put(cacheKey, hs.session)
Adam Langley's avatar
Adam Langley committed
410
		}
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470

		c.didResume = isResume
	}

	c.handshakeComplete = true
	c.cipherSuite = suite
	copy(c.clientRandom[:], hs.hello.random)
	copy(c.serverRandom[:], hs.serverHello.random)
	copy(c.masterSecret[:], hs.masterSecret)

	return nil
}

func (hs *clientHandshakeState) doTLS13Handshake() error {
	c := hs.c

	// Once the PRF hash is known, TLS 1.3 does not require a handshake
	// buffer.
	hs.finishedHash.discardHandshakeBuffer()

	zeroSecret := hs.finishedHash.zeroSecret()

	// Resolve PSK and compute the early secret.
	//
	// TODO(davidben): This will need to be handled slightly earlier once
	// 0-RTT is implemented.
	var psk []byte
	if hs.suite.flags&suitePSK != 0 {
		if !hs.serverHello.hasPSKIdentity {
			c.sendAlert(alertMissingExtension)
			return errors.New("tls: server omitted the PSK identity extension")
		}

		// TODO(davidben): Support PSK ciphers and PSK resumption. Set
		// the resumption context appropriately if resuming.
		return errors.New("tls: PSK ciphers not implemented for TLS 1.3")
	} else {
		if hs.serverHello.hasPSKIdentity {
			c.sendAlert(alertUnsupportedExtension)
			return errors.New("tls: server sent unexpected PSK identity")
		}

		psk = zeroSecret
		hs.finishedHash.setResumptionContext(zeroSecret)
	}

	earlySecret := hs.finishedHash.extractKey(zeroSecret, psk)

	// Resolve ECDHE and compute the handshake secret.
	var ecdheSecret []byte
	if hs.suite.flags&suiteECDHE != 0 {
		if !hs.serverHello.hasKeyShare {
			c.sendAlert(alertMissingExtension)
			return errors.New("tls: server omitted the key share extension")
		}

		curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
		if !ok {
			c.sendAlert(alertHandshakeFailure)
			return errors.New("tls: server selected an unsupported group")
Adam Langley's avatar
Adam Langley committed
471
		}
472
473
474
475

		var err error
		ecdheSecret, err = curve.finish(hs.serverHello.keyShare.keyExchange)
		if err != nil {
Adam Langley's avatar
Adam Langley committed
476
477
478
			return err
		}
	} else {
479
480
481
		if hs.serverHello.hasKeyShare {
			c.sendAlert(alertUnsupportedExtension)
			return errors.New("tls: server sent unexpected key share extension")
Adam Langley's avatar
Adam Langley committed
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

		ecdheSecret = zeroSecret
	}

	// Compute the handshake secret.
	handshakeSecret := hs.finishedHash.extractKey(earlySecret, ecdheSecret)

	// Switch to handshake traffic keys.
	handshakeTrafficSecret := hs.finishedHash.deriveSecret(handshakeSecret, handshakeTrafficLabel)
	c.out.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, clientWrite), c.vers)
	c.in.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, handshakeTrafficSecret, handshakePhase, serverWrite), c.vers)

	msg, err := c.readHandshake()
	if err != nil {
		return err
	}

	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
	if !ok {
		c.sendAlert(alertUnexpectedMessage)
		return unexpectedMessageError(encryptedExtensions, msg)
	}
	hs.writeServerHash(encryptedExtensions.marshal())

	err = hs.processServerExtensions(&encryptedExtensions.extensions)
	if err != nil {
		return err
	}

	var chainToSend *Certificate
513
	var certReq *certificateRequestMsg
514
515
516
517
518
519
520
521
522
523
524
525
	if hs.suite.flags&suitePSK != 0 {
		if encryptedExtensions.extensions.ocspResponse != nil {
			c.sendAlert(alertUnsupportedExtension)
			return errors.New("tls: server sent OCSP response without a certificate")
		}
		if encryptedExtensions.extensions.sctList != nil {
			c.sendAlert(alertUnsupportedExtension)
			return errors.New("tls: server sent SCT list without a certificate")
		}
	} else {
		c.ocspResponse = encryptedExtensions.extensions.ocspResponse
		c.sctList = encryptedExtensions.extensions.sctList
526
527
528

		msg, err := c.readHandshake()
		if err != nil {
Adam Langley's avatar
Adam Langley committed
529
530
			return err
		}
531

532
533
		var ok bool
		certReq, ok = msg.(*certificateRequestMsg)
534
535
536
537
538
539
540
541
542
543
544
545
		if ok {
			hs.writeServerHash(certReq.marshal())

			chainToSend, err = selectClientCertificate(c, certReq)
			if err != nil {
				return err
			}

			msg, err = c.readHandshake()
			if err != nil {
				return err
			}
Adam Langley's avatar
Adam Langley committed
546
		}
547
548
549
550
551
552
553
554
555

		certMsg, ok := msg.(*certificateMsg)
		if !ok {
			c.sendAlert(alertUnexpectedMessage)
			return unexpectedMessageError(certMsg, msg)
		}
		hs.writeServerHash(certMsg.marshal())

		if err := hs.verifyCertificates(certMsg); err != nil {
556
557
			return err
		}
558
559
560
561
		leaf := c.peerCertificates[0]

		msg, err = c.readHandshake()
		if err != nil {
Adam Langley's avatar
Adam Langley committed
562
563
			return err
		}
564
565
566
567
568
569
570
		certVerifyMsg, ok := msg.(*certificateVerifyMsg)
		if !ok {
			c.sendAlert(alertUnexpectedMessage)
			return unexpectedMessageError(certVerifyMsg, msg)
		}

		input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
571
		err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
572
		if err != nil {
Adam Langley's avatar
Adam Langley committed
573
574
			return err
		}
575
576

		hs.writeServerHash(certVerifyMsg.marshal())
Adam Langley's avatar
Adam Langley committed
577
578
	}

579
580
581
582
583
584
585
586
	msg, err = c.readHandshake()
	if err != nil {
		return err
	}
	serverFinished, ok := msg.(*finishedMsg)
	if !ok {
		c.sendAlert(alertUnexpectedMessage)
		return unexpectedMessageError(serverFinished, msg)
Adam Langley's avatar
Adam Langley committed
587
588
	}

589
590
591
592
593
594
595
596
	verify := hs.finishedHash.serverSum(handshakeTrafficSecret)
	if len(verify) != len(serverFinished.verifyData) ||
		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
		c.sendAlert(alertHandshakeFailure)
		return errors.New("tls: server's Finished message was incorrect")
	}

	hs.writeServerHash(serverFinished.marshal())
597

598
599
600
601
602
	// The various secrets do not incorporate the client's final leg, so
	// derive them now before updating the handshake context.
	masterSecret := hs.finishedHash.extractKey(handshakeSecret, zeroSecret)
	trafficSecret := hs.finishedHash.deriveSecret(masterSecret, applicationTrafficLabel)

603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
	if certReq != nil {
		certMsg := &certificateMsg{
			hasRequestContext: true,
			requestContext:    certReq.requestContext,
		}
		if chainToSend != nil {
			certMsg.certificates = chainToSend.Certificate
		}
		hs.writeClientHash(certMsg.marshal())
		c.writeRecord(recordTypeHandshake, certMsg.marshal())

		if chainToSend != nil {
			certVerify := &certificateVerifyMsg{
				hasSignatureAlgorithm: true,
			}

			// Determine the hash to sign.
			privKey := chainToSend.PrivateKey

			var err error
			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
			if err != nil {
				c.sendAlert(alertInternalError)
				return err
			}

			input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
			certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
			if err != nil {
				c.sendAlert(alertInternalError)
				return err
			}

			hs.writeClientHash(certVerify.marshal())
			c.writeRecord(recordTypeHandshake, certVerify.marshal())
		}
639
640
641
642
643
644
645
646
647
	}

	// Send a client Finished message.
	finished := new(finishedMsg)
	finished.verifyData = hs.finishedHash.clientSum(handshakeTrafficSecret)
	if c.config.Bugs.BadFinished {
		finished.verifyData[0]++
	}
	c.writeRecord(recordTypeHandshake, finished.marshal())
648
	c.flushHandshake()
649
650
651
652
653
654
655
656

	// Switch to application data keys.
	c.out.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, trafficSecret, applicationPhase, clientWrite), c.vers)
	c.in.updateKeys(deriveTrafficAEAD(c.vers, hs.suite, trafficSecret, applicationPhase, serverWrite), c.vers)

	// TODO(davidben): Derive and save the exporter master secret for key exporters. Swap out the masterSecret field.
	// TODO(davidben): Derive and save the resumption master secret for receiving tickets.
	// TODO(davidben): Save the traffic secret for KeyUpdate.
Adam Langley's avatar
Adam Langley committed
657
658
659
660
661
662
	return nil
}

func (hs *clientHandshakeState) doFullHandshake() error {
	c := hs.c

663
664
665
	var leaf *x509.Certificate
	if hs.suite.flags&suitePSK == 0 {
		msg, err := c.readHandshake()
Adam Langley's avatar
Adam Langley committed
666
		if err != nil {
667
			return err
Adam Langley's avatar
Adam Langley committed
668
669
		}

670
		certMsg, ok := msg.(*certificateMsg)
671
		if !ok {
672
673
			c.sendAlert(alertUnexpectedMessage)
			return unexpectedMessageError(certMsg, msg)
Adam Langley's avatar
Adam Langley committed
674
		}
675
		hs.writeServerHash(certMsg.marshal())
Adam Langley's avatar
Adam Langley committed
676

677
678
		if err := hs.verifyCertificates(certMsg); err != nil {
			return err
679
		}
680
		leaf = c.peerCertificates[0]
681
	}
Adam Langley's avatar
Adam Langley committed
682

683
	if hs.serverHello.extensions.ocspStapling {
684
		msg, err := c.readHandshake()
Adam Langley's avatar
Adam Langley committed
685
686
687
688
689
690
691
692
		if err != nil {
			return err
		}
		cs, ok := msg.(*certificateStatusMsg)
		if !ok {
			c.sendAlert(alertUnexpectedMessage)
			return unexpectedMessageError(cs, msg)
		}
693
		hs.writeServerHash(cs.marshal())
Adam Langley's avatar
Adam Langley committed
694
695
696
697
698
699

		if cs.statusType == statusTypeOCSP {
			c.ocspResponse = cs.response
		}
	}

700
	msg, err := c.readHandshake()
Adam Langley's avatar
Adam Langley committed
701
702
703
704
705
706
707
708
	if err != nil {
		return err
	}

	keyAgreement := hs.suite.ka(c.vers)

	skx, ok := msg.(*serverKeyExchangeMsg)
	if ok {
709
		hs.writeServerHash(skx.marshal())
710
		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley's avatar
Adam Langley committed
711
712
713
714
715
		if err != nil {
			c.sendAlert(alertUnexpectedMessage)
			return err
		}

716
717
		c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()

Adam Langley's avatar
Adam Langley committed
718
719
720
721
722
723
724
725
726
727
728
		msg, err = c.readHandshake()
		if err != nil {
			return err
		}
	}

	var chainToSend *Certificate
	var certRequested bool
	certReq, ok := msg.(*certificateRequestMsg)
	if ok {
		certRequested = true
729
730
731
		if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
			certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
		}
Adam Langley's avatar
Adam Langley committed
732

733
		hs.writeServerHash(certReq.marshal())
Adam Langley's avatar
Adam Langley committed
734

735
736
737
		chainToSend, err = selectClientCertificate(c, certReq)
		if err != nil {
			return err
Adam Langley's avatar
Adam Langley committed
738
739
740
741
742
743
744
745
746
747
748
749
750
		}

		msg, err = c.readHandshake()
		if err != nil {
			return err
		}
	}

	shd, ok := msg.(*serverHelloDoneMsg)
	if !ok {
		c.sendAlert(alertUnexpectedMessage)
		return unexpectedMessageError(shd, msg)
	}
751
	hs.writeServerHash(shd.marshal())
Adam Langley's avatar
Adam Langley committed
752
753

	// If the server requested a certificate then we have to send a
754
755
756
	// Certificate message in TLS, even if it's empty because we don't have
	// a certificate to send. In SSL 3.0, skip the message and send a
	// no_certificate warning alert.
Adam Langley's avatar
Adam Langley committed
757
	if certRequested {
758
759
760
761
762
763
764
765
766
		if c.vers == VersionSSL30 && chainToSend == nil {
			c.sendAlert(alertNoCertficate)
		} else if !c.config.Bugs.SkipClientCertificate {
			certMsg := new(certificateMsg)
			if chainToSend != nil {
				certMsg.certificates = chainToSend.Certificate
			}
			hs.writeClientHash(certMsg.marshal())
			c.writeRecord(recordTypeHandshake, certMsg.marshal())
Adam Langley's avatar
Adam Langley committed
767
768
769
		}
	}

770
	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley's avatar
Adam Langley committed
771
772
773
774
775
	if err != nil {
		c.sendAlert(alertInternalError)
		return err
	}
	if ckx != nil {
776
		if c.config.Bugs.EarlyChangeCipherSpec < 2 {
777
			hs.writeClientHash(ckx.marshal())
778
		}
Adam Langley's avatar
Adam Langley committed
779
780
781
		c.writeRecord(recordTypeHandshake, ckx.marshal())
	}

782
	if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
Adam Langley's avatar
Adam Langley committed
783
784
785
786
787
788
789
790
		hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
		c.extendedMasterSecret = true
	} else {
		if c.config.Bugs.RequireExtendedMasterSecret {
			return errors.New("tls: extended master secret required but not supported by peer")
		}
		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
	}
791

Adam Langley's avatar
Adam Langley committed
792
793
	if chainToSend != nil {
		certVerify := &certificateVerifyMsg{
794
			hasSignatureAlgorithm: c.vers >= VersionTLS12,
Adam Langley's avatar
Adam Langley committed
795
796
		}

797
		// Determine the hash to sign.
798
799
800
		privKey := c.config.Certificates[0].PrivateKey

		if certVerify.hasSignatureAlgorithm {
801
			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
802
803
804
805
			if err != nil {
				c.sendAlert(alertInternalError)
				return err
			}
806
		}
807

808
809
810
811
812
813
814
815
		if c.vers > VersionSSL30 {
			msg := hs.finishedHash.buffer
			if c.config.Bugs.InvalidCertVerifySignature {
				msg = make([]byte, len(hs.finishedHash.buffer))
				copy(msg, hs.finishedHash.buffer)
				msg[0] ^= 0x80
			}
			certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, msg)
816
817
818
			if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
				certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
			}
819
820
821
822
823
824
825
826
827
828
829
830
		} else {
			// SSL 3.0's client certificate construction is
			// incompatible with signatureAlgorithm.
			rsaKey, ok := privKey.(*rsa.PrivateKey)
			if !ok {
				err = errors.New("unsupported signature type for client certificate")
			} else {
				digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
				if c.config.Bugs.InvalidCertVerifySignature {
					digest[0] ^= 0x80
				}
				certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
Adam Langley's avatar
Adam Langley committed
831
832
833
834
835
836
837
			}
		}
		if err != nil {
			c.sendAlert(alertInternalError)
			return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
		}

838
		hs.writeClientHash(certVerify.marshal())
Adam Langley's avatar
Adam Langley committed
839
840
		c.writeRecord(recordTypeHandshake, certVerify.marshal())
	}
841
	// flushHandshake will be called in sendFinished.
Adam Langley's avatar
Adam Langley committed
842

843
844
	hs.finishedHash.discardHandshakeBuffer()

Adam Langley's avatar
Adam Langley committed
845
846
847
	return nil
}

848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
	c := hs.c

	if len(certMsg.certificates) == 0 {
		c.sendAlert(alertIllegalParameter)
		return errors.New("tls: no certificates sent")
	}

	certs := make([]*x509.Certificate, len(certMsg.certificates))
	for i, asn1Data := range certMsg.certificates {
		cert, err := x509.ParseCertificate(asn1Data)
		if err != nil {
			c.sendAlert(alertBadCertificate)
			return errors.New("tls: failed to parse certificate from server: " + err.Error())
		}
		certs[i] = cert
	}

	if !c.config.InsecureSkipVerify {
		opts := x509.VerifyOptions{
			Roots:         c.config.RootCAs,
			CurrentTime:   c.config.time(),
			DNSName:       c.config.ServerName,
			Intermediates: x509.NewCertPool(),
		}

		for i, cert := range certs {
			if i == 0 {
				continue
			}
			opts.Intermediates.AddCert(cert)
		}
		var err error
		c.verifiedChains, err = certs[0].Verify(opts)
		if err != nil {
			c.sendAlert(alertBadCertificate)
			return err
		}
	}

	switch certs[0].PublicKey.(type) {
	case *rsa.PublicKey, *ecdsa.PublicKey:
		break
	default:
		c.sendAlert(alertUnsupportedCertificate)
		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
	}

	c.peerCertificates = certs
	return nil
}

Adam Langley's avatar
Adam Langley committed
900
901
902
903
func (hs *clientHandshakeState) establishKeys() error {
	c := hs.c

	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
904
		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
Adam Langley's avatar
Adam Langley committed
905
906
907
908
909
910
911
912
	var clientCipher, serverCipher interface{}
	var clientHash, serverHash macFunction
	if hs.suite.cipher != nil {
		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
		clientHash = hs.suite.mac(c.vers, clientMAC)
		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
		serverHash = hs.suite.mac(c.vers, serverMAC)
	} else {
913
914
		clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
		serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
Adam Langley's avatar
Adam Langley committed
915
916
917
918
919
920
921
	}

	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
	return nil
}

922
func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
Adam Langley's avatar
Adam Langley committed
923
924
	c := hs.c

925
926
927
928
	if c.vers < VersionTLS13 || !enableTLS13Handshake {
		if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
			return errors.New("tls: renegotiation extension missing")
		}
929

930
931
932
933
934
935
936
937
		if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
			var expectedRenegInfo []byte
			expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
			expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
			if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
				c.sendAlert(alertHandshakeFailure)
				return fmt.Errorf("tls: renegotiation mismatch")
			}
938
939
940
941
942
943
944
		}
	}

	if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
		if serverExtensions.customExtension != *expected {
			return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
		}
Adam Langley's avatar
Adam Langley committed
945
946
	}

David Benjamin's avatar
David Benjamin committed
947
948
	clientDidNPN := hs.hello.nextProtoNeg
	clientDidALPN := len(hs.hello.alpnProtocols) > 0
949
950
	serverHasNPN := serverExtensions.nextProtoNeg
	serverHasALPN := len(serverExtensions.alpnProtocol) > 0
David Benjamin's avatar
David Benjamin committed
951
952

	if !clientDidNPN && serverHasNPN {
Adam Langley's avatar
Adam Langley committed
953
		c.sendAlert(alertHandshakeFailure)
954
		return errors.New("server advertised unrequested NPN extension")
Adam Langley's avatar
Adam Langley committed
955
956
	}

David Benjamin's avatar
David Benjamin committed
957
958
	if !clientDidALPN && serverHasALPN {
		c.sendAlert(alertHandshakeFailure)
959
		return errors.New("server advertised unrequested ALPN extension")
David Benjamin's avatar
David Benjamin committed
960
961
962
963
	}

	if serverHasNPN && serverHasALPN {
		c.sendAlert(alertHandshakeFailure)
964
		return errors.New("server advertised both NPN and ALPN extensions")
David Benjamin's avatar
David Benjamin committed
965
966
967
	}

	if serverHasALPN {
968
		c.clientProtocol = serverExtensions.alpnProtocol
David Benjamin's avatar
David Benjamin committed
969
		c.clientProtocolFallback = false
970
		c.usedALPN = true
David Benjamin's avatar
David Benjamin committed
971
972
	}

973
974
975
976
977
	if serverHasNPN && c.vers >= VersionTLS13 && enableTLS13Handshake {
		c.sendAlert(alertHandshakeFailure)
		return errors.New("server advertised NPN over TLS 1.3")
	}

978
	if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
979
		c.sendAlert(alertHandshakeFailure)
980
		return errors.New("server advertised unrequested Channel ID extension")
981
982
	}

983
984
985
986
987
	if serverExtensions.channelIDRequested && c.vers >= VersionTLS13 && enableTLS13Handshake {
		c.sendAlert(alertHandshakeFailure)
		return errors.New("server advertised Channel ID over TLS 1.3")
	}

988
989
990
	if serverExtensions.srtpProtectionProfile != 0 {
		if serverExtensions.srtpMasterKeyIdentifier != "" {
			return errors.New("tls: server selected SRTP MKI value")
David Benjamin's avatar
David Benjamin committed
991
992
993
994
		}

		found := false
		for _, p := range c.config.SRTPProtectionProfiles {
995
			if p == serverExtensions.srtpProtectionProfile {
David Benjamin's avatar
David Benjamin committed
996
997
998
999
1000
				found = true
				break
			}
		}
		if !found {
1001
			return errors.New("tls: server advertised unsupported SRTP profile")
David Benjamin's avatar
David Benjamin committed
1002
1003
		}

1004
		c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
David Benjamin's avatar
David Benjamin committed
1005
1006
	}

1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
	return nil
}

func (hs *clientHandshakeState) serverResumedSession() bool {
	// If the server responded with the same sessionId then it means the
	// sessionTicket is being used to resume a TLS session.
	return hs.session != nil && hs.hello.sessionId != nil &&
		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
}

func (hs *clientHandshakeState) processServerHello() (bool, error) {
	c := hs.c

Adam Langley's avatar
Adam Langley committed
1020
	if hs.serverResumedSession() {
1021
1022
1023
1024
1025
1026
		// For test purposes, assert that the server never accepts the
		// resumption offer on renegotiation.
		if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
			return false, errors.New("tls: server resumed session on renegotiation")
		}

1027
		if hs.serverHello.extensions.sctList != nil {
1028
1029
1030
			return false, errors.New("tls: server sent SCT extension on session resumption")
		}

1031
		if hs.serverHello.extensions.ocspStapling {
1032
1033
1034
			return false, errors.New("tls: server sent OCSP extension on session resumption")
		}

Adam Langley's avatar
Adam Langley committed
1035
1036
1037
		// Restore masterSecret and peerCerts from previous state
		hs.masterSecret = hs.session.masterSecret
		c.peerCertificates = hs.session.serverCertificates
Adam Langley's avatar
Adam Langley committed
1038
		c.extendedMasterSecret = hs.session.extendedMasterSecret
1039
1040
		c.sctList = hs.session.sctList
		c.ocspResponse = hs.session.ocspResponse
1041
		hs.finishedHash.discardHandshakeBuffer()
Adam Langley's avatar
Adam Langley committed
1042
1043
		return true, nil
	}
1044

1045
1046
	if hs.serverHello.extensions.sctList != nil {
		c.sctList = hs.serverHello.extensions.sctList
1047
1048
	}

Adam Langley's avatar
Adam Langley committed
1049
1050
1051
	return false, nil
}

Adam Langley's avatar
Adam Langley committed
1052
func (hs *clientHandshakeState) readFinished(out []byte) error {
Adam Langley's avatar
Adam Langley committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
	c := hs.c

	c.readRecord(recordTypeChangeCipherSpec)
	if err := c.in.error(); err != nil {
		return err
	}

	msg, err := c.readHandshake()
	if err != nil {
		return err
	}
	serverFinished, ok := msg.(*finishedMsg)
	if !ok {
		c.sendAlert(alertUnexpectedMessage)
		return unexpectedMessageError(serverFinished, msg)
	}

1070
1071
1072
1073
1074
1075
1076
	if c.config.Bugs.EarlyChangeCipherSpec == 0 {
		verify := hs.finishedHash.serverSum(hs.masterSecret)
		if len(verify) != len(serverFinished.verifyData) ||
			subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
			c.sendAlert(alertHandshakeFailure)
			return errors.New("tls: server's Finished message was incorrect")
		}
Adam Langley's avatar
Adam Langley committed
1077
	}
Adam Langley's avatar
Adam Langley committed
1078
	c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
Adam Langley's avatar
Adam Langley committed
1079
	copy(out, serverFinished.verifyData)
1080
	hs.writeServerHash(serverFinished.marshal())
Adam Langley's avatar
Adam Langley committed
1081
1082
1083
1084
	return nil
}

func (hs *clientHandshakeState) readSessionTicket() error {
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
	c := hs.c

	// Create a session with no server identifier. Either a
	// session ID or session ticket will be attached.
	session := &ClientSessionState{
		vers:               c.vers,
		cipherSuite:        hs.suite.id,
		masterSecret:       hs.masterSecret,
		handshakeHash:      hs.finishedHash.server.Sum(nil),
		serverCertificates: c.peerCertificates,
1095
1096
		sctList:            c.sctList,
		ocspResponse:       c.ocspResponse,
1097
1098
	}

1099
	if !hs.serverHello.extensions.ticketSupported {
1100
1101
1102
		if c.config.Bugs.ExpectNewTicket {
			return errors.New("tls: expected new ticket")
		}
1103
1104
1105
1106
		if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
			session.sessionId = hs.serverHello.sessionId
			hs.session = session
		}
Adam Langley's avatar
Adam Langley committed
1107
1108
1109
		return nil
	}

1110
1111
1112
1113
	if c.vers == VersionSSL30 {
		return errors.New("tls: negotiated session tickets in SSL 3.0")
	}

Adam Langley's avatar
Adam Langley committed
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
	msg, err := c.readHandshake()
	if err != nil {
		return err
	}
	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
	if !ok {
		c.sendAlert(alertUnexpectedMessage)
		return unexpectedMessageError(sessionTicketMsg, msg)
	}

1124
1125
	session.sessionTicket = sessionTicketMsg.ticket
	hs.session = session
Adam Langley's avatar
Adam Langley committed
1126

1127
1128
	hs.writeServerHash(sessionTicketMsg.marshal())

Adam Langley's avatar
Adam Langley committed
1129
1130
1131
	return nil
}

Adam Langley's avatar
Adam Langley committed
1132
func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
Adam Langley's avatar
Adam Langley committed
1133
1134
	c := hs.c

David Benjamin's avatar
David Benjamin committed
1135
	var postCCSBytes []byte
1136
	seqno := hs.c.sendHandshakeSeq
1137
	if hs.serverHello.extensions.nextProtoNeg {
Adam Langley's avatar
Adam Langley committed
1138
		nextProto := new(nextProtoMsg)
1139
		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
Adam Langley's avatar
Adam Langley committed
1140
1141
1142
1143
		nextProto.proto = proto
		c.clientProtocol = proto
		c.clientProtocolFallback = fallback

David Benjamin's avatar
David Benjamin committed
1144
		nextProtoBytes := nextProto.marshal()
1145
1146
		hs.writeHash(nextProtoBytes, seqno)
		seqno++
David Benjamin's avatar
David Benjamin committed
1147
		postCCSBytes = append(postCCSBytes, nextProtoBytes...)
Adam Langley's avatar
Adam Langley committed
1148
1149
	}

1150
	if hs.serverHello.extensions.channelIDRequested {
1151
		channelIDMsg := new(channelIDMsg)
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
		if c.config.ChannelID.Curve != elliptic.P256() {
			return fmt.Errorf("tls: Channel ID is not on P-256.")
		}
		var resumeHash []byte
		if isResume {
			resumeHash = hs.session.handshakeHash
		}
		r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash))
		if err != nil {
			return err
		}
		channelID := make([]byte, 128)
		writeIntPadded(channelID[0:32], c.config.ChannelID.X)
		writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
		writeIntPadded(channelID[64:96], r)
		writeIntPadded(channelID[96:128], s)
1168
		channelIDMsg.channelID = channelID
1169
1170
1171

		c.channelID = &c.config.ChannelID.PublicKey

1172
1173
		channelIDMsgBytes := channelIDMsg.marshal()
		hs.writeHash(channelIDMsgBytes, seqno)
1174
		seqno++
1175
		postCCSBytes = append(postCCSBytes, channelIDMsgBytes...)
1176
1177
	}

Adam Langley's avatar
Adam Langley committed
1178
	finished := new(finishedMsg)
1179
1180
1181
1182
1183
	if c.config.Bugs.EarlyChangeCipherSpec == 2 {
		finished.verifyData = hs.finishedHash.clientSum(nil)
	} else {
		finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
	}
Adam Langley's avatar
Adam Langley committed
1184
	copy(out, finished.verifyData)
1185
1186
1187
	if c.config.Bugs.BadFinished {
		finished.verifyData[0]++
	}
Adam Langley's avatar
Adam Langley committed
1188
	c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
1189
1190
1191
	hs.finishedBytes = finished.marshal()
	hs.writeHash(hs.finishedBytes, seqno)
	postCCSBytes = append(postCCSBytes, hs.finishedBytes...)
David Benjamin's avatar
David Benjamin committed
1192
1193
1194
1195
1196

	if c.config.Bugs.FragmentAcrossChangeCipherSpec {
		c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
		postCCSBytes = postCCSBytes[5:]
	}
1197
	c.flushHandshake()
David Benjamin's avatar
David Benjamin committed
1198
1199
1200

	if !c.config.Bugs.SkipChangeCipherSpec &&
		c.config.Bugs.EarlyChangeCipherSpec == 0 {
1201
1202
1203
1204
1205
		ccs := []byte{1}
		if c.config.Bugs.BadChangeCipherSpec != nil {
			ccs = c.config.Bugs.BadChangeCipherSpec
		}
		c.writeRecord(recordTypeChangeCipherSpec, ccs)
David Benjamin's avatar
David Benjamin committed
1206
1207
	}

1208
1209
1210
	if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
		c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
	}
1211
1212
1213
1214
	if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
		c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
		return errors.New("tls: simulating post-CCS alert")
	}
1215

1216
1217
	if !c.config.Bugs.SkipFinished {
		c.writeRecord(recordTypeHandshake, postCCSBytes)
1218
		c.flushHandshake()
1219
	}
Adam Langley's avatar
Adam Langley committed
1220
1221
1222
	return nil
}

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
func (hs *clientHandshakeState) writeClientHash(msg []byte) {
	// writeClientHash is called before writeRecord.
	hs.writeHash(msg, hs.c.sendHandshakeSeq)
}

func (hs *clientHandshakeState) writeServerHash(msg []byte) {
	// writeServerHash is called after readHandshake.
	hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
}

func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
	if hs.c.isDTLS {
		// This is somewhat hacky. DTLS hashes a slightly different format.
		// First, the TLS header.
		hs.finishedHash.Write(msg[:4])
		// Then the sequence number and reassembled fragment offset (always 0).
		hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
		// Then the reassembled fragment (always equal to the message length).
		hs.finishedHash.Write(msg[1:4])
		// And then the message body.
		hs.finishedHash.Write(msg[4:])
	} else {
		hs.finishedHash.Write(msg)
	}
}

1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
// selectClientCertificate selects a certificate for use with the given
// certificate, or none if none match. It may return a particular certificate or
// nil on success, or an error on internal error.
func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
	// RFC 4346 on the certificateAuthorities field:
	// A list of the distinguished names of acceptable certificate
	// authorities. These distinguished names may specify a desired
	// distinguished name for a root CA or for a subordinate CA; thus, this
	// message can be used to describe both known roots and a desired
	// authorization space. If the certificate_authorities list is empty
	// then the client MAY send any certificate of the appropriate
	// ClientCertificateType, unless there is some external arrangement to
	// the contrary.

	var rsaAvail, ecdsaAvail bool
1264
1265
1266
1267
1268
1269
1270
1271
	if !certReq.hasRequestContext {
		for _, certType := range certReq.certificateTypes {
			switch certType {
			case CertTypeRSASign:
				rsaAvail = true
			case CertTypeECDSASign:
				ecdsaAvail = true
			}
1272
1273
1274
1275
1276
1277
1278
1279
		}
	}

	// We need to search our list of client certs for one
	// where SignatureAlgorithm is RSA and the Issuer is in
	// certReq.certificateAuthorities
findCert:
	for i, chain := range c.config.Certificates {
1280
		if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
1281
1282
1283
1284
1285
1286
			continue
		}

		// Ensure the private key supports one of the advertised
		// signature algorithms.
		if certReq.hasSignatureAlgorithm {
1287
			if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
				continue
			}
		}

		for j, cert := range chain.Certificate {
			x509Cert := chain.Leaf
			// parse the certificate if this isn't the leaf
			// node, or if chain.Leaf was nil
			if j != 0 || x509Cert == nil {
				var err error
				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
					c.sendAlert(alertInternalError)
					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
				}
			}