github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/tls/handshake_server.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  	"context"
     9  	"crypto"
    10  	"crypto/ecdsa"
    11  	"crypto/ed25519"
    12  	"crypto/rsa"
    13  	"crypto/subtle"
    14  	"crypto/x509"
    15  	"errors"
    16  	"fmt"
    17  	"hash"
    18  	"io"
    19  	"time"
    20  )
    21  
    22  // serverHandshakeState contains details of a server handshake in progress.
    23  // It's discarded once the handshake has completed.
    24  type serverHandshakeState struct {
    25  	c            *Conn
    26  	ctx          context.Context
    27  	clientHello  *clientHelloMsg
    28  	hello        *serverHelloMsg
    29  	suite        *cipherSuite
    30  	ecdheOk      bool
    31  	ecSignOk     bool
    32  	rsaDecryptOk bool
    33  	rsaSignOk    bool
    34  	sessionState *SessionState
    35  	finishedHash finishedHash
    36  	masterSecret []byte
    37  	cert         *Certificate
    38  }
    39  
    40  // serverHandshake performs a TLS handshake as a server.
    41  func (c *Conn) serverHandshake(ctx context.Context) error {
    42  	clientHello, err := c.readClientHello(ctx)
    43  	if err != nil {
    44  		return err
    45  	}
    46  
    47  	// JLS_mark
    48  	if isValid, err := CheckJLSClientHello(c, clientHello); !isValid && err != nil {
    49  		fmt.Println(err)
    50  		return err
    51  	}
    52  
    53  	if c.vers == VersionTLS13 {
    54  		hs := serverHandshakeStateTLS13{
    55  			c:           c,
    56  			ctx:         ctx,
    57  			clientHello: clientHello,
    58  		}
    59  		return hs.handshake()
    60  	}
    61  
    62  	hs := serverHandshakeState{
    63  		c:           c,
    64  		ctx:         ctx,
    65  		clientHello: clientHello,
    66  	}
    67  	return hs.handshake()
    68  }
    69  
    70  func (hs *serverHandshakeState) handshake() error {
    71  	c := hs.c
    72  
    73  	if err := hs.processClientHello(); err != nil {
    74  		return err
    75  	}
    76  
    77  	// For an overview of TLS handshaking, see RFC 5246, Section 7.3.
    78  	c.buffering = true
    79  	if err := hs.checkForResumption(); err != nil {
    80  		return err
    81  	}
    82  	if hs.sessionState != nil {
    83  		// The client has included a session ticket and so we do an abbreviated handshake.
    84  		if err := hs.doResumeHandshake(); err != nil {
    85  			return err
    86  		}
    87  		if err := hs.establishKeys(); err != nil {
    88  			return err
    89  		}
    90  		if err := hs.sendSessionTicket(); err != nil {
    91  			return err
    92  		}
    93  		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
    94  			return err
    95  		}
    96  		if _, err := c.flush(); err != nil {
    97  			return err
    98  		}
    99  		c.clientFinishedIsFirst = false
   100  		if err := hs.readFinished(nil); err != nil {
   101  			return err
   102  		}
   103  	} else {
   104  		// The client didn't include a session ticket, or it wasn't
   105  		// valid so we do a full handshake.
   106  		if err := hs.pickCipherSuite(); err != nil {
   107  			return err
   108  		}
   109  		if err := hs.doFullHandshake(); err != nil {
   110  			return err
   111  		}
   112  		if err := hs.establishKeys(); err != nil {
   113  			return err
   114  		}
   115  		if err := hs.readFinished(c.clientFinished[:]); err != nil {
   116  			return err
   117  		}
   118  		c.clientFinishedIsFirst = true
   119  		c.buffering = true
   120  		if err := hs.sendSessionTicket(); err != nil {
   121  			return err
   122  		}
   123  		if err := hs.sendFinished(nil); err != nil {
   124  			return err
   125  		}
   126  		if _, err := c.flush(); err != nil {
   127  			return err
   128  		}
   129  	}
   130  
   131  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
   132  	c.isHandshakeComplete.Store(true)
   133  
   134  	return nil
   135  }
   136  
   137  // readClientHello reads a ClientHello message and selects the protocol version.
   138  func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
   139  	// clientHelloMsg is included in the transcript, but we haven't initialized
   140  	// it yet. The respective handshake functions will record it themselves.
   141  	msg, err := c.readHandshake(nil)
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  	clientHello, ok := msg.(*clientHelloMsg)
   146  	if !ok {
   147  		c.sendAlert(alertUnexpectedMessage)
   148  		return nil, unexpectedMessageError(clientHello, msg)
   149  	}
   150  
   151  	var configForClient *Config
   152  	originalConfig := c.config
   153  	if c.config.GetConfigForClient != nil {
   154  		chi := clientHelloInfo(ctx, c, clientHello)
   155  		if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
   156  			c.sendAlert(alertInternalError)
   157  			return nil, err
   158  		} else if configForClient != nil {
   159  			c.config = configForClient
   160  		}
   161  	}
   162  	c.ticketKeys = originalConfig.ticketKeys(configForClient)
   163  
   164  	clientVersions := clientHello.supportedVersions
   165  	if len(clientHello.supportedVersions) == 0 {
   166  		clientVersions = supportedVersionsFromMax(clientHello.vers)
   167  	}
   168  	c.vers, ok = c.config.mutualVersion(roleServer, clientVersions)
   169  	if !ok {
   170  		c.sendAlert(alertProtocolVersion)
   171  		return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
   172  	}
   173  	c.haveVers = true
   174  	c.in.version = c.vers
   175  	c.out.version = c.vers
   176  
   177  	return clientHello, nil
   178  }
   179  
   180  func (hs *serverHandshakeState) processClientHello() error {
   181  	c := hs.c
   182  
   183  	hs.hello = new(serverHelloMsg)
   184  	hs.hello.vers = c.vers
   185  
   186  	foundCompression := false
   187  	// We only support null compression, so check that the client offered it.
   188  	for _, compression := range hs.clientHello.compressionMethods {
   189  		if compression == compressionNone {
   190  			foundCompression = true
   191  			break
   192  		}
   193  	}
   194  
   195  	if !foundCompression {
   196  		c.sendAlert(alertHandshakeFailure)
   197  		return errors.New("tls: client does not support uncompressed connections")
   198  	}
   199  
   200  	hs.hello.random = make([]byte, 32)
   201  	serverRandom := hs.hello.random
   202  	// Downgrade protection canaries. See RFC 8446, Section 4.1.3.
   203  	maxVers := c.config.maxSupportedVersion(roleServer)
   204  	if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
   205  		if c.vers == VersionTLS12 {
   206  			copy(serverRandom[24:], downgradeCanaryTLS12)
   207  		} else {
   208  			copy(serverRandom[24:], downgradeCanaryTLS11)
   209  		}
   210  		serverRandom = serverRandom[:24]
   211  	}
   212  	_, err := io.ReadFull(c.config.rand(), serverRandom)
   213  	if err != nil {
   214  		c.sendAlert(alertInternalError)
   215  		return err
   216  	}
   217  
   218  	if len(hs.clientHello.secureRenegotiation) != 0 {
   219  		c.sendAlert(alertHandshakeFailure)
   220  		return errors.New("tls: initial handshake had non-empty renegotiation extension")
   221  	}
   222  
   223  	hs.hello.extendedMasterSecret = hs.clientHello.extendedMasterSecret
   224  	hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
   225  	hs.hello.compressionMethod = compressionNone
   226  	if len(hs.clientHello.serverName) > 0 {
   227  		c.serverName = hs.clientHello.serverName
   228  	}
   229  
   230  	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, false)
   231  	if err != nil {
   232  		c.sendAlert(alertNoApplicationProtocol)
   233  		return err
   234  	}
   235  	hs.hello.alpnProtocol = selectedProto
   236  	c.clientProtocol = selectedProto
   237  
   238  	hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
   239  	if err != nil {
   240  		if err == errNoCertificates {
   241  			c.sendAlert(alertUnrecognizedName)
   242  		} else {
   243  			c.sendAlert(alertInternalError)
   244  		}
   245  		return err
   246  	}
   247  	if hs.clientHello.scts {
   248  		hs.hello.scts = hs.cert.SignedCertificateTimestamps
   249  	}
   250  
   251  	hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
   252  
   253  	if hs.ecdheOk && len(hs.clientHello.supportedPoints) > 0 {
   254  		// Although omitting the ec_point_formats extension is permitted, some
   255  		// old OpenSSL version will refuse to handshake if not present.
   256  		//
   257  		// Per RFC 4492, section 5.1.2, implementations MUST support the
   258  		// uncompressed point format. See golang.org/issue/31943.
   259  		hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
   260  	}
   261  
   262  	if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
   263  		switch priv.Public().(type) {
   264  		case *ecdsa.PublicKey:
   265  			hs.ecSignOk = true
   266  		case ed25519.PublicKey:
   267  			hs.ecSignOk = true
   268  		case *rsa.PublicKey:
   269  			hs.rsaSignOk = true
   270  		default:
   271  			c.sendAlert(alertInternalError)
   272  			return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
   273  		}
   274  	}
   275  	if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
   276  		switch priv.Public().(type) {
   277  		case *rsa.PublicKey:
   278  			hs.rsaDecryptOk = true
   279  		default:
   280  			c.sendAlert(alertInternalError)
   281  			return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
   282  		}
   283  	}
   284  
   285  	return nil
   286  }
   287  
   288  // negotiateALPN picks a shared ALPN protocol that both sides support in server
   289  // preference order. If ALPN is not configured or the peer doesn't support it,
   290  // it returns "" and no error.
   291  func negotiateALPN(serverProtos, clientProtos []string, quic bool) (string, error) {
   292  	if len(serverProtos) == 0 || len(clientProtos) == 0 {
   293  		if quic && len(serverProtos) != 0 {
   294  			// RFC 9001, Section 8.1
   295  			return "", fmt.Errorf("tls: client did not request an application protocol")
   296  		}
   297  		return "", nil
   298  	}
   299  	var http11fallback bool
   300  	for _, s := range serverProtos {
   301  		for _, c := range clientProtos {
   302  			if s == c {
   303  				return s, nil
   304  			}
   305  			if s == "h2" && c == "http/1.1" {
   306  				http11fallback = true
   307  			}
   308  		}
   309  	}
   310  	// As a special case, let http/1.1 clients connect to h2 servers as if they
   311  	// didn't support ALPN. We used not to enforce protocol overlap, so over
   312  	// time a number of HTTP servers were configured with only "h2", but
   313  	// expected to accept connections from "http/1.1" clients. See Issue 46310.
   314  	if http11fallback {
   315  		return "", nil
   316  	}
   317  	return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos)
   318  }
   319  
   320  // supportsECDHE returns whether ECDHE key exchanges can be used with this
   321  // pre-TLS 1.3 client.
   322  func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
   323  	supportsCurve := false
   324  	for _, curve := range supportedCurves {
   325  		if c.supportsCurve(curve) {
   326  			supportsCurve = true
   327  			break
   328  		}
   329  	}
   330  
   331  	supportsPointFormat := false
   332  	for _, pointFormat := range supportedPoints {
   333  		if pointFormat == pointFormatUncompressed {
   334  			supportsPointFormat = true
   335  			break
   336  		}
   337  	}
   338  	// Per RFC 8422, Section 5.1.2, if the Supported Point Formats extension is
   339  	// missing, uncompressed points are supported. If supportedPoints is empty,
   340  	// the extension must be missing, as an empty extension body is rejected by
   341  	// the parser. See https://go.dev/issue/49126.
   342  	if len(supportedPoints) == 0 {
   343  		supportsPointFormat = true
   344  	}
   345  
   346  	return supportsCurve && supportsPointFormat
   347  }
   348  
   349  func (hs *serverHandshakeState) pickCipherSuite() error {
   350  	c := hs.c
   351  
   352  	preferenceOrder := cipherSuitesPreferenceOrder
   353  	if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
   354  		preferenceOrder = cipherSuitesPreferenceOrderNoAES
   355  	}
   356  
   357  	configCipherSuites := c.config.cipherSuites()
   358  	preferenceList := make([]uint16, 0, len(configCipherSuites))
   359  	for _, suiteID := range preferenceOrder {
   360  		for _, id := range configCipherSuites {
   361  			if id == suiteID {
   362  				preferenceList = append(preferenceList, id)
   363  				break
   364  			}
   365  		}
   366  	}
   367  
   368  	hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
   369  	if hs.suite == nil {
   370  		c.sendAlert(alertHandshakeFailure)
   371  		return errors.New("tls: no cipher suite supported by both client and server")
   372  	}
   373  	c.cipherSuite = hs.suite.id
   374  
   375  	for _, id := range hs.clientHello.cipherSuites {
   376  		if id == TLS_FALLBACK_SCSV {
   377  			// The client is doing a fallback connection. See RFC 7507.
   378  			if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) {
   379  				c.sendAlert(alertInappropriateFallback)
   380  				return errors.New("tls: client using inappropriate protocol fallback")
   381  			}
   382  			break
   383  		}
   384  	}
   385  
   386  	return nil
   387  }
   388  
   389  func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
   390  	if c.flags&suiteECDHE != 0 {
   391  		if !hs.ecdheOk {
   392  			return false
   393  		}
   394  		if c.flags&suiteECSign != 0 {
   395  			if !hs.ecSignOk {
   396  				return false
   397  			}
   398  		} else if !hs.rsaSignOk {
   399  			return false
   400  		}
   401  	} else if !hs.rsaDecryptOk {
   402  		return false
   403  	}
   404  	if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
   405  		return false
   406  	}
   407  	return true
   408  }
   409  
   410  // checkForResumption reports whether we should perform resumption on this connection.
   411  func (hs *serverHandshakeState) checkForResumption() error {
   412  	c := hs.c
   413  
   414  	if c.config.SessionTicketsDisabled {
   415  		return nil
   416  	}
   417  
   418  	var sessionState *SessionState
   419  	if c.config.UnwrapSession != nil {
   420  		ss, err := c.config.UnwrapSession(hs.clientHello.sessionTicket, c.connectionStateLocked())
   421  		if err != nil {
   422  			return err
   423  		}
   424  		if ss == nil {
   425  			return nil
   426  		}
   427  		sessionState = ss
   428  	} else {
   429  		plaintext := c.config.decryptTicket(hs.clientHello.sessionTicket, c.ticketKeys)
   430  		if plaintext == nil {
   431  			return nil
   432  		}
   433  		ss, err := ParseSessionState(plaintext)
   434  		if err != nil {
   435  			return nil
   436  		}
   437  		sessionState = ss
   438  	}
   439  
   440  	// TLS 1.2 tickets don't natively have a lifetime, but we want to avoid
   441  	// re-wrapping the same master secret in different tickets over and over for
   442  	// too long, weakening forward secrecy.
   443  	createdAt := time.Unix(int64(sessionState.createdAt), 0)
   444  	if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   445  		return nil
   446  	}
   447  
   448  	// Never resume a session for a different TLS version.
   449  	if c.vers != sessionState.version {
   450  		return nil
   451  	}
   452  
   453  	cipherSuiteOk := false
   454  	// Check that the client is still offering the ciphersuite in the session.
   455  	for _, id := range hs.clientHello.cipherSuites {
   456  		if id == sessionState.cipherSuite {
   457  			cipherSuiteOk = true
   458  			break
   459  		}
   460  	}
   461  	if !cipherSuiteOk {
   462  		return nil
   463  	}
   464  
   465  	// Check that we also support the ciphersuite from the session.
   466  	suite := selectCipherSuite([]uint16{sessionState.cipherSuite},
   467  		c.config.cipherSuites(), hs.cipherSuiteOk)
   468  	if suite == nil {
   469  		return nil
   470  	}
   471  
   472  	sessionHasClientCerts := len(sessionState.peerCertificates) != 0
   473  	needClientCerts := requiresClientCert(c.config.ClientAuth)
   474  	if needClientCerts && !sessionHasClientCerts {
   475  		return nil
   476  	}
   477  	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   478  		return nil
   479  	}
   480  	if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
   481  		return nil
   482  	}
   483  	if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
   484  		len(sessionState.verifiedChains) == 0 {
   485  		return nil
   486  	}
   487  
   488  	// RFC 7627, Section 5.3
   489  	if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
   490  		return nil
   491  	}
   492  	if sessionState.extMasterSecret && !hs.clientHello.extendedMasterSecret {
   493  		// Aborting is somewhat harsh, but it's a MUST and it would indicate a
   494  		// weird downgrade in client capabilities.
   495  		return errors.New("tls: session supported extended_master_secret but client does not")
   496  	}
   497  
   498  	c.peerCertificates = sessionState.peerCertificates
   499  	c.ocspResponse = sessionState.ocspResponse
   500  	c.scts = sessionState.scts
   501  	c.verifiedChains = sessionState.verifiedChains
   502  	c.extMasterSecret = sessionState.extMasterSecret
   503  	hs.sessionState = sessionState
   504  	hs.suite = suite
   505  	c.didResume = true
   506  	return nil
   507  }
   508  
   509  func (hs *serverHandshakeState) doResumeHandshake() error {
   510  	c := hs.c
   511  
   512  	hs.hello.cipherSuite = hs.suite.id
   513  	c.cipherSuite = hs.suite.id
   514  	// We echo the client's session ID in the ServerHello to let it know
   515  	// that we're doing a resumption.
   516  	hs.hello.sessionId = hs.clientHello.sessionId
   517  	// We always send a new session ticket, even if it wraps the same master
   518  	// secret and it's potentially encrypted with the same key, to help the
   519  	// client avoid cross-connection tracking from a network observer.
   520  	hs.hello.ticketSupported = true
   521  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   522  	hs.finishedHash.discardHandshakeBuffer()
   523  	if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
   524  		return err
   525  	}
   526  	if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
   527  		return err
   528  	}
   529  
   530  	if c.config.VerifyConnection != nil {
   531  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   532  			c.sendAlert(alertBadCertificate)
   533  			return err
   534  		}
   535  	}
   536  
   537  	hs.masterSecret = hs.sessionState.secret
   538  
   539  	return nil
   540  }
   541  
   542  func (hs *serverHandshakeState) doFullHandshake() error {
   543  	c := hs.c
   544  
   545  	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
   546  		hs.hello.ocspStapling = true
   547  	}
   548  
   549  	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
   550  	hs.hello.cipherSuite = hs.suite.id
   551  
   552  	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
   553  	if c.config.ClientAuth == NoClientCert {
   554  		// No need to keep a full record of the handshake if client
   555  		// certificates won't be used.
   556  		hs.finishedHash.discardHandshakeBuffer()
   557  	}
   558  	if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
   559  		return err
   560  	}
   561  	if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
   562  		return err
   563  	}
   564  
   565  	certMsg := new(certificateMsg)
   566  	certMsg.certificates = hs.cert.Certificate
   567  	if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
   568  		return err
   569  	}
   570  
   571  	if hs.hello.ocspStapling {
   572  		certStatus := new(certificateStatusMsg)
   573  		certStatus.response = hs.cert.OCSPStaple
   574  		if _, err := hs.c.writeHandshakeRecord(certStatus, &hs.finishedHash); err != nil {
   575  			return err
   576  		}
   577  	}
   578  
   579  	keyAgreement := hs.suite.ka(c.vers)
   580  	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
   581  	if err != nil {
   582  		c.sendAlert(alertHandshakeFailure)
   583  		return err
   584  	}
   585  	if skx != nil {
   586  		if _, err := hs.c.writeHandshakeRecord(skx, &hs.finishedHash); err != nil {
   587  			return err
   588  		}
   589  	}
   590  
   591  	var certReq *certificateRequestMsg
   592  	if c.config.ClientAuth >= RequestClientCert {
   593  		// Request a client certificate
   594  		certReq = new(certificateRequestMsg)
   595  		certReq.certificateTypes = []byte{
   596  			byte(certTypeRSASign),
   597  			byte(certTypeECDSASign),
   598  		}
   599  		if c.vers >= VersionTLS12 {
   600  			certReq.hasSignatureAlgorithm = true
   601  			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
   602  		}
   603  
   604  		// An empty list of certificateAuthorities signals to
   605  		// the client that it may send any certificate in response
   606  		// to our request. When we know the CAs we trust, then
   607  		// we can send them down, so that the client can choose
   608  		// an appropriate certificate to give to us.
   609  		if c.config.ClientCAs != nil {
   610  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   611  		}
   612  		if _, err := hs.c.writeHandshakeRecord(certReq, &hs.finishedHash); err != nil {
   613  			return err
   614  		}
   615  	}
   616  
   617  	helloDone := new(serverHelloDoneMsg)
   618  	if _, err := hs.c.writeHandshakeRecord(helloDone, &hs.finishedHash); err != nil {
   619  		return err
   620  	}
   621  
   622  	if _, err := c.flush(); err != nil {
   623  		return err
   624  	}
   625  
   626  	var pub crypto.PublicKey // public key for client auth, if any
   627  
   628  	msg, err := c.readHandshake(&hs.finishedHash)
   629  	if err != nil {
   630  		return err
   631  	}
   632  
   633  	// If we requested a client certificate, then the client must send a
   634  	// certificate message, even if it's empty.
   635  	if c.config.ClientAuth >= RequestClientCert {
   636  		certMsg, ok := msg.(*certificateMsg)
   637  		if !ok {
   638  			c.sendAlert(alertUnexpectedMessage)
   639  			return unexpectedMessageError(certMsg, msg)
   640  		}
   641  
   642  		if err := c.processCertsFromClient(Certificate{
   643  			Certificate: certMsg.certificates,
   644  		}); err != nil {
   645  			return err
   646  		}
   647  		if len(certMsg.certificates) != 0 {
   648  			pub = c.peerCertificates[0].PublicKey
   649  		}
   650  
   651  		msg, err = c.readHandshake(&hs.finishedHash)
   652  		if err != nil {
   653  			return err
   654  		}
   655  	}
   656  	if c.config.VerifyConnection != nil {
   657  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   658  			c.sendAlert(alertBadCertificate)
   659  			return err
   660  		}
   661  	}
   662  
   663  	// Get client key exchange
   664  	ckx, ok := msg.(*clientKeyExchangeMsg)
   665  	if !ok {
   666  		c.sendAlert(alertUnexpectedMessage)
   667  		return unexpectedMessageError(ckx, msg)
   668  	}
   669  
   670  	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
   671  	if err != nil {
   672  		c.sendAlert(alertHandshakeFailure)
   673  		return err
   674  	}
   675  	if hs.hello.extendedMasterSecret {
   676  		c.extMasterSecret = true
   677  		hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   678  			hs.finishedHash.Sum())
   679  	} else {
   680  		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   681  			hs.clientHello.random, hs.hello.random)
   682  	}
   683  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
   684  		c.sendAlert(alertInternalError)
   685  		return err
   686  	}
   687  
   688  	// If we received a client cert in response to our certificate request message,
   689  	// the client will send us a certificateVerifyMsg immediately after the
   690  	// clientKeyExchangeMsg. This message is a digest of all preceding
   691  	// handshake-layer messages that is signed using the private key corresponding
   692  	// to the client's certificate. This allows us to verify that the client is in
   693  	// possession of the private key of the certificate.
   694  	if len(c.peerCertificates) > 0 {
   695  		// certificateVerifyMsg is included in the transcript, but not until
   696  		// after we verify the handshake signature, since the state before
   697  		// this message was sent is used.
   698  		msg, err = c.readHandshake(nil)
   699  		if err != nil {
   700  			return err
   701  		}
   702  		certVerify, ok := msg.(*certificateVerifyMsg)
   703  		if !ok {
   704  			c.sendAlert(alertUnexpectedMessage)
   705  			return unexpectedMessageError(certVerify, msg)
   706  		}
   707  
   708  		var sigType uint8
   709  		var sigHash crypto.Hash
   710  		if c.vers >= VersionTLS12 {
   711  			if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
   712  				c.sendAlert(alertIllegalParameter)
   713  				return errors.New("tls: client certificate used with invalid signature algorithm")
   714  			}
   715  			sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   716  			if err != nil {
   717  				return c.sendAlert(alertInternalError)
   718  			}
   719  		} else {
   720  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
   721  			if err != nil {
   722  				c.sendAlert(alertIllegalParameter)
   723  				return err
   724  			}
   725  		}
   726  
   727  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
   728  		if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
   729  			c.sendAlert(alertDecryptError)
   730  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   731  		}
   732  
   733  		if err := transcriptMsg(certVerify, &hs.finishedHash); err != nil {
   734  			return err
   735  		}
   736  	}
   737  
   738  	hs.finishedHash.discardHandshakeBuffer()
   739  
   740  	return nil
   741  }
   742  
   743  func (hs *serverHandshakeState) establishKeys() error {
   744  	c := hs.c
   745  
   746  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   747  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   748  
   749  	var clientCipher, serverCipher any
   750  	var clientHash, serverHash hash.Hash
   751  
   752  	if hs.suite.aead == nil {
   753  		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
   754  		clientHash = hs.suite.mac(clientMAC)
   755  		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
   756  		serverHash = hs.suite.mac(serverMAC)
   757  	} else {
   758  		clientCipher = hs.suite.aead(clientKey, clientIV)
   759  		serverCipher = hs.suite.aead(serverKey, serverIV)
   760  	}
   761  
   762  	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
   763  	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
   764  
   765  	return nil
   766  }
   767  
   768  func (hs *serverHandshakeState) readFinished(out []byte) error {
   769  	c := hs.c
   770  
   771  	if err := c.readChangeCipherSpec(); err != nil {
   772  		return err
   773  	}
   774  
   775  	// finishedMsg is included in the transcript, but not until after we
   776  	// check the client version, since the state before this message was
   777  	// sent is used during verification.
   778  	msg, err := c.readHandshake(nil)
   779  	if err != nil {
   780  		return err
   781  	}
   782  	clientFinished, ok := msg.(*finishedMsg)
   783  	if !ok {
   784  		c.sendAlert(alertUnexpectedMessage)
   785  		return unexpectedMessageError(clientFinished, msg)
   786  	}
   787  
   788  	verify := hs.finishedHash.clientSum(hs.masterSecret)
   789  	if len(verify) != len(clientFinished.verifyData) ||
   790  		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
   791  		c.sendAlert(alertHandshakeFailure)
   792  		return errors.New("tls: client's Finished message is incorrect")
   793  	}
   794  
   795  	if err := transcriptMsg(clientFinished, &hs.finishedHash); err != nil {
   796  		return err
   797  	}
   798  
   799  	copy(out, verify)
   800  	return nil
   801  }
   802  
   803  func (hs *serverHandshakeState) sendSessionTicket() error {
   804  	if !hs.hello.ticketSupported {
   805  		return nil
   806  	}
   807  
   808  	c := hs.c
   809  	m := new(newSessionTicketMsg)
   810  
   811  	state, err := c.sessionState()
   812  	if err != nil {
   813  		return err
   814  	}
   815  	state.secret = hs.masterSecret
   816  	if hs.sessionState != nil {
   817  		// If this is re-wrapping an old key, then keep
   818  		// the original time it was created.
   819  		state.createdAt = hs.sessionState.createdAt
   820  	}
   821  	if c.config.WrapSession != nil {
   822  		m.ticket, err = c.config.WrapSession(c.connectionStateLocked(), state)
   823  		if err != nil {
   824  			return err
   825  		}
   826  	} else {
   827  		stateBytes, err := state.Bytes()
   828  		if err != nil {
   829  			return err
   830  		}
   831  		m.ticket, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
   832  		if err != nil {
   833  			return err
   834  		}
   835  	}
   836  
   837  	if _, err := hs.c.writeHandshakeRecord(m, &hs.finishedHash); err != nil {
   838  		return err
   839  	}
   840  
   841  	return nil
   842  }
   843  
   844  func (hs *serverHandshakeState) 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.serverSum(hs.masterSecret)
   853  	if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
   854  		return err
   855  	}
   856  
   857  	copy(out, finished.verifyData)
   858  
   859  	return nil
   860  }
   861  
   862  // processCertsFromClient takes a chain of client certificates either from a
   863  // Certificates message and verifies them.
   864  func (c *Conn) processCertsFromClient(certificate Certificate) error {
   865  	certificates := certificate.Certificate
   866  	certs := make([]*x509.Certificate, len(certificates))
   867  	var err error
   868  	for i, asn1Data := range certificates {
   869  		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
   870  			c.sendAlert(alertBadCertificate)
   871  			return errors.New("tls: failed to parse client certificate: " + err.Error())
   872  		}
   873  	}
   874  
   875  	if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
   876  		if c.vers == VersionTLS13 {
   877  			c.sendAlert(alertCertificateRequired)
   878  		} else {
   879  			c.sendAlert(alertBadCertificate)
   880  		}
   881  		return errors.New("tls: client didn't provide a certificate")
   882  	}
   883  
   884  	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
   885  		opts := x509.VerifyOptions{
   886  			Roots:         c.config.ClientCAs,
   887  			CurrentTime:   c.config.time(),
   888  			Intermediates: x509.NewCertPool(),
   889  			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
   890  		}
   891  
   892  		for _, cert := range certs[1:] {
   893  			opts.Intermediates.AddCert(cert)
   894  		}
   895  
   896  		chains, err := certs[0].Verify(opts)
   897  		if err != nil {
   898  			var errCertificateInvalid x509.CertificateInvalidError
   899  			if errors.As(err, &x509.UnknownAuthorityError{}) {
   900  				c.sendAlert(alertUnknownCA)
   901  			} else if errors.As(err, &errCertificateInvalid) && errCertificateInvalid.Reason == x509.Expired {
   902  				c.sendAlert(alertCertificateExpired)
   903  			} else {
   904  				c.sendAlert(alertBadCertificate)
   905  			}
   906  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
   907  		}
   908  
   909  		c.verifiedChains = chains
   910  	}
   911  
   912  	c.peerCertificates = certs
   913  	c.ocspResponse = certificate.OCSPStaple
   914  	c.scts = certificate.SignedCertificateTimestamps
   915  
   916  	if len(certs) > 0 {
   917  		switch certs[0].PublicKey.(type) {
   918  		case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
   919  		default:
   920  			c.sendAlert(alertUnsupportedCertificate)
   921  			return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
   922  		}
   923  	}
   924  
   925  	if c.config.VerifyPeerCertificate != nil {
   926  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   927  			c.sendAlert(alertBadCertificate)
   928  			return err
   929  		}
   930  	}
   931  
   932  	return nil
   933  }
   934  
   935  func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
   936  	supportedVersions := clientHello.supportedVersions
   937  	if len(clientHello.supportedVersions) == 0 {
   938  		supportedVersions = supportedVersionsFromMax(clientHello.vers)
   939  	}
   940  
   941  	return &ClientHelloInfo{
   942  		CipherSuites:      clientHello.cipherSuites,
   943  		ServerName:        clientHello.serverName,
   944  		SupportedCurves:   clientHello.supportedCurves,
   945  		SupportedPoints:   clientHello.supportedPoints,
   946  		SignatureSchemes:  clientHello.supportedSignatureAlgorithms,
   947  		SupportedProtos:   clientHello.alpnProtocols,
   948  		SupportedVersions: supportedVersions,
   949  		Conn:              c.conn,
   950  		config:            c.config,
   951  		ctx:               ctx,
   952  	}
   953  }