github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/crypto/tls/handshake_client.go (about)

     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  
     5  package tls
     6  
     7  import (
     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  )
    22  
    23  type clientHandshakeState struct {
    24  	c            *Conn
    25  	serverHello  *serverHelloMsg
    26  	hello        *clientHelloMsg
    27  	suite        *cipherSuite
    28  	finishedHash finishedHash
    29  	masterSecret []byte
    30  	session      *ClientSessionState
    31  }
    32  
    33  // c.out.Mutex <= L; c.handshakeMutex <= L.
    34  func (c *Conn) clientHandshake() error {
    35  	if c.config == nil {
    36  		c.config = defaultConfig()
    37  	}
    38  
    39  	// This may be a renegotiation handshake, in which case some fields
    40  	// need to be reset.
    41  	c.didResume = false
    42  
    43  	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
    44  		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
    45  	}
    46  
    47  	nextProtosLength := 0
    48  	for _, proto := range c.config.NextProtos {
    49  		if l := len(proto); l == 0 || l > 255 {
    50  			return errors.New("tls: invalid NextProtos value")
    51  		} else {
    52  			nextProtosLength += 1 + l
    53  		}
    54  	}
    55  	if nextProtosLength > 0xffff {
    56  		return errors.New("tls: NextProtos values too large")
    57  	}
    58  
    59  	hello := &clientHelloMsg{
    60  		vers:                         c.config.maxVersion(),
    61  		compressionMethods:           []uint8{compressionNone},
    62  		random:                       make([]byte, 32),
    63  		ocspStapling:                 true,
    64  		scts:                         true,
    65  		serverName:                   hostnameInSNI(c.config.ServerName),
    66  		supportedCurves:              c.config.curvePreferences(),
    67  		supportedPoints:              []uint8{pointFormatUncompressed},
    68  		nextProtoNeg:                 len(c.config.NextProtos) > 0,
    69  		secureRenegotiationSupported: true,
    70  		alpnProtocols:                c.config.NextProtos,
    71  	}
    72  
    73  	if c.handshakes > 0 {
    74  		hello.secureRenegotiation = c.clientFinished[:]
    75  	}
    76  
    77  	possibleCipherSuites := c.config.cipherSuites()
    78  	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
    79  
    80  NextCipherSuite:
    81  	for _, suiteId := range possibleCipherSuites {
    82  		for _, suite := range cipherSuites {
    83  			if suite.id != suiteId {
    84  				continue
    85  			}
    86  			// Don't advertise TLS 1.2-only cipher suites unless
    87  			// we're attempting TLS 1.2.
    88  			if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
    89  				continue NextCipherSuite
    90  			}
    91  			// Don't advertise TLS 1.3-only cipher suites unless
    92  			// we're attempting TLS 1.3.
    93  			if hello.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
    94  				continue NextCipherSuite
    95  			}
    96  			hello.cipherSuites = append(hello.cipherSuites, suiteId)
    97  			continue NextCipherSuite
    98  		}
    99  	}
   100  
   101  	_, err := io.ReadFull(c.config.rand(), hello.random)
   102  	if err != nil {
   103  		c.sendAlert(alertInternalError)
   104  		return errors.New("tls: short read from Rand: " + err.Error())
   105  	}
   106  
   107  	if hello.vers >= VersionTLS12 {
   108  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   109  	}
   110  
   111  	var session *ClientSessionState
   112  	var cacheKey string
   113  	sessionCache := c.config.ClientSessionCache
   114  	if c.config.SessionTicketsDisabled {
   115  		sessionCache = nil
   116  	}
   117  
   118  	if sessionCache != nil {
   119  		hello.ticketSupported = true
   120  	}
   121  
   122  	// Session resumption is not allowed if renegotiating because
   123  	// renegotiation is primarily used to allow a client to send a client
   124  	// certificate, which would be skipped if session resumption occurred.
   125  	if sessionCache != nil && c.handshakes == 0 {
   126  		// Try to resume a previously negotiated TLS session, if
   127  		// available.
   128  		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   129  		candidateSession, ok := sessionCache.Get(cacheKey)
   130  		if ok {
   131  			// Check that the ciphersuite/version used for the
   132  			// previous session are still valid.
   133  			cipherSuiteOk := false
   134  			for _, id := range hello.cipherSuites {
   135  				if id == candidateSession.cipherSuite {
   136  					cipherSuiteOk = true
   137  					break
   138  				}
   139  			}
   140  
   141  			versOk := candidateSession.vers >= c.config.minVersion() &&
   142  				candidateSession.vers <= c.config.maxVersion()
   143  			if versOk && cipherSuiteOk {
   144  				session = candidateSession
   145  			}
   146  		}
   147  	}
   148  
   149  	if session != nil {
   150  		hello.sessionTicket = session.sessionTicket
   151  		// A random session ID is used to detect when the
   152  		// server accepted the ticket and is resuming a session
   153  		// (see RFC 5077).
   154  		hello.sessionId = make([]byte, 16)
   155  		if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
   156  			c.sendAlert(alertInternalError)
   157  			return errors.New("tls: short read from Rand: " + err.Error())
   158  		}
   159  	}
   160  
   161  	if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
   162  		return err
   163  	}
   164  
   165  	msg, err := c.readHandshake()
   166  	if err != nil {
   167  		return err
   168  	}
   169  	serverHello, ok := msg.(*serverHelloMsg)
   170  	if !ok {
   171  		c.sendAlert(alertUnexpectedMessage)
   172  		return unexpectedMessageError(serverHello, msg)
   173  	}
   174  
   175  	vers, ok := c.config.pickVersion([]uint16{serverHello.vers})
   176  	if !ok || vers < VersionTLS10 {
   177  		// TLS 1.0 is the minimum version supported as a client.
   178  		c.sendAlert(alertProtocolVersion)
   179  		return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
   180  	}
   181  	c.vers = vers
   182  	c.haveVers = true
   183  
   184  	suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
   185  	if suite == nil {
   186  		c.sendAlert(alertHandshakeFailure)
   187  		return errors.New("tls: server chose an unconfigured cipher suite")
   188  	}
   189  	// Check that the chosen cipher suite matches the protocol version.
   190  	if c.vers >= VersionTLS13 && suite.flags&suiteTLS13 == 0 ||
   191  		c.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
   192  		c.sendAlert(alertHandshakeFailure)
   193  		return errors.New("tls: server chose an inappropriate cipher suite")
   194  	}
   195  
   196  	hs := &clientHandshakeState{
   197  		c:            c,
   198  		serverHello:  serverHello,
   199  		hello:        hello,
   200  		suite:        suite,
   201  		finishedHash: newFinishedHash(c.vers, suite),
   202  		session:      session,
   203  	}
   204  
   205  	isResume, err := hs.processServerHello()
   206  	if err != nil {
   207  		return err
   208  	}
   209  
   210  	// No signatures of the handshake are needed in a resumption.
   211  	// Otherwise, in a full handshake, if we don't have any certificates
   212  	// configured then we will never send a CertificateVerify message and
   213  	// thus no signatures are needed in that case either.
   214  	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
   215  		hs.finishedHash.discardHandshakeBuffer()
   216  	}
   217  
   218  	hs.finishedHash.Write(hs.hello.marshal())
   219  	hs.finishedHash.Write(hs.serverHello.marshal())
   220  
   221  	c.buffering = true
   222  	if isResume {
   223  		if err := hs.establishKeys(); err != nil {
   224  			return err
   225  		}
   226  		if err := hs.readSessionTicket(); err != nil {
   227  			return err
   228  		}
   229  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   230  			return err
   231  		}
   232  		c.clientFinishedIsFirst = false
   233  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   234  			return err
   235  		}
   236  		if _, err := c.flush(); err != nil {
   237  			return err
   238  		}
   239  	} else {
   240  		if err := hs.doFullHandshake(); err != nil {
   241  			return err
   242  		}
   243  		if err := hs.establishKeys(); err != nil {
   244  			return err
   245  		}
   246  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   247  			return err
   248  		}
   249  		if _, err := c.flush(); err != nil {
   250  			return err
   251  		}
   252  		c.clientFinishedIsFirst = true
   253  		if err := hs.readSessionTicket(); err != nil {
   254  			return err
   255  		}
   256  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   257  			return err
   258  		}
   259  	}
   260  
   261  	if sessionCache != nil && hs.session != nil && session != hs.session {
   262  		sessionCache.Put(cacheKey, hs.session)
   263  	}
   264  
   265  	c.didResume = isResume
   266  	c.phase = handshakeConfirmed
   267  	atomic.StoreInt32(&c.handshakeConfirmed, 1)
   268  	c.handshakeComplete = true
   269  	c.cipherSuite = suite.id
   270  	return nil
   271  }
   272  
   273  func (hs *clientHandshakeState) doFullHandshake() error {
   274  	c := hs.c
   275  
   276  	msg, err := c.readHandshake()
   277  	if err != nil {
   278  		return err
   279  	}
   280  	certMsg, ok := msg.(*certificateMsg)
   281  	if !ok || len(certMsg.certificates) == 0 {
   282  		c.sendAlert(alertUnexpectedMessage)
   283  		return unexpectedMessageError(certMsg, msg)
   284  	}
   285  	hs.finishedHash.Write(certMsg.marshal())
   286  
   287  	if c.handshakes == 0 {
   288  		// If this is the first handshake on a connection, process and
   289  		// (optionally) verify the server's certificates.
   290  		certs := make([]*x509.Certificate, len(certMsg.certificates))
   291  		for i, asn1Data := range certMsg.certificates {
   292  			cert, err := x509.ParseCertificate(asn1Data)
   293  			if err != nil {
   294  				c.sendAlert(alertBadCertificate)
   295  				return errors.New("tls: failed to parse certificate from server: " + err.Error())
   296  			}
   297  			certs[i] = cert
   298  		}
   299  
   300  		if !c.config.InsecureSkipVerify {
   301  			opts := x509.VerifyOptions{
   302  				Roots:         c.config.RootCAs,
   303  				CurrentTime:   c.config.time(),
   304  				DNSName:       c.config.ServerName,
   305  				Intermediates: x509.NewCertPool(),
   306  			}
   307  
   308  			for i, cert := range certs {
   309  				if i == 0 {
   310  					continue
   311  				}
   312  				opts.Intermediates.AddCert(cert)
   313  			}
   314  			c.verifiedChains, err = certs[0].Verify(opts)
   315  			if err != nil {
   316  				c.sendAlert(alertBadCertificate)
   317  				return err
   318  			}
   319  		}
   320  
   321  		if c.config.VerifyPeerCertificate != nil {
   322  			if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
   323  				c.sendAlert(alertBadCertificate)
   324  				return err
   325  			}
   326  		}
   327  
   328  		switch certs[0].PublicKey.(type) {
   329  		case *rsa.PublicKey, *ecdsa.PublicKey:
   330  			break
   331  		default:
   332  			c.sendAlert(alertUnsupportedCertificate)
   333  			return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
   334  		}
   335  
   336  		c.peerCertificates = certs
   337  	} else {
   338  		// This is a renegotiation handshake. We require that the
   339  		// server's identity (i.e. leaf certificate) is unchanged and
   340  		// thus any previous trust decision is still valid.
   341  		//
   342  		// See https://mitls.org/pages/attacks/3SHAKE for the
   343  		// motivation behind this requirement.
   344  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
   345  			c.sendAlert(alertBadCertificate)
   346  			return errors.New("tls: server's identity changed during renegotiation")
   347  		}
   348  	}
   349  
   350  	if hs.serverHello.ocspStapling {
   351  		msg, err = c.readHandshake()
   352  		if err != nil {
   353  			return err
   354  		}
   355  		cs, ok := msg.(*certificateStatusMsg)
   356  		if !ok {
   357  			c.sendAlert(alertUnexpectedMessage)
   358  			return unexpectedMessageError(cs, msg)
   359  		}
   360  		hs.finishedHash.Write(cs.marshal())
   361  
   362  		if cs.statusType == statusTypeOCSP {
   363  			c.ocspResponse = cs.response
   364  		}
   365  	}
   366  
   367  	msg, err = c.readHandshake()
   368  	if err != nil {
   369  		return err
   370  	}
   371  
   372  	keyAgreement := hs.suite.ka(c.vers)
   373  
   374  	skx, ok := msg.(*serverKeyExchangeMsg)
   375  	if ok {
   376  		hs.finishedHash.Write(skx.marshal())
   377  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
   378  		if err != nil {
   379  			c.sendAlert(alertUnexpectedMessage)
   380  			return err
   381  		}
   382  
   383  		msg, err = c.readHandshake()
   384  		if err != nil {
   385  			return err
   386  		}
   387  	}
   388  
   389  	var chainToSend *Certificate
   390  	var certRequested bool
   391  	certReq, ok := msg.(*certificateRequestMsg)
   392  	if ok {
   393  		certRequested = true
   394  		hs.finishedHash.Write(certReq.marshal())
   395  
   396  		if chainToSend, err = hs.getCertificate(certReq); err != nil {
   397  			c.sendAlert(alertInternalError)
   398  			return err
   399  		}
   400  
   401  		msg, err = c.readHandshake()
   402  		if err != nil {
   403  			return err
   404  		}
   405  	}
   406  
   407  	shd, ok := msg.(*serverHelloDoneMsg)
   408  	if !ok {
   409  		c.sendAlert(alertUnexpectedMessage)
   410  		return unexpectedMessageError(shd, msg)
   411  	}
   412  	hs.finishedHash.Write(shd.marshal())
   413  
   414  	// If the server requested a certificate then we have to send a
   415  	// Certificate message, even if it's empty because we don't have a
   416  	// certificate to send.
   417  	if certRequested {
   418  		certMsg = new(certificateMsg)
   419  		certMsg.certificates = chainToSend.Certificate
   420  		hs.finishedHash.Write(certMsg.marshal())
   421  		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   422  			return err
   423  		}
   424  	}
   425  
   426  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
   427  	if err != nil {
   428  		c.sendAlert(alertInternalError)
   429  		return err
   430  	}
   431  	if ckx != nil {
   432  		hs.finishedHash.Write(ckx.marshal())
   433  		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
   434  			return err
   435  		}
   436  	}
   437  
   438  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   439  		certVerify := &certificateVerifyMsg{
   440  			hasSignatureAndHash: c.vers >= VersionTLS12,
   441  		}
   442  
   443  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   444  		if !ok {
   445  			c.sendAlert(alertInternalError)
   446  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   447  		}
   448  
   449  		var signatureType uint8
   450  		switch key.Public().(type) {
   451  		case *ecdsa.PublicKey:
   452  			signatureType = signatureECDSA
   453  		case *rsa.PublicKey:
   454  			signatureType = signatureRSA
   455  		default:
   456  			c.sendAlert(alertInternalError)
   457  			return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
   458  		}
   459  
   460  		// SignatureAndHashAlgorithm was introduced in TLS 1.2.
   461  		if certVerify.hasSignatureAndHash {
   462  			certVerify.signatureAlgorithm, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.supportedSignatureAlgorithms, signatureType)
   463  			if err != nil {
   464  				c.sendAlert(alertInternalError)
   465  				return err
   466  			}
   467  		}
   468  		digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(signatureType, certVerify.signatureAlgorithm, hs.masterSecret)
   469  		if err != nil {
   470  			c.sendAlert(alertInternalError)
   471  			return err
   472  		}
   473  		certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
   474  		if err != nil {
   475  			c.sendAlert(alertInternalError)
   476  			return err
   477  		}
   478  
   479  		hs.finishedHash.Write(certVerify.marshal())
   480  		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
   481  			return err
   482  		}
   483  	}
   484  
   485  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
   486  	if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.hello.random, hs.masterSecret); err != nil {
   487  		c.sendAlert(alertInternalError)
   488  		return errors.New("tls: failed to write to key log: " + err.Error())
   489  	}
   490  
   491  	hs.finishedHash.discardHandshakeBuffer()
   492  
   493  	return nil
   494  }
   495  
   496  func (hs *clientHandshakeState) establishKeys() error {
   497  	c := hs.c
   498  
   499  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   500  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   501  	var clientCipher, serverCipher interface{}
   502  	var clientHash, serverHash macFunction
   503  	if hs.suite.cipher != nil {
   504  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   505  		clientHash = hs.suite.mac(c.vers, clientMAC)
   506  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   507  		serverHash = hs.suite.mac(c.vers, serverMAC)
   508  	} else {
   509  		clientCipher = hs.suite.aead(clientKey, clientIV)
   510  		serverCipher = hs.suite.aead(serverKey, serverIV)
   511  	}
   512  
   513  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   514  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   515  	return nil
   516  }
   517  
   518  func (hs *clientHandshakeState) serverResumedSession() bool {
   519  	// If the server responded with the same sessionId then it means the
   520  	// sessionTicket is being used to resume a TLS session.
   521  	return hs.session != nil && hs.hello.sessionId != nil &&
   522  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   523  }
   524  
   525  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   526  	c := hs.c
   527  
   528  	if hs.serverHello.compressionMethod != compressionNone {
   529  		c.sendAlert(alertUnexpectedMessage)
   530  		return false, errors.New("tls: server selected unsupported compression format")
   531  	}
   532  
   533  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   534  		c.secureRenegotiation = true
   535  		if len(hs.serverHello.secureRenegotiation) != 0 {
   536  			c.sendAlert(alertHandshakeFailure)
   537  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   538  		}
   539  	}
   540  
   541  	if c.handshakes > 0 && c.secureRenegotiation {
   542  		var expectedSecureRenegotiation [24]byte
   543  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   544  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   545  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   546  			c.sendAlert(alertHandshakeFailure)
   547  			return false, errors.New("tls: incorrect renegotiation extension contents")
   548  		}
   549  	}
   550  
   551  	clientDidNPN := hs.hello.nextProtoNeg
   552  	clientDidALPN := len(hs.hello.alpnProtocols) > 0
   553  	serverHasNPN := hs.serverHello.nextProtoNeg
   554  	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
   555  
   556  	if !clientDidNPN && serverHasNPN {
   557  		c.sendAlert(alertHandshakeFailure)
   558  		return false, errors.New("tls: server advertised unrequested NPN extension")
   559  	}
   560  
   561  	if !clientDidALPN && serverHasALPN {
   562  		c.sendAlert(alertHandshakeFailure)
   563  		return false, errors.New("tls: server advertised unrequested ALPN extension")
   564  	}
   565  
   566  	if serverHasNPN && serverHasALPN {
   567  		c.sendAlert(alertHandshakeFailure)
   568  		return false, errors.New("tls: server advertised both NPN and ALPN extensions")
   569  	}
   570  
   571  	if serverHasALPN {
   572  		c.clientProtocol = hs.serverHello.alpnProtocol
   573  		c.clientProtocolFallback = false
   574  	}
   575  	c.scts = hs.serverHello.scts
   576  
   577  	if !hs.serverResumedSession() {
   578  		return false, nil
   579  	}
   580  
   581  	if hs.session.vers != c.vers {
   582  		c.sendAlert(alertHandshakeFailure)
   583  		return false, errors.New("tls: server resumed a session with a different version")
   584  	}
   585  
   586  	if hs.session.cipherSuite != hs.suite.id {
   587  		c.sendAlert(alertHandshakeFailure)
   588  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   589  	}
   590  
   591  	// Restore masterSecret and peerCerts from previous state
   592  	hs.masterSecret = hs.session.masterSecret
   593  	c.peerCertificates = hs.session.serverCertificates
   594  	c.verifiedChains = hs.session.verifiedChains
   595  	return true, nil
   596  }
   597  
   598  func (hs *clientHandshakeState) readFinished(out []byte) error {
   599  	c := hs.c
   600  
   601  	c.readRecord(recordTypeChangeCipherSpec)
   602  	if c.in.err != nil {
   603  		return c.in.err
   604  	}
   605  
   606  	msg, err := c.readHandshake()
   607  	if err != nil {
   608  		return err
   609  	}
   610  	serverFinished, ok := msg.(*finishedMsg)
   611  	if !ok {
   612  		c.sendAlert(alertUnexpectedMessage)
   613  		return unexpectedMessageError(serverFinished, msg)
   614  	}
   615  
   616  	verify := hs.finishedHash.serverSum(hs.masterSecret)
   617  	if len(verify) != len(serverFinished.verifyData) ||
   618  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
   619  		c.sendAlert(alertDecryptError)
   620  		return errors.New("tls: server's Finished message was incorrect")
   621  	}
   622  	hs.finishedHash.Write(serverFinished.marshal())
   623  	copy(out, verify)
   624  	return nil
   625  }
   626  
   627  func (hs *clientHandshakeState) readSessionTicket() error {
   628  	if !hs.serverHello.ticketSupported {
   629  		return nil
   630  	}
   631  
   632  	c := hs.c
   633  	msg, err := c.readHandshake()
   634  	if err != nil {
   635  		return err
   636  	}
   637  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
   638  	if !ok {
   639  		c.sendAlert(alertUnexpectedMessage)
   640  		return unexpectedMessageError(sessionTicketMsg, msg)
   641  	}
   642  	hs.finishedHash.Write(sessionTicketMsg.marshal())
   643  
   644  	hs.session = &ClientSessionState{
   645  		sessionTicket:      sessionTicketMsg.ticket,
   646  		vers:               c.vers,
   647  		cipherSuite:        hs.suite.id,
   648  		masterSecret:       hs.masterSecret,
   649  		serverCertificates: c.peerCertificates,
   650  		verifiedChains:     c.verifiedChains,
   651  	}
   652  
   653  	return nil
   654  }
   655  
   656  func (hs *clientHandshakeState) sendFinished(out []byte) error {
   657  	c := hs.c
   658  
   659  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   660  		return err
   661  	}
   662  	if hs.serverHello.nextProtoNeg {
   663  		nextProto := new(nextProtoMsg)
   664  		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
   665  		nextProto.proto = proto
   666  		c.clientProtocol = proto
   667  		c.clientProtocolFallback = fallback
   668  
   669  		hs.finishedHash.Write(nextProto.marshal())
   670  		if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
   671  			return err
   672  		}
   673  	}
   674  
   675  	finished := new(finishedMsg)
   676  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
   677  	hs.finishedHash.Write(finished.marshal())
   678  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   679  		return err
   680  	}
   681  	copy(out, finished.verifyData)
   682  	return nil
   683  }
   684  
   685  // tls11SignatureSchemes contains the signature schemes that we synthesise for
   686  // a TLS <= 1.1 connection, based on the supported certificate types.
   687  var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
   688  
   689  const (
   690  	// tls11SignatureSchemesNumECDSA is the number of initial elements of
   691  	// tls11SignatureSchemes that use ECDSA.
   692  	tls11SignatureSchemesNumECDSA = 3
   693  	// tls11SignatureSchemesNumRSA is the number of trailing elements of
   694  	// tls11SignatureSchemes that use RSA.
   695  	tls11SignatureSchemesNumRSA = 4
   696  )
   697  
   698  func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
   699  	c := hs.c
   700  
   701  	var rsaAvail, ecdsaAvail bool
   702  	for _, certType := range certReq.certificateTypes {
   703  		switch certType {
   704  		case certTypeRSASign:
   705  			rsaAvail = true
   706  		case certTypeECDSASign:
   707  			ecdsaAvail = true
   708  		}
   709  	}
   710  
   711  	if c.config.GetClientCertificate != nil {
   712  		var signatureSchemes []SignatureScheme
   713  
   714  		if !certReq.hasSignatureAndHash {
   715  			// Prior to TLS 1.2, the signature schemes were not
   716  			// included in the certificate request message. In this
   717  			// case we use a plausible list based on the acceptable
   718  			// certificate types.
   719  			signatureSchemes = tls11SignatureSchemes
   720  			if !ecdsaAvail {
   721  				signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
   722  			}
   723  			if !rsaAvail {
   724  				signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
   725  			}
   726  		} else {
   727  			signatureSchemes = certReq.supportedSignatureAlgorithms
   728  		}
   729  
   730  		return c.config.GetClientCertificate(&CertificateRequestInfo{
   731  			AcceptableCAs:    certReq.certificateAuthorities,
   732  			SignatureSchemes: signatureSchemes,
   733  		})
   734  	}
   735  
   736  	// RFC 4346 on the certificateAuthorities field: A list of the
   737  	// distinguished names of acceptable certificate authorities.
   738  	// These distinguished names may specify a desired
   739  	// distinguished name for a root CA or for a subordinate CA;
   740  	// thus, this message can be used to describe both known roots
   741  	// and a desired authorization space. If the
   742  	// certificate_authorities list is empty then the client MAY
   743  	// send any certificate of the appropriate
   744  	// ClientCertificateType, unless there is some external
   745  	// arrangement to the contrary.
   746  
   747  	// We need to search our list of client certs for one
   748  	// where SignatureAlgorithm is acceptable to the server and the
   749  	// Issuer is in certReq.certificateAuthorities
   750  findCert:
   751  	for i, chain := range c.config.Certificates {
   752  		if !rsaAvail && !ecdsaAvail {
   753  			continue
   754  		}
   755  
   756  		for j, cert := range chain.Certificate {
   757  			x509Cert := chain.Leaf
   758  			// parse the certificate if this isn't the leaf
   759  			// node, or if chain.Leaf was nil
   760  			if j != 0 || x509Cert == nil {
   761  				var err error
   762  				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
   763  					c.sendAlert(alertInternalError)
   764  					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
   765  				}
   766  			}
   767  
   768  			switch {
   769  			case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
   770  			case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
   771  			default:
   772  				continue findCert
   773  			}
   774  
   775  			if len(certReq.certificateAuthorities) == 0 {
   776  				// they gave us an empty list, so just take the
   777  				// first cert from c.config.Certificates
   778  				return &chain, nil
   779  			}
   780  
   781  			for _, ca := range certReq.certificateAuthorities {
   782  				if bytes.Equal(x509Cert.RawIssuer, ca) {
   783  					return &chain, nil
   784  				}
   785  			}
   786  		}
   787  	}
   788  
   789  	// No acceptable certificate found. Don't send a certificate.
   790  	return new(Certificate), nil
   791  }
   792  
   793  // clientSessionCacheKey returns a key used to cache sessionTickets that could
   794  // be used to resume previously negotiated TLS sessions with a server.
   795  func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
   796  	if len(config.ServerName) > 0 {
   797  		return config.ServerName
   798  	}
   799  	return serverAddr.String()
   800  }
   801  
   802  // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
   803  // given list of possible protocols and a list of the preference order. The
   804  // first list must not be empty. It returns the resulting protocol and flag
   805  // indicating if the fallback case was reached.
   806  func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
   807  	for _, s := range preferenceProtos {
   808  		for _, c := range protos {
   809  			if s == c {
   810  				return s, false
   811  			}
   812  		}
   813  	}
   814  
   815  	return protos[0], true
   816  }
   817  
   818  // hostnameInSNI converts name into an appropriate hostname for SNI.
   819  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
   820  // See https://tools.ietf.org/html/rfc6066#section-3.
   821  func hostnameInSNI(name string) string {
   822  	host := name
   823  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
   824  		host = host[1 : len(host)-1]
   825  	}
   826  	if i := strings.LastIndex(host, "%"); i > 0 {
   827  		host = host[:i]
   828  	}
   829  	if net.ParseIP(host) != nil {
   830  		return ""
   831  	}
   832  	for len(name) > 0 && name[len(name)-1] == '.' {
   833  		name = name[:len(name)-1]
   834  	}
   835  	return name
   836  }