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