1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package runner
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/ecdsa"
11	"crypto/elliptic"
12	"crypto/rsa"
13	"crypto/subtle"
14	"crypto/x509"
15	"errors"
16	"fmt"
17	"io"
18	"math/big"
19	"net"
20	"strconv"
21	"time"
22)
23
24type clientHandshakeState struct {
25	c             *Conn
26	serverHello   *serverHelloMsg
27	hello         *clientHelloMsg
28	suite         *cipherSuite
29	finishedHash  finishedHash
30	keyShares     map[CurveID]ecdhCurve
31	masterSecret  []byte
32	session       *ClientSessionState
33	finishedBytes []byte
34}
35
36func (c *Conn) clientHandshake() error {
37	if c.config == nil {
38		c.config = defaultConfig()
39	}
40
41	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
42		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
43	}
44
45	c.sendHandshakeSeq = 0
46	c.recvHandshakeSeq = 0
47
48	nextProtosLength := 0
49	for _, proto := range c.config.NextProtos {
50		if l := len(proto); l > 255 {
51			return errors.New("tls: invalid NextProtos value")
52		} else {
53			nextProtosLength += 1 + l
54		}
55	}
56	if nextProtosLength > 0xffff {
57		return errors.New("tls: NextProtos values too large")
58	}
59
60	minVersion := c.config.minVersion(c.isDTLS)
61	maxVersion := c.config.maxVersion(c.isDTLS)
62	hello := &clientHelloMsg{
63		isDTLS:                  c.isDTLS,
64		vers:                    versionToWire(maxVersion, c.isDTLS),
65		compressionMethods:      []uint8{compressionNone},
66		random:                  make([]byte, 32),
67		ocspStapling:            !c.config.Bugs.NoOCSPStapling,
68		sctListSupported:        !c.config.Bugs.NoSignedCertificateTimestamps,
69		serverName:              c.config.ServerName,
70		supportedCurves:         c.config.curvePreferences(),
71		pskKEModes:              []byte{pskDHEKEMode},
72		supportedPoints:         []uint8{pointFormatUncompressed},
73		nextProtoNeg:            len(c.config.NextProtos) > 0,
74		secureRenegotiation:     []byte{},
75		alpnProtocols:           c.config.NextProtos,
76		duplicateExtension:      c.config.Bugs.DuplicateExtension,
77		channelIDSupported:      c.config.ChannelID != nil,
78		npnAfterAlpn:            c.config.Bugs.SwapNPNAndALPN,
79		extendedMasterSecret:    maxVersion >= VersionTLS10,
80		srtpProtectionProfiles:  c.config.SRTPProtectionProfiles,
81		srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
82		customExtension:         c.config.Bugs.CustomExtension,
83		pskBinderFirst:          c.config.Bugs.PSKBinderFirst,
84	}
85
86	disableEMS := c.config.Bugs.NoExtendedMasterSecret
87	if c.cipherSuite != nil {
88		disableEMS = c.config.Bugs.NoExtendedMasterSecretOnRenegotiation
89	}
90
91	if disableEMS {
92		hello.extendedMasterSecret = false
93	}
94
95	if c.config.Bugs.NoSupportedCurves {
96		hello.supportedCurves = nil
97	}
98
99	if len(c.config.Bugs.SendPSKKeyExchangeModes) != 0 {
100		hello.pskKEModes = c.config.Bugs.SendPSKKeyExchangeModes
101	}
102
103	if c.config.Bugs.SendCompressionMethods != nil {
104		hello.compressionMethods = c.config.Bugs.SendCompressionMethods
105	}
106
107	if c.config.Bugs.SendSupportedPointFormats != nil {
108		hello.supportedPoints = c.config.Bugs.SendSupportedPointFormats
109	}
110
111	if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
112		if c.config.Bugs.BadRenegotiationInfo {
113			hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
114			hello.secureRenegotiation[0] ^= 0x80
115		} else {
116			hello.secureRenegotiation = c.clientVerify
117		}
118	}
119
120	if c.noRenegotiationInfo() {
121		hello.secureRenegotiation = nil
122	}
123
124	var keyShares map[CurveID]ecdhCurve
125	if maxVersion >= VersionTLS13 {
126		keyShares = make(map[CurveID]ecdhCurve)
127		hello.hasKeyShares = true
128		hello.trailingKeyShareData = c.config.Bugs.TrailingKeyShareData
129		curvesToSend := c.config.defaultCurves()
130		for _, curveID := range hello.supportedCurves {
131			if !curvesToSend[curveID] {
132				continue
133			}
134			curve, ok := curveForCurveID(curveID)
135			if !ok {
136				continue
137			}
138			publicKey, err := curve.offer(c.config.rand())
139			if err != nil {
140				return err
141			}
142
143			if c.config.Bugs.SendCurve != 0 {
144				curveID = c.config.Bugs.SendCurve
145			}
146			if c.config.Bugs.InvalidECDHPoint {
147				publicKey[0] ^= 0xff
148			}
149
150			hello.keyShares = append(hello.keyShares, keyShareEntry{
151				group:       curveID,
152				keyExchange: publicKey,
153			})
154			keyShares[curveID] = curve
155
156			if c.config.Bugs.DuplicateKeyShares {
157				hello.keyShares = append(hello.keyShares, hello.keyShares[len(hello.keyShares)-1])
158			}
159		}
160
161		if c.config.Bugs.MissingKeyShare {
162			hello.hasKeyShares = false
163		}
164	}
165
166	possibleCipherSuites := c.config.cipherSuites()
167	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
168
169NextCipherSuite:
170	for _, suiteId := range possibleCipherSuites {
171		for _, suite := range cipherSuites {
172			if suite.id != suiteId {
173				continue
174			}
175			// Don't advertise TLS 1.2-only cipher suites unless
176			// we're attempting TLS 1.2.
177			if maxVersion < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
178				continue
179			}
180			// Don't advertise non-DTLS cipher suites in DTLS.
181			if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
182				continue
183			}
184			hello.cipherSuites = append(hello.cipherSuites, suiteId)
185			continue NextCipherSuite
186		}
187	}
188
189	if c.config.Bugs.AdvertiseAllConfiguredCiphers {
190		hello.cipherSuites = possibleCipherSuites
191	}
192
193	if c.config.Bugs.SendRenegotiationSCSV {
194		hello.cipherSuites = append(hello.cipherSuites, renegotiationSCSV)
195	}
196
197	if c.config.Bugs.SendFallbackSCSV {
198		hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
199	}
200
201	_, err := io.ReadFull(c.config.rand(), hello.random)
202	if err != nil {
203		c.sendAlert(alertInternalError)
204		return errors.New("tls: short read from Rand: " + err.Error())
205	}
206
207	if maxVersion >= VersionTLS12 && !c.config.Bugs.NoSignatureAlgorithms {
208		hello.signatureAlgorithms = c.config.verifySignatureAlgorithms()
209	}
210
211	var session *ClientSessionState
212	var cacheKey string
213	sessionCache := c.config.ClientSessionCache
214
215	if sessionCache != nil {
216		hello.ticketSupported = !c.config.SessionTicketsDisabled
217
218		// Try to resume a previously negotiated TLS session, if
219		// available.
220		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
221		// TODO(nharper): Support storing more than one session
222		// ticket for TLS 1.3.
223		candidateSession, ok := sessionCache.Get(cacheKey)
224		if ok {
225			ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
226
227			// Check that the ciphersuite/version used for the
228			// previous session are still valid.
229			cipherSuiteOk := false
230			if candidateSession.vers <= VersionTLS12 {
231				for _, id := range hello.cipherSuites {
232					if id == candidateSession.cipherSuite {
233						cipherSuiteOk = true
234						break
235					}
236				}
237			} else {
238				// TLS 1.3 allows the cipher to change on
239				// resumption.
240				cipherSuiteOk = true
241			}
242
243			versOk := candidateSession.vers >= minVersion &&
244				candidateSession.vers <= maxVersion
245			if ticketOk && versOk && cipherSuiteOk {
246				session = candidateSession
247			}
248		}
249	}
250
251	var pskCipherSuite *cipherSuite
252	if session != nil && c.config.time().Before(session.ticketExpiration) {
253		ticket := session.sessionTicket
254		if c.config.Bugs.FilterTicket != nil && len(ticket) > 0 {
255			// Copy the ticket so FilterTicket may act in-place.
256			ticket = make([]byte, len(session.sessionTicket))
257			copy(ticket, session.sessionTicket)
258
259			ticket, err = c.config.Bugs.FilterTicket(ticket)
260			if err != nil {
261				return err
262			}
263		}
264
265		if session.vers >= VersionTLS13 || c.config.Bugs.SendBothTickets {
266			pskCipherSuite = cipherSuiteFromID(session.cipherSuite)
267			if pskCipherSuite == nil {
268				return errors.New("tls: client session cache has invalid cipher suite")
269			}
270			// TODO(nharper): Support sending more
271			// than one PSK identity.
272			ticketAge := uint32(c.config.time().Sub(session.ticketCreationTime) / time.Millisecond)
273			if c.config.Bugs.SendTicketAge != 0 {
274				ticketAge = uint32(c.config.Bugs.SendTicketAge / time.Millisecond)
275			}
276			psk := pskIdentity{
277				ticket:              ticket,
278				obfuscatedTicketAge: session.ticketAgeAdd + ticketAge,
279			}
280			hello.pskIdentities = []pskIdentity{psk}
281
282			if c.config.Bugs.ExtraPSKIdentity {
283				hello.pskIdentities = append(hello.pskIdentities, psk)
284			}
285		}
286
287		if session.vers < VersionTLS13 || c.config.Bugs.SendBothTickets {
288			if ticket != nil {
289				hello.sessionTicket = ticket
290				// A random session ID is used to detect when the
291				// server accepted the ticket and is resuming a session
292				// (see RFC 5077).
293				sessionIdLen := 16
294				if c.config.Bugs.TicketSessionIDLength != 0 {
295					sessionIdLen = c.config.Bugs.TicketSessionIDLength
296				}
297				if c.config.Bugs.EmptyTicketSessionID {
298					sessionIdLen = 0
299				}
300				hello.sessionId = make([]byte, sessionIdLen)
301				if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
302					c.sendAlert(alertInternalError)
303					return errors.New("tls: short read from Rand: " + err.Error())
304				}
305			} else {
306				hello.sessionId = session.sessionId
307			}
308		}
309	}
310
311	if maxVersion == VersionTLS13 && !c.config.Bugs.OmitSupportedVersions {
312		if hello.vers >= VersionTLS13 {
313			hello.vers = VersionTLS12
314		}
315		for version := maxVersion; version >= minVersion; version-- {
316			hello.supportedVersions = append(hello.supportedVersions, versionToWire(version, c.isDTLS))
317		}
318	}
319
320	if len(c.config.Bugs.SendSupportedVersions) > 0 {
321		hello.supportedVersions = c.config.Bugs.SendSupportedVersions
322	}
323
324	if c.config.Bugs.SendClientVersion != 0 {
325		hello.vers = c.config.Bugs.SendClientVersion
326	}
327
328	if c.config.Bugs.SendCipherSuites != nil {
329		hello.cipherSuites = c.config.Bugs.SendCipherSuites
330	}
331
332	var sendEarlyData bool
333	if len(hello.pskIdentities) > 0 && c.config.Bugs.SendEarlyData != nil {
334		hello.hasEarlyData = true
335		sendEarlyData = true
336	}
337	if c.config.Bugs.SendFakeEarlyDataLength > 0 {
338		hello.hasEarlyData = true
339	}
340	if c.config.Bugs.OmitEarlyDataExtension {
341		hello.hasEarlyData = false
342	}
343
344	var helloBytes []byte
345	if c.config.Bugs.SendV2ClientHello {
346		// Test that the peer left-pads random.
347		hello.random[0] = 0
348		v2Hello := &v2ClientHelloMsg{
349			vers:         hello.vers,
350			cipherSuites: hello.cipherSuites,
351			// No session resumption for V2ClientHello.
352			sessionId: nil,
353			challenge: hello.random[1:],
354		}
355		helloBytes = v2Hello.marshal()
356		c.writeV2Record(helloBytes)
357	} else {
358		if len(hello.pskIdentities) > 0 {
359			generatePSKBinders(hello, pskCipherSuite, session.masterSecret, []byte{}, c.config)
360		}
361		helloBytes = hello.marshal()
362
363		if c.config.Bugs.PartialClientFinishedWithClientHello {
364			// Include one byte of Finished. We can compute it
365			// without completing the handshake. This assumes we
366			// negotiate TLS 1.3 with no HelloRetryRequest or
367			// CertificateRequest.
368			toWrite := make([]byte, 0, len(helloBytes)+1)
369			toWrite = append(toWrite, helloBytes...)
370			toWrite = append(toWrite, typeFinished)
371			c.writeRecord(recordTypeHandshake, toWrite)
372		} else {
373			c.writeRecord(recordTypeHandshake, helloBytes)
374		}
375	}
376	c.flushHandshake()
377
378	if err := c.simulatePacketLoss(nil); err != nil {
379		return err
380	}
381	if c.config.Bugs.SendEarlyAlert {
382		c.sendAlert(alertHandshakeFailure)
383	}
384	if c.config.Bugs.SendFakeEarlyDataLength > 0 {
385		c.sendFakeEarlyData(c.config.Bugs.SendFakeEarlyDataLength)
386	}
387
388	// Derive early write keys and set Conn state to allow early writes.
389	if sendEarlyData {
390		finishedHash := newFinishedHash(session.vers, pskCipherSuite)
391		finishedHash.addEntropy(session.masterSecret)
392		finishedHash.Write(helloBytes)
393		earlyTrafficSecret := finishedHash.deriveSecret(earlyTrafficLabel)
394		c.out.useTrafficSecret(session.vers, pskCipherSuite, earlyTrafficSecret, clientWrite)
395		for _, earlyData := range c.config.Bugs.SendEarlyData {
396			if _, err := c.writeRecord(recordTypeApplicationData, earlyData); err != nil {
397				return err
398			}
399		}
400	}
401
402	msg, err := c.readHandshake()
403	if err != nil {
404		return err
405	}
406
407	if c.isDTLS {
408		helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
409		if ok {
410			if helloVerifyRequest.vers != versionToWire(VersionTLS10, c.isDTLS) {
411				// Per RFC 6347, the version field in
412				// HelloVerifyRequest SHOULD be always DTLS
413				// 1.0. Enforce this for testing purposes.
414				return errors.New("dtls: bad HelloVerifyRequest version")
415			}
416
417			hello.raw = nil
418			hello.cookie = helloVerifyRequest.cookie
419			helloBytes = hello.marshal()
420			c.writeRecord(recordTypeHandshake, helloBytes)
421			c.flushHandshake()
422
423			if err := c.simulatePacketLoss(nil); err != nil {
424				return err
425			}
426			msg, err = c.readHandshake()
427			if err != nil {
428				return err
429			}
430		}
431	}
432
433	var serverWireVersion uint16
434	switch m := msg.(type) {
435	case *helloRetryRequestMsg:
436		serverWireVersion = m.vers
437	case *serverHelloMsg:
438		serverWireVersion = m.vers
439	default:
440		c.sendAlert(alertUnexpectedMessage)
441		return fmt.Errorf("tls: received unexpected message of type %T when waiting for HelloRetryRequest or ServerHello", msg)
442	}
443
444	serverVersion, ok := wireToVersion(serverWireVersion, c.isDTLS)
445	if ok {
446		ok = c.config.isSupportedVersion(serverVersion, c.isDTLS)
447	}
448	if !ok {
449		c.sendAlert(alertProtocolVersion)
450		return fmt.Errorf("tls: server selected unsupported protocol version %x", c.vers)
451	}
452	c.vers = serverVersion
453	c.haveVers = true
454
455	helloRetryRequest, haveHelloRetryRequest := msg.(*helloRetryRequestMsg)
456	var secondHelloBytes []byte
457	if haveHelloRetryRequest {
458		c.out.resetCipher()
459		if len(helloRetryRequest.cookie) > 0 {
460			hello.tls13Cookie = helloRetryRequest.cookie
461		}
462
463		if c.config.Bugs.MisinterpretHelloRetryRequestCurve != 0 {
464			helloRetryRequest.hasSelectedGroup = true
465			helloRetryRequest.selectedGroup = c.config.Bugs.MisinterpretHelloRetryRequestCurve
466		}
467		if helloRetryRequest.hasSelectedGroup {
468			var hrrCurveFound bool
469			group := helloRetryRequest.selectedGroup
470			for _, curveID := range hello.supportedCurves {
471				if group == curveID {
472					hrrCurveFound = true
473					break
474				}
475			}
476			if !hrrCurveFound || keyShares[group] != nil {
477				c.sendAlert(alertHandshakeFailure)
478				return errors.New("tls: received invalid HelloRetryRequest")
479			}
480			curve, ok := curveForCurveID(group)
481			if !ok {
482				return errors.New("tls: Unable to get curve requested in HelloRetryRequest")
483			}
484			publicKey, err := curve.offer(c.config.rand())
485			if err != nil {
486				return err
487			}
488			keyShares[group] = curve
489			hello.keyShares = []keyShareEntry{{
490				group:       group,
491				keyExchange: publicKey,
492			}}
493		}
494
495		if c.config.Bugs.SecondClientHelloMissingKeyShare {
496			hello.hasKeyShares = false
497		}
498
499		hello.hasEarlyData = c.config.Bugs.SendEarlyDataOnSecondClientHello
500		hello.raw = nil
501
502		if len(hello.pskIdentities) > 0 {
503			generatePSKBinders(hello, pskCipherSuite, session.masterSecret, append(helloBytes, helloRetryRequest.marshal()...), c.config)
504		}
505		secondHelloBytes = hello.marshal()
506
507		if c.config.Bugs.InterleaveEarlyData {
508			c.sendFakeEarlyData(4)
509			c.writeRecord(recordTypeHandshake, secondHelloBytes[:16])
510			c.sendFakeEarlyData(4)
511			c.writeRecord(recordTypeHandshake, secondHelloBytes[16:])
512		} else {
513			c.writeRecord(recordTypeHandshake, secondHelloBytes)
514		}
515		c.flushHandshake()
516
517		if c.config.Bugs.SendEarlyDataOnSecondClientHello {
518			c.sendFakeEarlyData(4)
519		}
520
521		msg, err = c.readHandshake()
522		if err != nil {
523			return err
524		}
525	}
526
527	serverHello, ok := msg.(*serverHelloMsg)
528	if !ok {
529		c.sendAlert(alertUnexpectedMessage)
530		return unexpectedMessageError(serverHello, msg)
531	}
532
533	if serverWireVersion != serverHello.vers {
534		c.sendAlert(alertProtocolVersion)
535		return fmt.Errorf("tls: server sent non-matching version %x vs %x", serverWireVersion, serverHello.vers)
536	}
537
538	// Check for downgrade signals in the server random, per
539	// draft-ietf-tls-tls13-16, section 4.1.3.
540	if c.vers <= VersionTLS12 && c.config.maxVersion(c.isDTLS) >= VersionTLS13 {
541		if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS13) {
542			c.sendAlert(alertProtocolVersion)
543			return errors.New("tls: downgrade from TLS 1.3 detected")
544		}
545	}
546	if c.vers <= VersionTLS11 && c.config.maxVersion(c.isDTLS) >= VersionTLS12 {
547		if bytes.Equal(serverHello.random[len(serverHello.random)-8:], downgradeTLS12) {
548			c.sendAlert(alertProtocolVersion)
549			return errors.New("tls: downgrade from TLS 1.2 detected")
550		}
551	}
552
553	suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
554	if suite == nil {
555		c.sendAlert(alertHandshakeFailure)
556		return fmt.Errorf("tls: server selected an unsupported cipher suite")
557	}
558
559	if haveHelloRetryRequest && helloRetryRequest.hasSelectedGroup && helloRetryRequest.selectedGroup != serverHello.keyShare.group {
560		c.sendAlert(alertHandshakeFailure)
561		return errors.New("tls: ServerHello parameters did not match HelloRetryRequest")
562	}
563
564	hs := &clientHandshakeState{
565		c:            c,
566		serverHello:  serverHello,
567		hello:        hello,
568		suite:        suite,
569		finishedHash: newFinishedHash(c.vers, suite),
570		keyShares:    keyShares,
571		session:      session,
572	}
573
574	hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
575	if haveHelloRetryRequest {
576		hs.writeServerHash(helloRetryRequest.marshal())
577		hs.writeClientHash(secondHelloBytes)
578	}
579	hs.writeServerHash(hs.serverHello.marshal())
580
581	if c.vers >= VersionTLS13 {
582		if err := hs.doTLS13Handshake(); err != nil {
583			return err
584		}
585	} else {
586		if c.config.Bugs.EarlyChangeCipherSpec > 0 {
587			hs.establishKeys()
588			c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
589		}
590
591		if hs.serverHello.compressionMethod != compressionNone {
592			c.sendAlert(alertUnexpectedMessage)
593			return errors.New("tls: server selected unsupported compression format")
594		}
595
596		err = hs.processServerExtensions(&serverHello.extensions)
597		if err != nil {
598			return err
599		}
600
601		isResume, err := hs.processServerHello()
602		if err != nil {
603			return err
604		}
605
606		if isResume {
607			if c.config.Bugs.EarlyChangeCipherSpec == 0 {
608				if err := hs.establishKeys(); err != nil {
609					return err
610				}
611			}
612			if err := hs.readSessionTicket(); err != nil {
613				return err
614			}
615			if err := hs.readFinished(c.firstFinished[:]); err != nil {
616				return err
617			}
618			if err := hs.sendFinished(nil, isResume); err != nil {
619				return err
620			}
621		} else {
622			if err := hs.doFullHandshake(); err != nil {
623				return err
624			}
625			if err := hs.establishKeys(); err != nil {
626				return err
627			}
628			if err := hs.sendFinished(c.firstFinished[:], isResume); err != nil {
629				return err
630			}
631			// Most retransmits are triggered by a timeout, but the final
632			// leg of the handshake is retransmited upon re-receiving a
633			// Finished.
634			if err := c.simulatePacketLoss(func() {
635				c.sendHandshakeSeq--
636				c.writeRecord(recordTypeHandshake, hs.finishedBytes)
637				c.flushHandshake()
638			}); err != nil {
639				return err
640			}
641			if err := hs.readSessionTicket(); err != nil {
642				return err
643			}
644			if err := hs.readFinished(nil); err != nil {
645				return err
646			}
647		}
648
649		if sessionCache != nil && hs.session != nil && session != hs.session {
650			if c.config.Bugs.RequireSessionTickets && len(hs.session.sessionTicket) == 0 {
651				return errors.New("tls: new session used session IDs instead of tickets")
652			}
653			sessionCache.Put(cacheKey, hs.session)
654		}
655
656		c.didResume = isResume
657		c.exporterSecret = hs.masterSecret
658	}
659
660	c.handshakeComplete = true
661	c.cipherSuite = suite
662	copy(c.clientRandom[:], hs.hello.random)
663	copy(c.serverRandom[:], hs.serverHello.random)
664
665	return nil
666}
667
668func (hs *clientHandshakeState) doTLS13Handshake() error {
669	c := hs.c
670
671	// Once the PRF hash is known, TLS 1.3 does not require a handshake
672	// buffer.
673	hs.finishedHash.discardHandshakeBuffer()
674
675	zeroSecret := hs.finishedHash.zeroSecret()
676
677	// Resolve PSK and compute the early secret.
678	//
679	// TODO(davidben): This will need to be handled slightly earlier once
680	// 0-RTT is implemented.
681	if hs.serverHello.hasPSKIdentity {
682		// We send at most one PSK identity.
683		if hs.session == nil || hs.serverHello.pskIdentity != 0 {
684			c.sendAlert(alertUnknownPSKIdentity)
685			return errors.New("tls: server sent unknown PSK identity")
686		}
687		sessionCipher := cipherSuiteFromID(hs.session.cipherSuite)
688		if sessionCipher == nil || sessionCipher.hash() != hs.suite.hash() {
689			c.sendAlert(alertHandshakeFailure)
690			return errors.New("tls: server resumed an invalid session for the cipher suite")
691		}
692		hs.finishedHash.addEntropy(hs.session.masterSecret)
693		c.didResume = true
694	} else {
695		hs.finishedHash.addEntropy(zeroSecret)
696	}
697
698	if !hs.serverHello.hasKeyShare {
699		c.sendAlert(alertUnsupportedExtension)
700		return errors.New("tls: server omitted KeyShare on resumption.")
701	}
702
703	// Resolve ECDHE and compute the handshake secret.
704	if !c.config.Bugs.MissingKeyShare && !c.config.Bugs.SecondClientHelloMissingKeyShare {
705		curve, ok := hs.keyShares[hs.serverHello.keyShare.group]
706		if !ok {
707			c.sendAlert(alertHandshakeFailure)
708			return errors.New("tls: server selected an unsupported group")
709		}
710		c.curveID = hs.serverHello.keyShare.group
711
712		ecdheSecret, err := curve.finish(hs.serverHello.keyShare.keyExchange)
713		if err != nil {
714			return err
715		}
716		hs.finishedHash.addEntropy(ecdheSecret)
717	} else {
718		hs.finishedHash.addEntropy(zeroSecret)
719	}
720
721	// Derive handshake traffic keys and switch read key to handshake
722	// traffic key.
723	clientHandshakeTrafficSecret := hs.finishedHash.deriveSecret(clientHandshakeTrafficLabel)
724	serverHandshakeTrafficSecret := hs.finishedHash.deriveSecret(serverHandshakeTrafficLabel)
725	c.in.useTrafficSecret(c.vers, hs.suite, serverHandshakeTrafficSecret, serverWrite)
726
727	msg, err := c.readHandshake()
728	if err != nil {
729		return err
730	}
731
732	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
733	if !ok {
734		c.sendAlert(alertUnexpectedMessage)
735		return unexpectedMessageError(encryptedExtensions, msg)
736	}
737	hs.writeServerHash(encryptedExtensions.marshal())
738
739	err = hs.processServerExtensions(&encryptedExtensions.extensions)
740	if err != nil {
741		return err
742	}
743
744	var chainToSend *Certificate
745	var certReq *certificateRequestMsg
746	if c.didResume {
747		// Copy over authentication from the session.
748		c.peerCertificates = hs.session.serverCertificates
749		c.sctList = hs.session.sctList
750		c.ocspResponse = hs.session.ocspResponse
751	} else {
752		msg, err := c.readHandshake()
753		if err != nil {
754			return err
755		}
756
757		var ok bool
758		certReq, ok = msg.(*certificateRequestMsg)
759		if ok {
760			if len(certReq.requestContext) != 0 {
761				return errors.New("tls: non-empty certificate request context sent in handshake")
762			}
763
764			if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
765				certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
766			}
767
768			hs.writeServerHash(certReq.marshal())
769
770			chainToSend, err = selectClientCertificate(c, certReq)
771			if err != nil {
772				return err
773			}
774
775			msg, err = c.readHandshake()
776			if err != nil {
777				return err
778			}
779		}
780
781		certMsg, ok := msg.(*certificateMsg)
782		if !ok {
783			c.sendAlert(alertUnexpectedMessage)
784			return unexpectedMessageError(certMsg, msg)
785		}
786		hs.writeServerHash(certMsg.marshal())
787
788		// Check for unsolicited extensions.
789		for i, cert := range certMsg.certificates {
790			if c.config.Bugs.NoOCSPStapling && cert.ocspResponse != nil {
791				c.sendAlert(alertUnsupportedExtension)
792				return errors.New("tls: unexpected OCSP response in the server certificate")
793			}
794			if c.config.Bugs.NoSignedCertificateTimestamps && cert.sctList != nil {
795				c.sendAlert(alertUnsupportedExtension)
796				return errors.New("tls: unexpected SCT list in the server certificate")
797			}
798			if i > 0 && c.config.Bugs.ExpectNoExtensionsOnIntermediate && (cert.ocspResponse != nil || cert.sctList != nil) {
799				c.sendAlert(alertUnsupportedExtension)
800				return errors.New("tls: unexpected extensions in the server certificate")
801			}
802		}
803
804		if err := hs.verifyCertificates(certMsg); err != nil {
805			return err
806		}
807		leaf := c.peerCertificates[0]
808		c.ocspResponse = certMsg.certificates[0].ocspResponse
809		c.sctList = certMsg.certificates[0].sctList
810
811		msg, err = c.readHandshake()
812		if err != nil {
813			return err
814		}
815		certVerifyMsg, ok := msg.(*certificateVerifyMsg)
816		if !ok {
817			c.sendAlert(alertUnexpectedMessage)
818			return unexpectedMessageError(certVerifyMsg, msg)
819		}
820
821		c.peerSignatureAlgorithm = certVerifyMsg.signatureAlgorithm
822		input := hs.finishedHash.certificateVerifyInput(serverCertificateVerifyContextTLS13)
823		err = verifyMessage(c.vers, leaf.PublicKey, c.config, certVerifyMsg.signatureAlgorithm, input, certVerifyMsg.signature)
824		if err != nil {
825			return err
826		}
827
828		hs.writeServerHash(certVerifyMsg.marshal())
829	}
830
831	msg, err = c.readHandshake()
832	if err != nil {
833		return err
834	}
835	serverFinished, ok := msg.(*finishedMsg)
836	if !ok {
837		c.sendAlert(alertUnexpectedMessage)
838		return unexpectedMessageError(serverFinished, msg)
839	}
840
841	verify := hs.finishedHash.serverSum(serverHandshakeTrafficSecret)
842	if len(verify) != len(serverFinished.verifyData) ||
843		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
844		c.sendAlert(alertHandshakeFailure)
845		return errors.New("tls: server's Finished message was incorrect")
846	}
847
848	hs.writeServerHash(serverFinished.marshal())
849
850	// The various secrets do not incorporate the client's final leg, so
851	// derive them now before updating the handshake context.
852	hs.finishedHash.addEntropy(zeroSecret)
853	clientTrafficSecret := hs.finishedHash.deriveSecret(clientApplicationTrafficLabel)
854	serverTrafficSecret := hs.finishedHash.deriveSecret(serverApplicationTrafficLabel)
855	c.exporterSecret = hs.finishedHash.deriveSecret(exporterLabel)
856
857	// Switch to application data keys on read. In particular, any alerts
858	// from the client certificate are read over these keys.
859	c.in.useTrafficSecret(c.vers, hs.suite, serverTrafficSecret, serverWrite)
860
861	// If we're expecting 0.5-RTT messages from the server, read them
862	// now.
863	if encryptedExtensions.extensions.hasEarlyData {
864		// BoringSSL will always send two tickets half-RTT when
865		// negotiating 0-RTT.
866		for i := 0; i < shimConfig.HalfRTTTickets; i++ {
867			msg, err := c.readHandshake()
868			if err != nil {
869				return fmt.Errorf("tls: error reading half-RTT ticket: %s", err)
870			}
871			newSessionTicket, ok := msg.(*newSessionTicketMsg)
872			if !ok {
873				return errors.New("tls: expected half-RTT ticket")
874			}
875			if err := c.processTLS13NewSessionTicket(newSessionTicket, hs.suite); err != nil {
876				return err
877			}
878		}
879		for _, expectedMsg := range c.config.Bugs.ExpectHalfRTTData {
880			if err := c.readRecord(recordTypeApplicationData); err != nil {
881				return err
882			}
883			if !bytes.Equal(c.input.data[c.input.off:], expectedMsg) {
884				return errors.New("ExpectHalfRTTData: did not get expected message")
885			}
886			c.in.freeBlock(c.input)
887			c.input = nil
888		}
889	}
890
891	// Send EndOfEarlyData and then switch write key to handshake
892	// traffic key.
893	if c.out.cipher != nil && !c.config.Bugs.SkipEndOfEarlyData {
894		if c.config.Bugs.SendStrayEarlyHandshake {
895			helloRequest := new(helloRequestMsg)
896			c.writeRecord(recordTypeHandshake, helloRequest.marshal())
897		}
898		c.sendAlert(alertEndOfEarlyData)
899	}
900	c.out.useTrafficSecret(c.vers, hs.suite, clientHandshakeTrafficSecret, clientWrite)
901
902	if certReq != nil && !c.config.Bugs.SkipClientCertificate {
903		certMsg := &certificateMsg{
904			hasRequestContext: true,
905			requestContext:    certReq.requestContext,
906		}
907		if chainToSend != nil {
908			for _, certData := range chainToSend.Certificate {
909				certMsg.certificates = append(certMsg.certificates, certificateEntry{
910					data:           certData,
911					extraExtension: c.config.Bugs.SendExtensionOnCertificate,
912				})
913			}
914		}
915		hs.writeClientHash(certMsg.marshal())
916		c.writeRecord(recordTypeHandshake, certMsg.marshal())
917
918		if chainToSend != nil {
919			certVerify := &certificateVerifyMsg{
920				hasSignatureAlgorithm: true,
921			}
922
923			// Determine the hash to sign.
924			privKey := chainToSend.PrivateKey
925
926			var err error
927			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
928			if err != nil {
929				c.sendAlert(alertInternalError)
930				return err
931			}
932
933			input := hs.finishedHash.certificateVerifyInput(clientCertificateVerifyContextTLS13)
934			certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, input)
935			if err != nil {
936				c.sendAlert(alertInternalError)
937				return err
938			}
939			if c.config.Bugs.SendSignatureAlgorithm != 0 {
940				certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
941			}
942
943			hs.writeClientHash(certVerify.marshal())
944			c.writeRecord(recordTypeHandshake, certVerify.marshal())
945		}
946	}
947
948	if encryptedExtensions.extensions.channelIDRequested {
949		channelIDHash := crypto.SHA256.New()
950		channelIDHash.Write(hs.finishedHash.certificateVerifyInput(channelIDContextTLS13))
951		channelIDMsgBytes, err := hs.writeChannelIDMessage(channelIDHash.Sum(nil))
952		if err != nil {
953			return err
954		}
955		hs.writeClientHash(channelIDMsgBytes)
956		c.writeRecord(recordTypeHandshake, channelIDMsgBytes)
957	}
958
959	// Send a client Finished message.
960	finished := new(finishedMsg)
961	finished.verifyData = hs.finishedHash.clientSum(clientHandshakeTrafficSecret)
962	if c.config.Bugs.BadFinished {
963		finished.verifyData[0]++
964	}
965	hs.writeClientHash(finished.marshal())
966	if c.config.Bugs.PartialClientFinishedWithClientHello {
967		// The first byte has already been sent.
968		c.writeRecord(recordTypeHandshake, finished.marshal()[1:])
969	} else if c.config.Bugs.InterleaveEarlyData {
970		finishedBytes := finished.marshal()
971		c.sendFakeEarlyData(4)
972		c.writeRecord(recordTypeHandshake, finishedBytes[:1])
973		c.sendFakeEarlyData(4)
974		c.writeRecord(recordTypeHandshake, finishedBytes[1:])
975	} else {
976		c.writeRecord(recordTypeHandshake, finished.marshal())
977	}
978	if c.config.Bugs.SendExtraFinished {
979		c.writeRecord(recordTypeHandshake, finished.marshal())
980	}
981	c.flushHandshake()
982
983	// Switch to application data keys.
984	c.out.useTrafficSecret(c.vers, hs.suite, clientTrafficSecret, clientWrite)
985
986	c.resumptionSecret = hs.finishedHash.deriveSecret(resumptionLabel)
987	return nil
988}
989
990func (hs *clientHandshakeState) doFullHandshake() error {
991	c := hs.c
992
993	var leaf *x509.Certificate
994	if hs.suite.flags&suitePSK == 0 {
995		msg, err := c.readHandshake()
996		if err != nil {
997			return err
998		}
999
1000		certMsg, ok := msg.(*certificateMsg)
1001		if !ok {
1002			c.sendAlert(alertUnexpectedMessage)
1003			return unexpectedMessageError(certMsg, msg)
1004		}
1005		hs.writeServerHash(certMsg.marshal())
1006
1007		if err := hs.verifyCertificates(certMsg); err != nil {
1008			return err
1009		}
1010		leaf = c.peerCertificates[0]
1011	}
1012
1013	if hs.serverHello.extensions.ocspStapling {
1014		msg, err := c.readHandshake()
1015		if err != nil {
1016			return err
1017		}
1018		cs, ok := msg.(*certificateStatusMsg)
1019		if !ok {
1020			c.sendAlert(alertUnexpectedMessage)
1021			return unexpectedMessageError(cs, msg)
1022		}
1023		hs.writeServerHash(cs.marshal())
1024
1025		if cs.statusType == statusTypeOCSP {
1026			c.ocspResponse = cs.response
1027		}
1028	}
1029
1030	msg, err := c.readHandshake()
1031	if err != nil {
1032		return err
1033	}
1034
1035	keyAgreement := hs.suite.ka(c.vers)
1036
1037	skx, ok := msg.(*serverKeyExchangeMsg)
1038	if ok {
1039		hs.writeServerHash(skx.marshal())
1040		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
1041		if err != nil {
1042			c.sendAlert(alertUnexpectedMessage)
1043			return err
1044		}
1045		if ecdhe, ok := keyAgreement.(*ecdheKeyAgreement); ok {
1046			c.curveID = ecdhe.curveID
1047		}
1048
1049		c.peerSignatureAlgorithm = keyAgreement.peerSignatureAlgorithm()
1050
1051		msg, err = c.readHandshake()
1052		if err != nil {
1053			return err
1054		}
1055	}
1056
1057	var chainToSend *Certificate
1058	var certRequested bool
1059	certReq, ok := msg.(*certificateRequestMsg)
1060	if ok {
1061		certRequested = true
1062		if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
1063			certReq.signatureAlgorithms = c.config.signSignatureAlgorithms()
1064		}
1065
1066		hs.writeServerHash(certReq.marshal())
1067
1068		chainToSend, err = selectClientCertificate(c, certReq)
1069		if err != nil {
1070			return err
1071		}
1072
1073		msg, err = c.readHandshake()
1074		if err != nil {
1075			return err
1076		}
1077	}
1078
1079	shd, ok := msg.(*serverHelloDoneMsg)
1080	if !ok {
1081		c.sendAlert(alertUnexpectedMessage)
1082		return unexpectedMessageError(shd, msg)
1083	}
1084	hs.writeServerHash(shd.marshal())
1085
1086	// If the server requested a certificate then we have to send a
1087	// Certificate message in TLS, even if it's empty because we don't have
1088	// a certificate to send. In SSL 3.0, skip the message and send a
1089	// no_certificate warning alert.
1090	if certRequested {
1091		if c.vers == VersionSSL30 && chainToSend == nil {
1092			c.sendAlert(alertNoCertificate)
1093		} else if !c.config.Bugs.SkipClientCertificate {
1094			certMsg := new(certificateMsg)
1095			if chainToSend != nil {
1096				for _, certData := range chainToSend.Certificate {
1097					certMsg.certificates = append(certMsg.certificates, certificateEntry{
1098						data: certData,
1099					})
1100				}
1101			}
1102			hs.writeClientHash(certMsg.marshal())
1103			c.writeRecord(recordTypeHandshake, certMsg.marshal())
1104		}
1105	}
1106
1107	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
1108	if err != nil {
1109		c.sendAlert(alertInternalError)
1110		return err
1111	}
1112	if ckx != nil {
1113		if c.config.Bugs.EarlyChangeCipherSpec < 2 {
1114			hs.writeClientHash(ckx.marshal())
1115		}
1116		c.writeRecord(recordTypeHandshake, ckx.marshal())
1117	}
1118
1119	if hs.serverHello.extensions.extendedMasterSecret && c.vers >= VersionTLS10 {
1120		hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
1121		c.extendedMasterSecret = true
1122	} else {
1123		if c.config.Bugs.RequireExtendedMasterSecret {
1124			return errors.New("tls: extended master secret required but not supported by peer")
1125		}
1126		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
1127	}
1128
1129	if chainToSend != nil {
1130		certVerify := &certificateVerifyMsg{
1131			hasSignatureAlgorithm: c.vers >= VersionTLS12,
1132		}
1133
1134		// Determine the hash to sign.
1135		privKey := c.config.Certificates[0].PrivateKey
1136
1137		if certVerify.hasSignatureAlgorithm {
1138			certVerify.signatureAlgorithm, err = selectSignatureAlgorithm(c.vers, privKey, c.config, certReq.signatureAlgorithms)
1139			if err != nil {
1140				c.sendAlert(alertInternalError)
1141				return err
1142			}
1143		}
1144
1145		if c.vers > VersionSSL30 {
1146			certVerify.signature, err = signMessage(c.vers, privKey, c.config, certVerify.signatureAlgorithm, hs.finishedHash.buffer)
1147			if err == nil && c.config.Bugs.SendSignatureAlgorithm != 0 {
1148				certVerify.signatureAlgorithm = c.config.Bugs.SendSignatureAlgorithm
1149			}
1150		} else {
1151			// SSL 3.0's client certificate construction is
1152			// incompatible with signatureAlgorithm.
1153			rsaKey, ok := privKey.(*rsa.PrivateKey)
1154			if !ok {
1155				err = errors.New("unsupported signature type for client certificate")
1156			} else {
1157				digest := hs.finishedHash.hashForClientCertificateSSL3(hs.masterSecret)
1158				if c.config.Bugs.InvalidSignature {
1159					digest[0] ^= 0x80
1160				}
1161				certVerify.signature, err = rsa.SignPKCS1v15(c.config.rand(), rsaKey, crypto.MD5SHA1, digest)
1162			}
1163		}
1164		if err != nil {
1165			c.sendAlert(alertInternalError)
1166			return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
1167		}
1168
1169		hs.writeClientHash(certVerify.marshal())
1170		c.writeRecord(recordTypeHandshake, certVerify.marshal())
1171	}
1172	// flushHandshake will be called in sendFinished.
1173
1174	hs.finishedHash.discardHandshakeBuffer()
1175
1176	return nil
1177}
1178
1179func (hs *clientHandshakeState) verifyCertificates(certMsg *certificateMsg) error {
1180	c := hs.c
1181
1182	if len(certMsg.certificates) == 0 {
1183		c.sendAlert(alertIllegalParameter)
1184		return errors.New("tls: no certificates sent")
1185	}
1186
1187	certs := make([]*x509.Certificate, len(certMsg.certificates))
1188	for i, certEntry := range certMsg.certificates {
1189		cert, err := x509.ParseCertificate(certEntry.data)
1190		if err != nil {
1191			c.sendAlert(alertBadCertificate)
1192			return errors.New("tls: failed to parse certificate from server: " + err.Error())
1193		}
1194		certs[i] = cert
1195	}
1196
1197	if !c.config.InsecureSkipVerify {
1198		opts := x509.VerifyOptions{
1199			Roots:         c.config.RootCAs,
1200			CurrentTime:   c.config.time(),
1201			DNSName:       c.config.ServerName,
1202			Intermediates: x509.NewCertPool(),
1203		}
1204
1205		for i, cert := range certs {
1206			if i == 0 {
1207				continue
1208			}
1209			opts.Intermediates.AddCert(cert)
1210		}
1211		var err error
1212		c.verifiedChains, err = certs[0].Verify(opts)
1213		if err != nil {
1214			c.sendAlert(alertBadCertificate)
1215			return err
1216		}
1217	}
1218
1219	switch certs[0].PublicKey.(type) {
1220	case *rsa.PublicKey, *ecdsa.PublicKey:
1221		break
1222	default:
1223		c.sendAlert(alertUnsupportedCertificate)
1224		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
1225	}
1226
1227	c.peerCertificates = certs
1228	return nil
1229}
1230
1231func (hs *clientHandshakeState) establishKeys() error {
1232	c := hs.c
1233
1234	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
1235		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen(c.vers))
1236	var clientCipher, serverCipher interface{}
1237	var clientHash, serverHash macFunction
1238	if hs.suite.cipher != nil {
1239		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
1240		clientHash = hs.suite.mac(c.vers, clientMAC)
1241		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
1242		serverHash = hs.suite.mac(c.vers, serverMAC)
1243	} else {
1244		clientCipher = hs.suite.aead(c.vers, clientKey, clientIV)
1245		serverCipher = hs.suite.aead(c.vers, serverKey, serverIV)
1246	}
1247
1248	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
1249	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
1250	return nil
1251}
1252
1253func (hs *clientHandshakeState) processServerExtensions(serverExtensions *serverExtensions) error {
1254	c := hs.c
1255
1256	if c.vers < VersionTLS13 {
1257		if c.config.Bugs.RequireRenegotiationInfo && serverExtensions.secureRenegotiation == nil {
1258			return errors.New("tls: renegotiation extension missing")
1259		}
1260
1261		if len(c.clientVerify) > 0 && !c.noRenegotiationInfo() {
1262			var expectedRenegInfo []byte
1263			expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
1264			expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
1265			if !bytes.Equal(serverExtensions.secureRenegotiation, expectedRenegInfo) {
1266				c.sendAlert(alertHandshakeFailure)
1267				return fmt.Errorf("tls: renegotiation mismatch")
1268			}
1269		}
1270	} else if serverExtensions.secureRenegotiation != nil {
1271		return errors.New("tls: renegotiation info sent in TLS 1.3")
1272	}
1273
1274	if expected := c.config.Bugs.ExpectedCustomExtension; expected != nil {
1275		if serverExtensions.customExtension != *expected {
1276			return fmt.Errorf("tls: bad custom extension contents %q", serverExtensions.customExtension)
1277		}
1278	}
1279
1280	clientDidNPN := hs.hello.nextProtoNeg
1281	clientDidALPN := len(hs.hello.alpnProtocols) > 0
1282	serverHasNPN := serverExtensions.nextProtoNeg
1283	serverHasALPN := len(serverExtensions.alpnProtocol) > 0
1284
1285	if !clientDidNPN && serverHasNPN {
1286		c.sendAlert(alertHandshakeFailure)
1287		return errors.New("server advertised unrequested NPN extension")
1288	}
1289
1290	if !clientDidALPN && serverHasALPN {
1291		c.sendAlert(alertHandshakeFailure)
1292		return errors.New("server advertised unrequested ALPN extension")
1293	}
1294
1295	if serverHasNPN && serverHasALPN {
1296		c.sendAlert(alertHandshakeFailure)
1297		return errors.New("server advertised both NPN and ALPN extensions")
1298	}
1299
1300	if serverHasALPN {
1301		c.clientProtocol = serverExtensions.alpnProtocol
1302		c.clientProtocolFallback = false
1303		c.usedALPN = true
1304	}
1305
1306	if serverHasNPN && c.vers >= VersionTLS13 {
1307		c.sendAlert(alertHandshakeFailure)
1308		return errors.New("server advertised NPN over TLS 1.3")
1309	}
1310
1311	if !hs.hello.channelIDSupported && serverExtensions.channelIDRequested {
1312		c.sendAlert(alertHandshakeFailure)
1313		return errors.New("server advertised unrequested Channel ID extension")
1314	}
1315
1316	if serverExtensions.extendedMasterSecret && c.vers >= VersionTLS13 {
1317		return errors.New("tls: server advertised extended master secret over TLS 1.3")
1318	}
1319
1320	if serverExtensions.ticketSupported && c.vers >= VersionTLS13 {
1321		return errors.New("tls: server advertised ticket extension over TLS 1.3")
1322	}
1323
1324	if serverExtensions.ocspStapling && c.vers >= VersionTLS13 {
1325		return errors.New("tls: server advertised OCSP in ServerHello over TLS 1.3")
1326	}
1327
1328	if serverExtensions.ocspStapling && c.config.Bugs.NoOCSPStapling {
1329		return errors.New("tls: server advertised unrequested OCSP extension")
1330	}
1331
1332	if len(serverExtensions.sctList) > 0 && c.vers >= VersionTLS13 {
1333		return errors.New("tls: server advertised SCTs in ServerHello over TLS 1.3")
1334	}
1335
1336	if len(serverExtensions.sctList) > 0 && c.config.Bugs.NoSignedCertificateTimestamps {
1337		return errors.New("tls: server advertised unrequested SCTs")
1338	}
1339
1340	if serverExtensions.srtpProtectionProfile != 0 {
1341		if serverExtensions.srtpMasterKeyIdentifier != "" {
1342			return errors.New("tls: server selected SRTP MKI value")
1343		}
1344
1345		found := false
1346		for _, p := range c.config.SRTPProtectionProfiles {
1347			if p == serverExtensions.srtpProtectionProfile {
1348				found = true
1349				break
1350			}
1351		}
1352		if !found {
1353			return errors.New("tls: server advertised unsupported SRTP profile")
1354		}
1355
1356		c.srtpProtectionProfile = serverExtensions.srtpProtectionProfile
1357	}
1358
1359	if c.vers >= VersionTLS13 && c.didResume {
1360		if c.config.Bugs.ExpectEarlyDataAccepted && !serverExtensions.hasEarlyData {
1361			c.sendAlert(alertHandshakeFailure)
1362			return errors.New("tls: server did not accept early data when expected")
1363		}
1364
1365		if !c.config.Bugs.ExpectEarlyDataAccepted && serverExtensions.hasEarlyData {
1366			c.sendAlert(alertHandshakeFailure)
1367			return errors.New("tls: server accepted early data when not expected")
1368		}
1369	}
1370
1371	return nil
1372}
1373
1374func (hs *clientHandshakeState) serverResumedSession() bool {
1375	// If the server responded with the same sessionId then it means the
1376	// sessionTicket is being used to resume a TLS session.
1377	//
1378	// Note that, if hs.hello.sessionId is a non-nil empty array, this will
1379	// accept an empty session ID from the server as resumption. See
1380	// EmptyTicketSessionID.
1381	return hs.session != nil && hs.hello.sessionId != nil &&
1382		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
1383}
1384
1385func (hs *clientHandshakeState) processServerHello() (bool, error) {
1386	c := hs.c
1387
1388	if hs.serverResumedSession() {
1389		// For test purposes, assert that the server never accepts the
1390		// resumption offer on renegotiation.
1391		if c.cipherSuite != nil && c.config.Bugs.FailIfResumeOnRenego {
1392			return false, errors.New("tls: server resumed session on renegotiation")
1393		}
1394
1395		if hs.serverHello.extensions.sctList != nil {
1396			return false, errors.New("tls: server sent SCT extension on session resumption")
1397		}
1398
1399		if hs.serverHello.extensions.ocspStapling {
1400			return false, errors.New("tls: server sent OCSP extension on session resumption")
1401		}
1402
1403		// Restore masterSecret and peerCerts from previous state
1404		hs.masterSecret = hs.session.masterSecret
1405		c.peerCertificates = hs.session.serverCertificates
1406		c.extendedMasterSecret = hs.session.extendedMasterSecret
1407		c.sctList = hs.session.sctList
1408		c.ocspResponse = hs.session.ocspResponse
1409		hs.finishedHash.discardHandshakeBuffer()
1410		return true, nil
1411	}
1412
1413	if hs.serverHello.extensions.sctList != nil {
1414		c.sctList = hs.serverHello.extensions.sctList
1415	}
1416
1417	return false, nil
1418}
1419
1420func (hs *clientHandshakeState) readFinished(out []byte) error {
1421	c := hs.c
1422
1423	c.readRecord(recordTypeChangeCipherSpec)
1424	if err := c.in.error(); err != nil {
1425		return err
1426	}
1427
1428	msg, err := c.readHandshake()
1429	if err != nil {
1430		return err
1431	}
1432	serverFinished, ok := msg.(*finishedMsg)
1433	if !ok {
1434		c.sendAlert(alertUnexpectedMessage)
1435		return unexpectedMessageError(serverFinished, msg)
1436	}
1437
1438	if c.config.Bugs.EarlyChangeCipherSpec == 0 {
1439		verify := hs.finishedHash.serverSum(hs.masterSecret)
1440		if len(verify) != len(serverFinished.verifyData) ||
1441			subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
1442			c.sendAlert(alertHandshakeFailure)
1443			return errors.New("tls: server's Finished message was incorrect")
1444		}
1445	}
1446	c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
1447	copy(out, serverFinished.verifyData)
1448	hs.writeServerHash(serverFinished.marshal())
1449	return nil
1450}
1451
1452func (hs *clientHandshakeState) readSessionTicket() error {
1453	c := hs.c
1454
1455	// Create a session with no server identifier. Either a
1456	// session ID or session ticket will be attached.
1457	session := &ClientSessionState{
1458		vers:               c.vers,
1459		cipherSuite:        hs.suite.id,
1460		masterSecret:       hs.masterSecret,
1461		handshakeHash:      hs.finishedHash.Sum(),
1462		serverCertificates: c.peerCertificates,
1463		sctList:            c.sctList,
1464		ocspResponse:       c.ocspResponse,
1465		ticketExpiration:   c.config.time().Add(time.Duration(7 * 24 * time.Hour)),
1466	}
1467
1468	if !hs.serverHello.extensions.ticketSupported {
1469		if c.config.Bugs.ExpectNewTicket {
1470			return errors.New("tls: expected new ticket")
1471		}
1472		if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
1473			session.sessionId = hs.serverHello.sessionId
1474			hs.session = session
1475		}
1476		return nil
1477	}
1478
1479	if c.vers == VersionSSL30 {
1480		return errors.New("tls: negotiated session tickets in SSL 3.0")
1481	}
1482
1483	msg, err := c.readHandshake()
1484	if err != nil {
1485		return err
1486	}
1487	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
1488	if !ok {
1489		c.sendAlert(alertUnexpectedMessage)
1490		return unexpectedMessageError(sessionTicketMsg, msg)
1491	}
1492
1493	session.sessionTicket = sessionTicketMsg.ticket
1494	hs.session = session
1495
1496	hs.writeServerHash(sessionTicketMsg.marshal())
1497
1498	return nil
1499}
1500
1501func (hs *clientHandshakeState) sendFinished(out []byte, isResume bool) error {
1502	c := hs.c
1503
1504	var postCCSMsgs [][]byte
1505	seqno := hs.c.sendHandshakeSeq
1506	if hs.serverHello.extensions.nextProtoNeg {
1507		nextProto := new(nextProtoMsg)
1508		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.extensions.nextProtos)
1509		nextProto.proto = proto
1510		c.clientProtocol = proto
1511		c.clientProtocolFallback = fallback
1512
1513		nextProtoBytes := nextProto.marshal()
1514		hs.writeHash(nextProtoBytes, seqno)
1515		seqno++
1516		postCCSMsgs = append(postCCSMsgs, nextProtoBytes)
1517	}
1518
1519	if hs.serverHello.extensions.channelIDRequested {
1520		var resumeHash []byte
1521		if isResume {
1522			resumeHash = hs.session.handshakeHash
1523		}
1524		channelIDMsgBytes, err := hs.writeChannelIDMessage(hs.finishedHash.hashForChannelID(resumeHash))
1525		if err != nil {
1526			return err
1527		}
1528		hs.writeHash(channelIDMsgBytes, seqno)
1529		seqno++
1530		postCCSMsgs = append(postCCSMsgs, channelIDMsgBytes)
1531	}
1532
1533	finished := new(finishedMsg)
1534	if c.config.Bugs.EarlyChangeCipherSpec == 2 {
1535		finished.verifyData = hs.finishedHash.clientSum(nil)
1536	} else {
1537		finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
1538	}
1539	copy(out, finished.verifyData)
1540	if c.config.Bugs.BadFinished {
1541		finished.verifyData[0]++
1542	}
1543	c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
1544	hs.finishedBytes = finished.marshal()
1545	hs.writeHash(hs.finishedBytes, seqno)
1546	postCCSMsgs = append(postCCSMsgs, hs.finishedBytes)
1547
1548	if c.config.Bugs.FragmentAcrossChangeCipherSpec {
1549		c.writeRecord(recordTypeHandshake, postCCSMsgs[0][:5])
1550		postCCSMsgs[0] = postCCSMsgs[0][5:]
1551	} else if c.config.Bugs.SendUnencryptedFinished {
1552		c.writeRecord(recordTypeHandshake, postCCSMsgs[0])
1553		postCCSMsgs = postCCSMsgs[1:]
1554	}
1555	c.flushHandshake()
1556
1557	if !c.config.Bugs.SkipChangeCipherSpec &&
1558		c.config.Bugs.EarlyChangeCipherSpec == 0 {
1559		ccs := []byte{1}
1560		if c.config.Bugs.BadChangeCipherSpec != nil {
1561			ccs = c.config.Bugs.BadChangeCipherSpec
1562		}
1563		c.writeRecord(recordTypeChangeCipherSpec, ccs)
1564	}
1565
1566	if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
1567		c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
1568	}
1569	if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
1570		c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
1571		return errors.New("tls: simulating post-CCS alert")
1572	}
1573
1574	if !c.config.Bugs.SkipFinished {
1575		for _, msg := range postCCSMsgs {
1576			c.writeRecord(recordTypeHandshake, msg)
1577		}
1578
1579		if c.config.Bugs.SendExtraFinished {
1580			c.writeRecord(recordTypeHandshake, finished.marshal())
1581		}
1582
1583		c.flushHandshake()
1584	}
1585	return nil
1586}
1587
1588func (hs *clientHandshakeState) writeChannelIDMessage(channelIDHash []byte) ([]byte, error) {
1589	c := hs.c
1590	channelIDMsg := new(channelIDMsg)
1591	if c.config.ChannelID.Curve != elliptic.P256() {
1592		return nil, fmt.Errorf("tls: Channel ID is not on P-256.")
1593	}
1594	r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, channelIDHash)
1595	if err != nil {
1596		return nil, err
1597	}
1598	channelID := make([]byte, 128)
1599	writeIntPadded(channelID[0:32], c.config.ChannelID.X)
1600	writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
1601	writeIntPadded(channelID[64:96], r)
1602	writeIntPadded(channelID[96:128], s)
1603	if c.config.Bugs.InvalidChannelIDSignature {
1604		channelID[64] ^= 1
1605	}
1606	channelIDMsg.channelID = channelID
1607
1608	c.channelID = &c.config.ChannelID.PublicKey
1609
1610	return channelIDMsg.marshal(), nil
1611}
1612
1613func (hs *clientHandshakeState) writeClientHash(msg []byte) {
1614	// writeClientHash is called before writeRecord.
1615	hs.writeHash(msg, hs.c.sendHandshakeSeq)
1616}
1617
1618func (hs *clientHandshakeState) writeServerHash(msg []byte) {
1619	// writeServerHash is called after readHandshake.
1620	hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
1621}
1622
1623func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
1624	if hs.c.isDTLS {
1625		// This is somewhat hacky. DTLS hashes a slightly different format.
1626		// First, the TLS header.
1627		hs.finishedHash.Write(msg[:4])
1628		// Then the sequence number and reassembled fragment offset (always 0).
1629		hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
1630		// Then the reassembled fragment (always equal to the message length).
1631		hs.finishedHash.Write(msg[1:4])
1632		// And then the message body.
1633		hs.finishedHash.Write(msg[4:])
1634	} else {
1635		hs.finishedHash.Write(msg)
1636	}
1637}
1638
1639// selectClientCertificate selects a certificate for use with the given
1640// certificate, or none if none match. It may return a particular certificate or
1641// nil on success, or an error on internal error.
1642func selectClientCertificate(c *Conn, certReq *certificateRequestMsg) (*Certificate, error) {
1643	// RFC 4346 on the certificateAuthorities field:
1644	// A list of the distinguished names of acceptable certificate
1645	// authorities. These distinguished names may specify a desired
1646	// distinguished name for a root CA or for a subordinate CA; thus, this
1647	// message can be used to describe both known roots and a desired
1648	// authorization space. If the certificate_authorities list is empty
1649	// then the client MAY send any certificate of the appropriate
1650	// ClientCertificateType, unless there is some external arrangement to
1651	// the contrary.
1652
1653	var rsaAvail, ecdsaAvail bool
1654	if !certReq.hasRequestContext {
1655		for _, certType := range certReq.certificateTypes {
1656			switch certType {
1657			case CertTypeRSASign:
1658				rsaAvail = true
1659			case CertTypeECDSASign:
1660				ecdsaAvail = true
1661			}
1662		}
1663	}
1664
1665	// We need to search our list of client certs for one
1666	// where SignatureAlgorithm is RSA and the Issuer is in
1667	// certReq.certificateAuthorities
1668findCert:
1669	for i, chain := range c.config.Certificates {
1670		if !certReq.hasRequestContext && !rsaAvail && !ecdsaAvail {
1671			continue
1672		}
1673
1674		// Ensure the private key supports one of the advertised
1675		// signature algorithms.
1676		if certReq.hasSignatureAlgorithm {
1677			if _, err := selectSignatureAlgorithm(c.vers, chain.PrivateKey, c.config, certReq.signatureAlgorithms); err != nil {
1678				continue
1679			}
1680		}
1681
1682		for j, cert := range chain.Certificate {
1683			x509Cert := chain.Leaf
1684			// parse the certificate if this isn't the leaf
1685			// node, or if chain.Leaf was nil
1686			if j != 0 || x509Cert == nil {
1687				var err error
1688				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
1689					c.sendAlert(alertInternalError)
1690					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
1691				}
1692			}
1693
1694			if !certReq.hasRequestContext {
1695				switch {
1696				case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
1697				case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
1698				default:
1699					continue findCert
1700				}
1701			}
1702
1703			if expected := c.config.Bugs.ExpectCertificateReqNames; expected != nil {
1704				if !eqByteSlices(expected, certReq.certificateAuthorities) {
1705					return nil, fmt.Errorf("tls: CertificateRequest names differed, got %#v but expected %#v", certReq.certificateAuthorities, expected)
1706				}
1707			}
1708
1709			return &chain, nil
1710		}
1711	}
1712
1713	return nil, nil
1714}
1715
1716// clientSessionCacheKey returns a key used to cache sessionTickets that could
1717// be used to resume previously negotiated TLS sessions with a server.
1718func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
1719	if len(config.ServerName) > 0 {
1720		return config.ServerName
1721	}
1722	return serverAddr.String()
1723}
1724
1725// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
1726// given list of possible protocols and a list of the preference order. The
1727// first list must not be empty. It returns the resulting protocol and flag
1728// indicating if the fallback case was reached.
1729func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
1730	for _, s := range preferenceProtos {
1731		for _, c := range protos {
1732			if s == c {
1733				return s, false
1734			}
1735		}
1736	}
1737
1738	return protos[0], true
1739}
1740
1741// writeIntPadded writes x into b, padded up with leading zeros as
1742// needed.
1743func writeIntPadded(b []byte, x *big.Int) {
1744	for i := range b {
1745		b[i] = 0
1746	}
1747	xb := x.Bytes()
1748	copy(b[len(b)-len(xb):], xb)
1749}
1750
1751func generatePSKBinders(hello *clientHelloMsg, pskCipherSuite *cipherSuite, psk, transcript []byte, config *Config) {
1752	if config.Bugs.SendNoPSKBinder {
1753		return
1754	}
1755
1756	binderLen := pskCipherSuite.hash().Size()
1757	if config.Bugs.SendShortPSKBinder {
1758		binderLen--
1759	}
1760
1761	numBinders := 1
1762	if config.Bugs.SendExtraPSKBinder {
1763		numBinders++
1764	}
1765
1766	// Fill hello.pskBinders with appropriate length arrays of zeros so the
1767	// length prefixes are correct when computing the binder over the truncated
1768	// ClientHello message.
1769	hello.pskBinders = make([][]byte, numBinders)
1770	for i := range hello.pskBinders {
1771		hello.pskBinders[i] = make([]byte, binderLen)
1772	}
1773
1774	helloBytes := hello.marshal()
1775	binderSize := len(hello.pskBinders)*(binderLen+1) + 2
1776	truncatedHello := helloBytes[:len(helloBytes)-binderSize]
1777	binder := computePSKBinder(psk, resumptionPSKBinderLabel, pskCipherSuite, transcript, truncatedHello)
1778	if config.Bugs.SendShortPSKBinder {
1779		binder = binder[:binderLen]
1780	}
1781	if config.Bugs.SendInvalidPSKBinder {
1782		binder[0] ^= 1
1783	}
1784
1785	for i := range hello.pskBinders {
1786		hello.pskBinders[i] = binder
1787	}
1788
1789	hello.raw = nil
1790}
1791