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