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