github.com/Filosottile/go@v0.0.0-20170906193555-dbed9972d994/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  	if err := c.enableApplicationDataEncryption(); err != nil {
   269  		return err
   270  	}
   271  
   272  	c.didResume = isResume
   273  	c.handshakeComplete = true
   274  
   275  	return nil
   276  }
   277  
   278  func (hs *clientHandshakeState) pickTLSVersion() error {
   279  	vers, ok := hs.c.config.mutualVersion(hs.serverHello.vers)
   280  	if !ok || vers < VersionTLS10 {
   281  		// TLS 1.0 is the minimum version supported as a client.
   282  		hs.c.sendAlert(alertProtocolVersion)
   283  		return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
   284  	}
   285  
   286  	hs.c.vers = vers
   287  	hs.c.haveVers = true
   288  
   289  	return nil
   290  }
   291  
   292  func (hs *clientHandshakeState) pickCipherSuite() error {
   293  	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
   294  		hs.c.sendAlert(alertHandshakeFailure)
   295  		return errors.New("tls: server chose an unconfigured cipher suite")
   296  	}
   297  
   298  	hs.c.cipherSuite = hs.suite.id
   299  	return nil
   300  }
   301  
   302  func (hs *clientHandshakeState) doFullHandshake() error {
   303  	c := hs.c
   304  
   305  	msg, err := c.readHandshake()
   306  	if err != nil {
   307  		return err
   308  	}
   309  	certMsg, ok := msg.(*certificateMsg)
   310  	if !ok || len(certMsg.certificates) == 0 {
   311  		c.sendAlert(alertUnexpectedMessage)
   312  		return unexpectedMessageError(certMsg, msg)
   313  	}
   314  	hs.finishedHash.Write(certMsg.marshal())
   315  
   316  	if c.handshakes == 0 {
   317  		// If this is the first handshake on a connection, process and
   318  		// (optionally) verify the server's certificates.
   319  		certs := make([]*x509.Certificate, len(certMsg.certificates))
   320  		for i, asn1Data := range certMsg.certificates {
   321  			cert, err := x509.ParseCertificate(asn1Data)
   322  			if err != nil {
   323  				c.sendAlert(alertBadCertificate)
   324  				return errors.New("tls: failed to parse certificate from server: " + err.Error())
   325  			}
   326  			certs[i] = cert
   327  		}
   328  
   329  		if !c.config.InsecureSkipVerify {
   330  			opts := x509.VerifyOptions{
   331  				Roots:         c.config.RootCAs,
   332  				CurrentTime:   c.config.time(),
   333  				DNSName:       c.config.ServerName,
   334  				Intermediates: x509.NewCertPool(),
   335  			}
   336  
   337  			for i, cert := range certs {
   338  				if i == 0 {
   339  					continue
   340  				}
   341  				opts.Intermediates.AddCert(cert)
   342  			}
   343  			c.verifiedChains, err = certs[0].Verify(opts)
   344  			if err != nil {
   345  				c.sendAlert(alertBadCertificate)
   346  				return err
   347  			}
   348  		}
   349  
   350  		if c.config.VerifyPeerCertificate != nil {
   351  			if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
   352  				c.sendAlert(alertBadCertificate)
   353  				return err
   354  			}
   355  		}
   356  
   357  		switch certs[0].PublicKey.(type) {
   358  		case *rsa.PublicKey, *ecdsa.PublicKey:
   359  			break
   360  		default:
   361  			c.sendAlert(alertUnsupportedCertificate)
   362  			return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
   363  		}
   364  
   365  		c.peerCertificates = certs
   366  	} else {
   367  		// This is a renegotiation handshake. We require that the
   368  		// server's identity (i.e. leaf certificate) is unchanged and
   369  		// thus any previous trust decision is still valid.
   370  		//
   371  		// See https://mitls.org/pages/attacks/3SHAKE for the
   372  		// motivation behind this requirement.
   373  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
   374  			c.sendAlert(alertBadCertificate)
   375  			return errors.New("tls: server's identity changed during renegotiation")
   376  		}
   377  	}
   378  
   379  	if hs.serverHello.ocspStapling {
   380  		msg, err = c.readHandshake()
   381  		if err != nil {
   382  			return err
   383  		}
   384  		cs, ok := msg.(*certificateStatusMsg)
   385  		if !ok {
   386  			c.sendAlert(alertUnexpectedMessage)
   387  			return unexpectedMessageError(cs, msg)
   388  		}
   389  		hs.finishedHash.Write(cs.marshal())
   390  
   391  		if cs.statusType == statusTypeOCSP {
   392  			c.ocspResponse = cs.response
   393  		}
   394  	}
   395  
   396  	msg, err = c.readHandshake()
   397  	if err != nil {
   398  		return err
   399  	}
   400  
   401  	keyAgreement := hs.suite.ka(c.vers)
   402  
   403  	skx, ok := msg.(*serverKeyExchangeMsg)
   404  	if ok {
   405  		hs.finishedHash.Write(skx.marshal())
   406  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
   407  		if err != nil {
   408  			c.sendAlert(alertUnexpectedMessage)
   409  			return err
   410  		}
   411  
   412  		msg, err = c.readHandshake()
   413  		if err != nil {
   414  			return err
   415  		}
   416  	}
   417  
   418  	var chainToSend *Certificate
   419  	var certRequested bool
   420  	certReq, ok := msg.(*certificateRequestMsg)
   421  	if ok {
   422  		certRequested = true
   423  		hs.finishedHash.Write(certReq.marshal())
   424  
   425  		if chainToSend, err = hs.getCertificate(certReq); err != nil {
   426  			c.sendAlert(alertInternalError)
   427  			return err
   428  		}
   429  
   430  		msg, err = c.readHandshake()
   431  		if err != nil {
   432  			return err
   433  		}
   434  	}
   435  
   436  	shd, ok := msg.(*serverHelloDoneMsg)
   437  	if !ok {
   438  		c.sendAlert(alertUnexpectedMessage)
   439  		return unexpectedMessageError(shd, msg)
   440  	}
   441  	hs.finishedHash.Write(shd.marshal())
   442  
   443  	// If the server requested a certificate then we have to send a
   444  	// Certificate message, even if it's empty because we don't have a
   445  	// certificate to send.
   446  	if certRequested {
   447  		certMsg = new(certificateMsg)
   448  		certMsg.certificates = chainToSend.Certificate
   449  		hs.finishedHash.Write(certMsg.marshal())
   450  		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   451  			return err
   452  		}
   453  	}
   454  
   455  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
   456  	if err != nil {
   457  		c.sendAlert(alertInternalError)
   458  		return err
   459  	}
   460  	if ckx != nil {
   461  		hs.finishedHash.Write(ckx.marshal())
   462  		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
   463  			return err
   464  		}
   465  	}
   466  
   467  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   468  		certVerify := &certificateVerifyMsg{
   469  			hasSignatureAndHash: c.vers >= VersionTLS12,
   470  		}
   471  
   472  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   473  		if !ok {
   474  			c.sendAlert(alertInternalError)
   475  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   476  		}
   477  
   478  		var signatureType uint8
   479  		switch key.Public().(type) {
   480  		case *ecdsa.PublicKey:
   481  			signatureType = signatureECDSA
   482  		case *rsa.PublicKey:
   483  			signatureType = signatureRSA
   484  		default:
   485  			c.sendAlert(alertInternalError)
   486  			return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
   487  		}
   488  
   489  		certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureType)
   490  		if err != nil {
   491  			c.sendAlert(alertInternalError)
   492  			return err
   493  		}
   494  		digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
   495  		if err != nil {
   496  			c.sendAlert(alertInternalError)
   497  			return err
   498  		}
   499  		certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
   500  		if err != nil {
   501  			c.sendAlert(alertInternalError)
   502  			return err
   503  		}
   504  
   505  		hs.finishedHash.Write(certVerify.marshal())
   506  		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
   507  			return err
   508  		}
   509  	}
   510  
   511  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
   512  	if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
   513  		c.sendAlert(alertInternalError)
   514  		return errors.New("tls: failed to write to key log: " + err.Error())
   515  	}
   516  
   517  	hs.finishedHash.discardHandshakeBuffer()
   518  
   519  	return nil
   520  }
   521  
   522  func (hs *clientHandshakeState) establishKeys() error {
   523  	c := hs.c
   524  
   525  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   526  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   527  	var clientCipher, serverCipher interface{}
   528  	var clientHash, serverHash macFunction
   529  	if hs.suite.cipher != nil {
   530  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   531  		clientHash = hs.suite.mac(c.vers, clientMAC)
   532  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   533  		serverHash = hs.suite.mac(c.vers, serverMAC)
   534  	} else {
   535  		clientCipher = hs.suite.aead(clientKey, clientIV)
   536  		serverCipher = hs.suite.aead(serverKey, serverIV)
   537  	}
   538  
   539  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   540  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   541  	return nil
   542  }
   543  
   544  func (hs *clientHandshakeState) serverResumedSession() bool {
   545  	// If the server responded with the same sessionId then it means the
   546  	// sessionTicket is being used to resume a TLS session.
   547  	return hs.session != nil && hs.hello.sessionId != nil &&
   548  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   549  }
   550  
   551  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   552  	c := hs.c
   553  
   554  	if hs.serverHello.compressionMethod != compressionNone {
   555  		c.sendAlert(alertUnexpectedMessage)
   556  		return false, errors.New("tls: server selected unsupported compression format")
   557  	}
   558  
   559  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   560  		c.secureRenegotiation = true
   561  		if len(hs.serverHello.secureRenegotiation) != 0 {
   562  			c.sendAlert(alertHandshakeFailure)
   563  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   564  		}
   565  	}
   566  
   567  	if c.handshakes > 0 && c.secureRenegotiation {
   568  		var expectedSecureRenegotiation [24]byte
   569  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   570  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   571  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   572  			c.sendAlert(alertHandshakeFailure)
   573  			return false, errors.New("tls: incorrect renegotiation extension contents")
   574  		}
   575  	}
   576  
   577  	clientDidNPN := hs.hello.nextProtoNeg
   578  	clientDidALPN := len(hs.hello.alpnProtocols) > 0
   579  	serverHasNPN := hs.serverHello.nextProtoNeg
   580  	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
   581  
   582  	if !clientDidNPN && serverHasNPN {
   583  		c.sendAlert(alertHandshakeFailure)
   584  		return false, errors.New("tls: server advertised unrequested NPN extension")
   585  	}
   586  
   587  	if !clientDidALPN && serverHasALPN {
   588  		c.sendAlert(alertHandshakeFailure)
   589  		return false, errors.New("tls: server advertised unrequested ALPN extension")
   590  	}
   591  
   592  	if serverHasNPN && serverHasALPN {
   593  		c.sendAlert(alertHandshakeFailure)
   594  		return false, errors.New("tls: server advertised both NPN and ALPN extensions")
   595  	}
   596  
   597  	if serverHasALPN {
   598  		c.clientProtocol = hs.serverHello.alpnProtocol
   599  		c.clientProtocolFallback = false
   600  	}
   601  	c.scts = hs.serverHello.scts
   602  
   603  	if !hs.serverResumedSession() {
   604  		return false, nil
   605  	}
   606  
   607  	if hs.session.vers != c.vers {
   608  		c.sendAlert(alertHandshakeFailure)
   609  		return false, errors.New("tls: server resumed a session with a different version")
   610  	}
   611  
   612  	if hs.session.cipherSuite != hs.suite.id {
   613  		c.sendAlert(alertHandshakeFailure)
   614  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   615  	}
   616  
   617  	// Restore masterSecret and peerCerts from previous state
   618  	hs.masterSecret = hs.session.masterSecret
   619  	c.peerCertificates = hs.session.serverCertificates
   620  	c.verifiedChains = hs.session.verifiedChains
   621  	return true, nil
   622  }
   623  
   624  func (hs *clientHandshakeState) readFinished(out []byte) error {
   625  	c := hs.c
   626  
   627  	c.readRecord(recordTypeChangeCipherSpec)
   628  	if c.in.err != nil {
   629  		return c.in.err
   630  	}
   631  
   632  	msg, err := c.readHandshake()
   633  	if err != nil {
   634  		return err
   635  	}
   636  	serverFinished, ok := msg.(*finishedMsg)
   637  	if !ok {
   638  		c.sendAlert(alertUnexpectedMessage)
   639  		return unexpectedMessageError(serverFinished, msg)
   640  	}
   641  
   642  	verify := hs.finishedHash.serverSum(hs.masterSecret)
   643  	if len(verify) != len(serverFinished.verifyData) ||
   644  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
   645  		c.sendAlert(alertHandshakeFailure)
   646  		return errors.New("tls: server's Finished message was incorrect")
   647  	}
   648  	hs.finishedHash.Write(serverFinished.marshal())
   649  	copy(out, verify)
   650  	return nil
   651  }
   652  
   653  func (hs *clientHandshakeState) readSessionTicket() error {
   654  	if !hs.serverHello.ticketSupported {
   655  		return nil
   656  	}
   657  
   658  	c := hs.c
   659  	msg, err := c.readHandshake()
   660  	if err != nil {
   661  		return err
   662  	}
   663  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
   664  	if !ok {
   665  		c.sendAlert(alertUnexpectedMessage)
   666  		return unexpectedMessageError(sessionTicketMsg, msg)
   667  	}
   668  	hs.finishedHash.Write(sessionTicketMsg.marshal())
   669  
   670  	hs.session = &ClientSessionState{
   671  		sessionTicket:      sessionTicketMsg.ticket,
   672  		vers:               c.vers,
   673  		cipherSuite:        hs.suite.id,
   674  		masterSecret:       hs.masterSecret,
   675  		serverCertificates: c.peerCertificates,
   676  		verifiedChains:     c.verifiedChains,
   677  	}
   678  
   679  	return nil
   680  }
   681  
   682  func (hs *clientHandshakeState) sendFinished(out []byte) error {
   683  	c := hs.c
   684  
   685  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   686  		return err
   687  	}
   688  	if hs.serverHello.nextProtoNeg {
   689  		nextProto := new(nextProtoMsg)
   690  		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
   691  		nextProto.proto = proto
   692  		c.clientProtocol = proto
   693  		c.clientProtocolFallback = fallback
   694  
   695  		hs.finishedHash.Write(nextProto.marshal())
   696  		if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
   697  			return err
   698  		}
   699  	}
   700  
   701  	finished := new(finishedMsg)
   702  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
   703  	hs.finishedHash.Write(finished.marshal())
   704  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   705  		return err
   706  	}
   707  	copy(out, finished.verifyData)
   708  	return nil
   709  }
   710  
   711  // tls11SignatureSchemes contains the signature schemes that we synthesise for
   712  // a TLS <= 1.1 connection, based on the supported certificate types.
   713  var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
   714  
   715  const (
   716  	// tls11SignatureSchemesNumECDSA is the number of initial elements of
   717  	// tls11SignatureSchemes that use ECDSA.
   718  	tls11SignatureSchemesNumECDSA = 3
   719  	// tls11SignatureSchemesNumRSA is the number of trailing elements of
   720  	// tls11SignatureSchemes that use RSA.
   721  	tls11SignatureSchemesNumRSA = 4
   722  )
   723  
   724  func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
   725  	c := hs.c
   726  
   727  	var rsaAvail, ecdsaAvail bool
   728  	for _, certType := range certReq.certificateTypes {
   729  		switch certType {
   730  		case certTypeRSASign:
   731  			rsaAvail = true
   732  		case certTypeECDSASign:
   733  			ecdsaAvail = true
   734  		}
   735  	}
   736  
   737  	if c.config.GetClientCertificate != nil {
   738  		var signatureSchemes []SignatureScheme
   739  
   740  		if !certReq.hasSignatureAndHash {
   741  			// Prior to TLS 1.2, the signature schemes were not
   742  			// included in the certificate request message. In this
   743  			// case we use a plausible list based on the acceptable
   744  			// certificate types.
   745  			signatureSchemes = tls11SignatureSchemes
   746  			if !ecdsaAvail {
   747  				signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
   748  			}
   749  			if !rsaAvail {
   750  				signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
   751  			}
   752  		} else {
   753  			signatureSchemes = make([]SignatureScheme, 0, len(certReq.signatureAndHashes))
   754  			for _, sah := range certReq.signatureAndHashes {
   755  				signatureSchemes = append(signatureSchemes, SignatureScheme(sah.hash)<<8+SignatureScheme(sah.signature))
   756  			}
   757  		}
   758  
   759  		return c.config.GetClientCertificate(&CertificateRequestInfo{
   760  			AcceptableCAs:    certReq.certificateAuthorities,
   761  			SignatureSchemes: signatureSchemes,
   762  		})
   763  	}
   764  
   765  	// RFC 4346 on the certificateAuthorities field: A list of the
   766  	// distinguished names of acceptable certificate authorities.
   767  	// These distinguished names may specify a desired
   768  	// distinguished name for a root CA or for a subordinate CA;
   769  	// thus, this message can be used to describe both known roots
   770  	// and a desired authorization space. If the
   771  	// certificate_authorities list is empty then the client MAY
   772  	// send any certificate of the appropriate
   773  	// ClientCertificateType, unless there is some external
   774  	// arrangement to the contrary.
   775  
   776  	// We need to search our list of client certs for one
   777  	// where SignatureAlgorithm is acceptable to the server and the
   778  	// Issuer is in certReq.certificateAuthorities
   779  findCert:
   780  	for i, chain := range c.config.Certificates {
   781  		if !rsaAvail && !ecdsaAvail {
   782  			continue
   783  		}
   784  
   785  		for j, cert := range chain.Certificate {
   786  			x509Cert := chain.Leaf
   787  			// parse the certificate if this isn't the leaf
   788  			// node, or if chain.Leaf was nil
   789  			if j != 0 || x509Cert == nil {
   790  				var err error
   791  				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
   792  					c.sendAlert(alertInternalError)
   793  					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
   794  				}
   795  			}
   796  
   797  			switch {
   798  			case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
   799  			case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
   800  			default:
   801  				continue findCert
   802  			}
   803  
   804  			if len(certReq.certificateAuthorities) == 0 {
   805  				// they gave us an empty list, so just take the
   806  				// first cert from c.config.Certificates
   807  				return &chain, nil
   808  			}
   809  
   810  			for _, ca := range certReq.certificateAuthorities {
   811  				if bytes.Equal(x509Cert.RawIssuer, ca) {
   812  					return &chain, nil
   813  				}
   814  			}
   815  		}
   816  	}
   817  
   818  	// No acceptable certificate found. Don't send a certificate.
   819  	return new(Certificate), nil
   820  }
   821  
   822  // clientSessionCacheKey returns a key used to cache sessionTickets that could
   823  // be used to resume previously negotiated TLS sessions with a server.
   824  func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
   825  	if len(config.ServerName) > 0 {
   826  		return config.ServerName
   827  	}
   828  	return serverAddr.String()
   829  }
   830  
   831  // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
   832  // given list of possible protocols and a list of the preference order. The
   833  // first list must not be empty. It returns the resulting protocol and flag
   834  // indicating if the fallback case was reached.
   835  func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
   836  	for _, s := range preferenceProtos {
   837  		for _, c := range protos {
   838  			if s == c {
   839  				return s, false
   840  			}
   841  		}
   842  	}
   843  
   844  	return protos[0], true
   845  }
   846  
   847  // hostnameInSNI converts name into an approriate hostname for SNI.
   848  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
   849  // See https://tools.ietf.org/html/rfc6066#section-3.
   850  func hostnameInSNI(name string) string {
   851  	host := name
   852  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
   853  		host = host[1 : len(host)-1]
   854  	}
   855  	if i := strings.LastIndex(host, "%"); i > 0 {
   856  		host = host[:i]
   857  	}
   858  	if net.ParseIP(host) != nil {
   859  		return ""
   860  	}
   861  	for len(name) > 0 && name[len(name)-1] == '.' {
   862  		name = name[:len(name)-1]
   863  	}
   864  	return name
   865  }