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