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