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