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 tls
6
7import (
8	"bytes"
9	"crypto"
10	"crypto/ecdsa"
11	"crypto/ed25519"
12	"crypto/rsa"
13	"crypto/subtle"
14	"crypto/x509"
15	"errors"
16	"fmt"
17	"io"
18	"net"
19	"strings"
20	"sync/atomic"
21	"time"
22)
23
24type clientHandshakeState struct {
25	c            *Conn
26	serverHello  *serverHelloMsg
27	hello        *clientHelloMsg
28	suite        *cipherSuite
29	finishedHash finishedHash
30	masterSecret []byte
31	session      *ClientSessionState
32}
33
34func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
35	config := c.config
36	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
37		return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
38	}
39
40	nextProtosLength := 0
41	for _, proto := range config.NextProtos {
42		if l := len(proto); l == 0 || l > 255 {
43			return nil, nil, errors.New("tls: invalid NextProtos value")
44		} else {
45			nextProtosLength += 1 + l
46		}
47	}
48	if nextProtosLength > 0xffff {
49		return nil, nil, errors.New("tls: NextProtos values too large")
50	}
51
52	supportedVersions := config.supportedVersions()
53	if len(supportedVersions) == 0 {
54		return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
55	}
56
57	clientHelloVersion := supportedVersions[0]
58	// The version at the beginning of the ClientHello was capped at TLS 1.2
59	// for compatibility reasons. The supported_versions extension is used
60	// to negotiate versions now. See RFC 8446, Section 4.2.1.
61	if clientHelloVersion > VersionTLS12 {
62		clientHelloVersion = VersionTLS12
63	}
64
65	hello := &clientHelloMsg{
66		vers:                         clientHelloVersion,
67		compressionMethods:           []uint8{compressionNone},
68		random:                       make([]byte, 32),
69		sessionId:                    make([]byte, 32),
70		ocspStapling:                 true,
71		scts:                         true,
72		serverName:                   hostnameInSNI(config.ServerName),
73		supportedCurves:              config.curvePreferences(),
74		supportedPoints:              []uint8{pointFormatUncompressed},
75		secureRenegotiationSupported: true,
76		alpnProtocols:                config.NextProtos,
77		supportedVersions:            supportedVersions,
78	}
79
80	if c.handshakes > 0 {
81		hello.secureRenegotiation = c.clientFinished[:]
82	}
83
84	possibleCipherSuites := config.cipherSuites()
85	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
86
87	for _, suiteId := range possibleCipherSuites {
88		for _, suite := range cipherSuites {
89			if suite.id != suiteId {
90				continue
91			}
92			// Don't advertise TLS 1.2-only cipher suites unless
93			// we're attempting TLS 1.2.
94			if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
95				break
96			}
97			hello.cipherSuites = append(hello.cipherSuites, suiteId)
98			break
99		}
100	}
101
102	_, err := io.ReadFull(config.rand(), hello.random)
103	if err != nil {
104		return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
105	}
106
107	// A random session ID is used to detect when the server accepted a ticket
108	// and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
109	// a compatibility measure (see RFC 8446, Section 4.1.2).
110	if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
111		return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
112	}
113
114	if hello.vers >= VersionTLS12 {
115		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
116	}
117
118	var params ecdheParameters
119	if hello.supportedVersions[0] == VersionTLS13 {
120		hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13()...)
121
122		curveID := config.curvePreferences()[0]
123		if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
124			return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
125		}
126		params, err = generateECDHEParameters(config.rand(), curveID)
127		if err != nil {
128			return nil, nil, err
129		}
130		hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
131	}
132
133	return hello, params, nil
134}
135
136func (c *Conn) clientHandshake() (err error) {
137	if c.config == nil {
138		c.config = defaultConfig()
139	}
140
141	// This may be a renegotiation handshake, in which case some fields
142	// need to be reset.
143	c.didResume = false
144
145	hello, ecdheParams, err := c.makeClientHello()
146	if err != nil {
147		return err
148	}
149
150	cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
151	if cacheKey != "" && session != nil {
152		defer func() {
153			// If we got a handshake failure when resuming a session, throw away
154			// the session ticket. See RFC 5077, Section 3.2.
155			//
156			// RFC 8446 makes no mention of dropping tickets on failure, but it
157			// does require servers to abort on invalid binders, so we need to
158			// delete tickets to recover from a corrupted PSK.
159			if err != nil {
160				c.config.ClientSessionCache.Put(cacheKey, nil)
161			}
162		}()
163	}
164
165	if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
166		return err
167	}
168
169	msg, err := c.readHandshake()
170	if err != nil {
171		return err
172	}
173
174	serverHello, ok := msg.(*serverHelloMsg)
175	if !ok {
176		c.sendAlert(alertUnexpectedMessage)
177		return unexpectedMessageError(serverHello, msg)
178	}
179
180	if err := c.pickTLSVersion(serverHello); err != nil {
181		return err
182	}
183
184	if c.vers == VersionTLS13 {
185		hs := &clientHandshakeStateTLS13{
186			c:           c,
187			serverHello: serverHello,
188			hello:       hello,
189			ecdheParams: ecdheParams,
190			session:     session,
191			earlySecret: earlySecret,
192			binderKey:   binderKey,
193		}
194
195		// In TLS 1.3, session tickets are delivered after the handshake.
196		return hs.handshake()
197	}
198
199	hs := &clientHandshakeState{
200		c:           c,
201		serverHello: serverHello,
202		hello:       hello,
203		session:     session,
204	}
205
206	if err := hs.handshake(); err != nil {
207		return err
208	}
209
210	// If we had a successful handshake and hs.session is different from
211	// the one already cached - cache a new one.
212	if cacheKey != "" && hs.session != nil && session != hs.session {
213		c.config.ClientSessionCache.Put(cacheKey, hs.session)
214	}
215
216	return nil
217}
218
219func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
220	session *ClientSessionState, earlySecret, binderKey []byte) {
221	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
222		return "", nil, nil, nil
223	}
224
225	hello.ticketSupported = true
226
227	if hello.supportedVersions[0] == VersionTLS13 {
228		// Require DHE on resumption as it guarantees forward secrecy against
229		// compromise of the session ticket key. See RFC 8446, Section 4.2.9.
230		hello.pskModes = []uint8{pskModeDHE}
231	}
232
233	// Session resumption is not allowed if renegotiating because
234	// renegotiation is primarily used to allow a client to send a client
235	// certificate, which would be skipped if session resumption occurred.
236	if c.handshakes != 0 {
237		return "", nil, nil, nil
238	}
239
240	// Try to resume a previously negotiated TLS session, if available.
241	cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
242	session, ok := c.config.ClientSessionCache.Get(cacheKey)
243	if !ok || session == nil {
244		return cacheKey, nil, nil, nil
245	}
246
247	// Check that version used for the previous session is still valid.
248	versOk := false
249	for _, v := range hello.supportedVersions {
250		if v == session.vers {
251			versOk = true
252			break
253		}
254	}
255	if !versOk {
256		return cacheKey, nil, nil, nil
257	}
258
259	// Check that the cached server certificate is not expired, and that it's
260	// valid for the ServerName. This should be ensured by the cache key, but
261	// protect the application from a faulty ClientSessionCache implementation.
262	if !c.config.InsecureSkipVerify {
263		if len(session.verifiedChains) == 0 {
264			// The original connection had InsecureSkipVerify, while this doesn't.
265			return cacheKey, nil, nil, nil
266		}
267		serverCert := session.serverCertificates[0]
268		if c.config.time().After(serverCert.NotAfter) {
269			// Expired certificate, delete the entry.
270			c.config.ClientSessionCache.Put(cacheKey, nil)
271			return cacheKey, nil, nil, nil
272		}
273		if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
274			return cacheKey, nil, nil, nil
275		}
276	}
277
278	if session.vers != VersionTLS13 {
279		// In TLS 1.2 the cipher suite must match the resumed session. Ensure we
280		// are still offering it.
281		if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
282			return cacheKey, nil, nil, nil
283		}
284
285		hello.sessionTicket = session.sessionTicket
286		return
287	}
288
289	// Check that the session ticket is not expired.
290	if c.config.time().After(session.useBy) {
291		c.config.ClientSessionCache.Put(cacheKey, nil)
292		return cacheKey, nil, nil, nil
293	}
294
295	// In TLS 1.3 the KDF hash must match the resumed session. Ensure we
296	// offer at least one cipher suite with that hash.
297	cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
298	if cipherSuite == nil {
299		return cacheKey, nil, nil, nil
300	}
301	cipherSuiteOk := false
302	for _, offeredID := range hello.cipherSuites {
303		offeredSuite := cipherSuiteTLS13ByID(offeredID)
304		if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
305			cipherSuiteOk = true
306			break
307		}
308	}
309	if !cipherSuiteOk {
310		return cacheKey, nil, nil, nil
311	}
312
313	// Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
314	ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
315	identity := pskIdentity{
316		label:               session.sessionTicket,
317		obfuscatedTicketAge: ticketAge + session.ageAdd,
318	}
319	hello.pskIdentities = []pskIdentity{identity}
320	hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
321
322	// Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
323	psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
324		session.nonce, cipherSuite.hash.Size())
325	earlySecret = cipherSuite.extract(psk, nil)
326	binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
327	transcript := cipherSuite.hash.New()
328	transcript.Write(hello.marshalWithoutBinders())
329	pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
330	hello.updateBinders(pskBinders)
331
332	return
333}
334
335func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
336	peerVersion := serverHello.vers
337	if serverHello.supportedVersion != 0 {
338		peerVersion = serverHello.supportedVersion
339	}
340
341	vers, ok := c.config.mutualVersion([]uint16{peerVersion})
342	if !ok {
343		c.sendAlert(alertProtocolVersion)
344		return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
345	}
346
347	c.vers = vers
348	c.haveVers = true
349	c.in.version = vers
350	c.out.version = vers
351
352	return nil
353}
354
355// Does the handshake, either a full one or resumes old session. Requires hs.c,
356// hs.hello, hs.serverHello, and, optionally, hs.session to be set.
357func (hs *clientHandshakeState) handshake() error {
358	c := hs.c
359
360	isResume, err := hs.processServerHello()
361	if err != nil {
362		return err
363	}
364
365	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
366
367	// No signatures of the handshake are needed in a resumption.
368	// Otherwise, in a full handshake, if we don't have any certificates
369	// configured then we will never send a CertificateVerify message and
370	// thus no signatures are needed in that case either.
371	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
372		hs.finishedHash.discardHandshakeBuffer()
373	}
374
375	hs.finishedHash.Write(hs.hello.marshal())
376	hs.finishedHash.Write(hs.serverHello.marshal())
377
378	c.buffering = true
379	if isResume {
380		if err := hs.establishKeys(); err != nil {
381			return err
382		}
383		if err := hs.readSessionTicket(); err != nil {
384			return err
385		}
386		if err := hs.readFinished(c.serverFinished[:]); err != nil {
387			return err
388		}
389		c.clientFinishedIsFirst = false
390		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
391			return err
392		}
393		if _, err := c.flush(); err != nil {
394			return err
395		}
396	} else {
397		if err := hs.doFullHandshake(); err != nil {
398			return err
399		}
400		if err := hs.establishKeys(); err != nil {
401			return err
402		}
403		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
404			return err
405		}
406		if _, err := c.flush(); err != nil {
407			return err
408		}
409		c.clientFinishedIsFirst = true
410		if err := hs.readSessionTicket(); err != nil {
411			return err
412		}
413		if err := hs.readFinished(c.serverFinished[:]); err != nil {
414			return err
415		}
416	}
417
418	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
419	c.didResume = isResume
420	atomic.StoreUint32(&c.handshakeStatus, 1)
421
422	return nil
423}
424
425func (hs *clientHandshakeState) pickCipherSuite() error {
426	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
427		hs.c.sendAlert(alertHandshakeFailure)
428		return errors.New("tls: server chose an unconfigured cipher suite")
429	}
430
431	hs.c.cipherSuite = hs.suite.id
432	return nil
433}
434
435func (hs *clientHandshakeState) doFullHandshake() error {
436	c := hs.c
437
438	msg, err := c.readHandshake()
439	if err != nil {
440		return err
441	}
442	certMsg, ok := msg.(*certificateMsg)
443	if !ok || len(certMsg.certificates) == 0 {
444		c.sendAlert(alertUnexpectedMessage)
445		return unexpectedMessageError(certMsg, msg)
446	}
447	hs.finishedHash.Write(certMsg.marshal())
448
449	if c.handshakes == 0 {
450		// If this is the first handshake on a connection, process and
451		// (optionally) verify the server's certificates.
452		if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
453			return err
454		}
455	} else {
456		// This is a renegotiation handshake. We require that the
457		// server's identity (i.e. leaf certificate) is unchanged and
458		// thus any previous trust decision is still valid.
459		//
460		// See https://mitls.org/pages/attacks/3SHAKE for the
461		// motivation behind this requirement.
462		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
463			c.sendAlert(alertBadCertificate)
464			return errors.New("tls: server's identity changed during renegotiation")
465		}
466	}
467
468	msg, err = c.readHandshake()
469	if err != nil {
470		return err
471	}
472
473	cs, ok := msg.(*certificateStatusMsg)
474	if ok {
475		// RFC4366 on Certificate Status Request:
476		// The server MAY return a "certificate_status" message.
477
478		if !hs.serverHello.ocspStapling {
479			// If a server returns a "CertificateStatus" message, then the
480			// server MUST have included an extension of type "status_request"
481			// with empty "extension_data" in the extended server hello.
482
483			c.sendAlert(alertUnexpectedMessage)
484			return errors.New("tls: received unexpected CertificateStatus message")
485		}
486		hs.finishedHash.Write(cs.marshal())
487
488		c.ocspResponse = cs.response
489
490		msg, err = c.readHandshake()
491		if err != nil {
492			return err
493		}
494	}
495
496	keyAgreement := hs.suite.ka(c.vers)
497
498	skx, ok := msg.(*serverKeyExchangeMsg)
499	if ok {
500		hs.finishedHash.Write(skx.marshal())
501		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
502		if err != nil {
503			c.sendAlert(alertUnexpectedMessage)
504			return err
505		}
506
507		msg, err = c.readHandshake()
508		if err != nil {
509			return err
510		}
511	}
512
513	var chainToSend *Certificate
514	var certRequested bool
515	certReq, ok := msg.(*certificateRequestMsg)
516	if ok {
517		certRequested = true
518		hs.finishedHash.Write(certReq.marshal())
519
520		cri := certificateRequestInfoFromMsg(c.vers, certReq)
521		if chainToSend, err = c.getClientCertificate(cri); err != nil {
522			c.sendAlert(alertInternalError)
523			return err
524		}
525
526		msg, err = c.readHandshake()
527		if err != nil {
528			return err
529		}
530	}
531
532	shd, ok := msg.(*serverHelloDoneMsg)
533	if !ok {
534		c.sendAlert(alertUnexpectedMessage)
535		return unexpectedMessageError(shd, msg)
536	}
537	hs.finishedHash.Write(shd.marshal())
538
539	// If the server requested a certificate then we have to send a
540	// Certificate message, even if it's empty because we don't have a
541	// certificate to send.
542	if certRequested {
543		certMsg = new(certificateMsg)
544		certMsg.certificates = chainToSend.Certificate
545		hs.finishedHash.Write(certMsg.marshal())
546		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
547			return err
548		}
549	}
550
551	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
552	if err != nil {
553		c.sendAlert(alertInternalError)
554		return err
555	}
556	if ckx != nil {
557		hs.finishedHash.Write(ckx.marshal())
558		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
559			return err
560		}
561	}
562
563	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
564		certVerify := &certificateVerifyMsg{}
565
566		key, ok := chainToSend.PrivateKey.(crypto.Signer)
567		if !ok {
568			c.sendAlert(alertInternalError)
569			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
570		}
571
572		var sigType uint8
573		var sigHash crypto.Hash
574		if c.vers >= VersionTLS12 {
575			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
576			if err != nil {
577				c.sendAlert(alertIllegalParameter)
578				return err
579			}
580			sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
581			if err != nil {
582				return c.sendAlert(alertInternalError)
583			}
584			certVerify.hasSignatureAlgorithm = true
585			certVerify.signatureAlgorithm = signatureAlgorithm
586		} else {
587			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
588			if err != nil {
589				c.sendAlert(alertIllegalParameter)
590				return err
591			}
592		}
593
594		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
595		signOpts := crypto.SignerOpts(sigHash)
596		if sigType == signatureRSAPSS {
597			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
598		}
599		certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
600		if err != nil {
601			c.sendAlert(alertInternalError)
602			return err
603		}
604
605		hs.finishedHash.Write(certVerify.marshal())
606		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
607			return err
608		}
609	}
610
611	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
612	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
613		c.sendAlert(alertInternalError)
614		return errors.New("tls: failed to write to key log: " + err.Error())
615	}
616
617	hs.finishedHash.discardHandshakeBuffer()
618
619	return nil
620}
621
622func (hs *clientHandshakeState) establishKeys() error {
623	c := hs.c
624
625	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
626		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
627	var clientCipher, serverCipher interface{}
628	var clientHash, serverHash macFunction
629	if hs.suite.cipher != nil {
630		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
631		clientHash = hs.suite.mac(c.vers, clientMAC)
632		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
633		serverHash = hs.suite.mac(c.vers, serverMAC)
634	} else {
635		clientCipher = hs.suite.aead(clientKey, clientIV)
636		serverCipher = hs.suite.aead(serverKey, serverIV)
637	}
638
639	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
640	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
641	return nil
642}
643
644func (hs *clientHandshakeState) serverResumedSession() bool {
645	// If the server responded with the same sessionId then it means the
646	// sessionTicket is being used to resume a TLS session.
647	return hs.session != nil && hs.hello.sessionId != nil &&
648		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
649}
650
651func (hs *clientHandshakeState) processServerHello() (bool, error) {
652	c := hs.c
653
654	if err := hs.pickCipherSuite(); err != nil {
655		return false, err
656	}
657
658	if hs.serverHello.compressionMethod != compressionNone {
659		c.sendAlert(alertUnexpectedMessage)
660		return false, errors.New("tls: server selected unsupported compression format")
661	}
662
663	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
664		c.secureRenegotiation = true
665		if len(hs.serverHello.secureRenegotiation) != 0 {
666			c.sendAlert(alertHandshakeFailure)
667			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
668		}
669	}
670
671	if c.handshakes > 0 && c.secureRenegotiation {
672		var expectedSecureRenegotiation [24]byte
673		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
674		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
675		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
676			c.sendAlert(alertHandshakeFailure)
677			return false, errors.New("tls: incorrect renegotiation extension contents")
678		}
679	}
680
681	clientDidALPN := len(hs.hello.alpnProtocols) > 0
682	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
683
684	if !clientDidALPN && serverHasALPN {
685		c.sendAlert(alertHandshakeFailure)
686		return false, errors.New("tls: server advertised unrequested ALPN extension")
687	}
688
689	if serverHasALPN {
690		c.clientProtocol = hs.serverHello.alpnProtocol
691		c.clientProtocolFallback = false
692	}
693	c.scts = hs.serverHello.scts
694
695	if !hs.serverResumedSession() {
696		return false, nil
697	}
698
699	if hs.session.vers != c.vers {
700		c.sendAlert(alertHandshakeFailure)
701		return false, errors.New("tls: server resumed a session with a different version")
702	}
703
704	if hs.session.cipherSuite != hs.suite.id {
705		c.sendAlert(alertHandshakeFailure)
706		return false, errors.New("tls: server resumed a session with a different cipher suite")
707	}
708
709	// Restore masterSecret and peerCerts from previous state
710	hs.masterSecret = hs.session.masterSecret
711	c.peerCertificates = hs.session.serverCertificates
712	c.verifiedChains = hs.session.verifiedChains
713	return true, nil
714}
715
716func (hs *clientHandshakeState) readFinished(out []byte) error {
717	c := hs.c
718
719	if err := c.readChangeCipherSpec(); err != nil {
720		return err
721	}
722
723	msg, err := c.readHandshake()
724	if err != nil {
725		return err
726	}
727	serverFinished, ok := msg.(*finishedMsg)
728	if !ok {
729		c.sendAlert(alertUnexpectedMessage)
730		return unexpectedMessageError(serverFinished, msg)
731	}
732
733	verify := hs.finishedHash.serverSum(hs.masterSecret)
734	if len(verify) != len(serverFinished.verifyData) ||
735		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
736		c.sendAlert(alertHandshakeFailure)
737		return errors.New("tls: server's Finished message was incorrect")
738	}
739	hs.finishedHash.Write(serverFinished.marshal())
740	copy(out, verify)
741	return nil
742}
743
744func (hs *clientHandshakeState) readSessionTicket() error {
745	if !hs.serverHello.ticketSupported {
746		return nil
747	}
748
749	c := hs.c
750	msg, err := c.readHandshake()
751	if err != nil {
752		return err
753	}
754	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
755	if !ok {
756		c.sendAlert(alertUnexpectedMessage)
757		return unexpectedMessageError(sessionTicketMsg, msg)
758	}
759	hs.finishedHash.Write(sessionTicketMsg.marshal())
760
761	hs.session = &ClientSessionState{
762		sessionTicket:      sessionTicketMsg.ticket,
763		vers:               c.vers,
764		cipherSuite:        hs.suite.id,
765		masterSecret:       hs.masterSecret,
766		serverCertificates: c.peerCertificates,
767		verifiedChains:     c.verifiedChains,
768		receivedAt:         c.config.time(),
769	}
770
771	return nil
772}
773
774func (hs *clientHandshakeState) sendFinished(out []byte) error {
775	c := hs.c
776
777	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
778		return err
779	}
780
781	finished := new(finishedMsg)
782	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
783	hs.finishedHash.Write(finished.marshal())
784	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
785		return err
786	}
787	copy(out, finished.verifyData)
788	return nil
789}
790
791// verifyServerCertificate parses and verifies the provided chain, setting
792// c.verifiedChains and c.peerCertificates or sending the appropriate alert.
793func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
794	certs := make([]*x509.Certificate, len(certificates))
795	for i, asn1Data := range certificates {
796		cert, err := x509.ParseCertificate(asn1Data)
797		if err != nil {
798			c.sendAlert(alertBadCertificate)
799			return errors.New("tls: failed to parse certificate from server: " + err.Error())
800		}
801		certs[i] = cert
802	}
803
804	if !c.config.InsecureSkipVerify {
805		opts := x509.VerifyOptions{
806			Roots:         c.config.RootCAs,
807			CurrentTime:   c.config.time(),
808			DNSName:       c.config.ServerName,
809			Intermediates: x509.NewCertPool(),
810		}
811		for _, cert := range certs[1:] {
812			opts.Intermediates.AddCert(cert)
813		}
814		var err error
815		c.verifiedChains, err = certs[0].Verify(opts)
816		if err != nil {
817			c.sendAlert(alertBadCertificate)
818			return err
819		}
820	}
821
822	if c.config.VerifyPeerCertificate != nil {
823		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
824			c.sendAlert(alertBadCertificate)
825			return err
826		}
827	}
828
829	switch certs[0].PublicKey.(type) {
830	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
831		break
832	default:
833		c.sendAlert(alertUnsupportedCertificate)
834		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
835	}
836
837	c.peerCertificates = certs
838
839	return nil
840}
841
842// tls11SignatureSchemes contains the signature schemes that we synthesise for
843// a TLS <= 1.1 connection, based on the supported certificate types.
844var (
845	tls11SignatureSchemes      = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
846	tls11SignatureSchemesECDSA = tls11SignatureSchemes[:3]
847	tls11SignatureSchemesRSA   = tls11SignatureSchemes[3:]
848)
849
850// certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
851// <= 1.2 CertificateRequest, making an effort to fill in missing information.
852func certificateRequestInfoFromMsg(vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
853	cri := &CertificateRequestInfo{
854		AcceptableCAs: certReq.certificateAuthorities,
855		Version:       vers,
856	}
857
858	var rsaAvail, ecAvail bool
859	for _, certType := range certReq.certificateTypes {
860		switch certType {
861		case certTypeRSASign:
862			rsaAvail = true
863		case certTypeECDSASign:
864			ecAvail = true
865		}
866	}
867
868	if !certReq.hasSignatureAlgorithm {
869		// Prior to TLS 1.2, the signature schemes were not
870		// included in the certificate request message. In this
871		// case we use a plausible list based on the acceptable
872		// certificate types.
873		switch {
874		case rsaAvail && ecAvail:
875			cri.SignatureSchemes = tls11SignatureSchemes
876		case rsaAvail:
877			cri.SignatureSchemes = tls11SignatureSchemesRSA
878		case ecAvail:
879			cri.SignatureSchemes = tls11SignatureSchemesECDSA
880		}
881		return cri
882	}
883
884	// Filter the signature schemes based on the certificate types.
885	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
886	cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
887	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
888		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
889		if err != nil {
890			continue
891		}
892		switch sigType {
893		case signatureECDSA, signatureEd25519:
894			if ecAvail {
895				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
896			}
897		case signatureRSAPSS, signaturePKCS1v15:
898			if rsaAvail {
899				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
900			}
901		}
902	}
903
904	return cri
905}
906
907func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
908	if c.config.GetClientCertificate != nil {
909		return c.config.GetClientCertificate(cri)
910	}
911
912	for _, chain := range c.config.Certificates {
913		if err := cri.SupportsCertificate(&chain); err != nil {
914			continue
915		}
916		return &chain, nil
917	}
918
919	// No acceptable certificate found. Don't send a certificate.
920	return new(Certificate), nil
921}
922
923// clientSessionCacheKey returns a key used to cache sessionTickets that could
924// be used to resume previously negotiated TLS sessions with a server.
925func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
926	if len(config.ServerName) > 0 {
927		return config.ServerName
928	}
929	return serverAddr.String()
930}
931
932// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
933// given list of possible protocols and a list of the preference order. The
934// first list must not be empty. It returns the resulting protocol and flag
935// indicating if the fallback case was reached.
936func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
937	for _, s := range preferenceProtos {
938		for _, c := range protos {
939			if s == c {
940				return s, false
941			}
942		}
943	}
944
945	return protos[0], true
946}
947
948// hostnameInSNI converts name into an appropriate hostname for SNI.
949// Literal IP addresses and absolute FQDNs are not permitted as SNI values.
950// See RFC 6066, Section 3.
951func hostnameInSNI(name string) string {
952	host := name
953	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
954		host = host[1 : len(host)-1]
955	}
956	if i := strings.LastIndex(host, "%"); i > 0 {
957		host = host[:i]
958	}
959	if net.ParseIP(host) != nil {
960		return ""
961	}
962	for len(name) > 0 && name[len(name)-1] == '.' {
963		name = name[:len(name)-1]
964	}
965	return name
966}
967