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