github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/handshake_server.go (about)

     1  // Copyright (c) 2022 zhaochun
     2  // gmgo is licensed under Mulan PSL v2.
     3  // You can use this software according to the terms and conditions of the Mulan PSL v2.
     4  // You may obtain a copy of Mulan PSL v2 at:
     5  //          http://license.coscl.org.cn/MulanPSL2
     6  // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
     7  // See the Mulan PSL v2 for more details.
     8  
     9  /*
    10  gmtls是基于`golang/go`的`tls`包实现的国密改造版本。
    11  对应版权声明: thrid_licenses/github.com/golang/go/LICENSE
    12  */
    13  
    14  package gmtls
    15  
    16  import (
    17  	"context"
    18  	"crypto"
    19  	"crypto/ecdsa"
    20  	"crypto/ed25519"
    21  	"crypto/rsa"
    22  	"crypto/subtle"
    23  	"errors"
    24  	"fmt"
    25  	"hash"
    26  	"io"
    27  	"sync/atomic"
    28  	"time"
    29  
    30  	"gitee.com/zhaochuninhefei/zcgolog/zclog"
    31  	"github.com/hxx258456/ccgo/sm2"
    32  	"github.com/hxx258456/ccgo/x509"
    33  )
    34  
    35  // serverHandshakeState contains details of a server handshake in progress.
    36  // It's discarded once the handshake has completed.
    37  type serverHandshakeState struct {
    38  	c            *Conn
    39  	ctx          context.Context
    40  	clientHello  *clientHelloMsg
    41  	hello        *serverHelloMsg
    42  	suite        *cipherSuite
    43  	ecdheOk      bool
    44  	ecSignOk     bool
    45  	rsaDecryptOk bool
    46  	rsaSignOk    bool
    47  	sessionState *sessionState
    48  	finishedHash finishedHash
    49  	masterSecret []byte
    50  	cert         *Certificate
    51  }
    52  
    53  // 服务端握手
    54  // serverHandshake performs a TLS handshake as a server.
    55  func (c *Conn) serverHandshake(ctx context.Context) error {
    56  	zclog.Debug("===== 开始服务端握手过程")
    57  	// 读取 ClientHello
    58  	clientHello, err := c.readClientHello(ctx)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	// GMSSL目前采用tls1.3的处理
    63  	if c.vers == VersionTLS13 || c.vers == VersionGMSSL {
    64  		zclog.Debug("===== 服务端执行tls1.3或gmssl的握手过程")
    65  		hs := serverHandshakeStateTLS13{
    66  			c:           c,
    67  			ctx:         ctx,
    68  			clientHello: clientHello,
    69  		}
    70  		return hs.handshake()
    71  	}
    72  	zclog.Debug("===== 服务端执行tls1.2或更老版本的握手过程")
    73  	hs := serverHandshakeState{
    74  		c:           c,
    75  		ctx:         ctx,
    76  		clientHello: clientHello,
    77  	}
    78  	return hs.handshake()
    79  }
    80  
    81  // tls1.2及更老版本在读取ClientHello之后的握手过程
    82  func (hs *serverHandshakeState) handshake() error {
    83  	c := hs.c
    84  
    85  	if err := hs.processClientHello(); err != nil {
    86  		return err
    87  	}
    88  
    89  	// For an overview of TLS handshaking, see RFC 5246, Section 7.3.
    90  	c.buffering = true
    91  	if hs.checkForResumption() {
    92  		// The client has included a session ticket and so we do an abbreviated handshake.
    93  		c.didResume = true
    94  		if err := hs.doResumeHandshake(); err != nil {
    95  			return err
    96  		}
    97  		if err := hs.establishKeys(); err != nil {
    98  			return err
    99  		}
   100  		if err := hs.sendSessionTicket(); err != nil {
   101  			return err
   102  		}
   103  		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
   104  			return err
   105  		}
   106  		if _, err := c.flush(); err != nil {
   107  			return err
   108  		}
   109  		c.clientFinishedIsFirst = false
   110  		if err := hs.readFinished(nil); err != nil {
   111  			return err
   112  		}
   113  	} else {
   114  		// The client didn't include a session ticket, or it wasn't
   115  		// valid so we do a full handshake.
   116  		if err := hs.pickCipherSuite(); err != nil {
   117  			return err
   118  		}
   119  		if err := hs.doFullHandshake(); err != nil {
   120  			return err
   121  		}
   122  		if err := hs.establishKeys(); err != nil {
   123  			return err
   124  		}
   125  		if err := hs.readFinished(c.clientFinished[:]); err != nil {
   126  			return err
   127  		}
   128  		c.clientFinishedIsFirst = true
   129  		c.buffering = true
   130  		if err := hs.sendSessionTicket(); err != nil {
   131  			return err
   132  		}
   133  		if err := hs.sendFinished(nil); err != nil {
   134  			return err
   135  		}
   136  		if _, err := c.flush(); err != nil {
   137  			return err
   138  		}
   139  	}
   140  
   141  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
   142  	atomic.StoreUint32(&c.handshakeStatus, 1)
   143  
   144  	return nil
   145  }
   146  
   147  // 读取ClientHello并选择协议版本。
   148  // readClientHello reads a ClientHello message and selects the protocol version.
   149  func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
   150  	// 读取ClientHello
   151  	msg, err := c.readHandshake()
   152  	if err != nil {
   153  		return nil, err
   154  	}
   155  	clientHello, ok := msg.(*clientHelloMsg)
   156  	if !ok {
   157  		_ = c.sendAlert(alertUnexpectedMessage)
   158  		return nil, unexpectedMessageError(clientHello, msg)
   159  	}
   160  	zclog.Debug("===== 服务端读取到 ClientHello")
   161  
   162  	var configForClient *Config
   163  	originalConfig := c.config
   164  	if c.config.GetConfigForClient != nil {
   165  		chi := clientHelloInfo(ctx, c, clientHello)
   166  		if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
   167  			_ = c.sendAlert(alertInternalError)
   168  			return nil, fmt.Errorf("gmtls: GetConfigForClient时发生错误: %s", err)
   169  		} else if configForClient != nil {
   170  			c.config = configForClient
   171  		}
   172  	}
   173  	// 为当前连接设置ticketKeys
   174  	c.ticketKeys = originalConfig.ticketKeys(configForClient)
   175  	// 获取ClientHello的协议版本信息,默认使用supportedVersions,没有设置supportedVersions的情况下使用vers
   176  	clientVersions := clientHello.supportedVersions
   177  	if len(clientHello.supportedVersions) == 0 {
   178  		clientVersions = supportedVersionsFromMax(clientHello.vers)
   179  	}
   180  	// 协商tls协议版本
   181  	c.vers, ok = c.config.mutualVersion(clientVersions)
   182  	if !ok {
   183  		_ = c.sendAlert(alertProtocolVersion)
   184  		return nil, fmt.Errorf("gmtls: client offered only unsupported versions: %x", clientVersions)
   185  	}
   186  	zclog.Debug("===== 服务端选择本次tls连接使用的版本是:", ShowTLSVersion(int(c.vers)))
   187  	c.haveVers = true
   188  	c.in.version = c.vers
   189  	c.out.version = c.vers
   190  
   191  	return clientHello, nil
   192  }
   193  
   194  func (hs *serverHandshakeState) processClientHello() error {
   195  	c := hs.c
   196  
   197  	hs.hello = new(serverHelloMsg)
   198  	hs.hello.vers = c.vers
   199  
   200  	foundCompression := false
   201  	// We only support null compression, so check that the client offered it.
   202  	for _, compression := range hs.clientHello.compressionMethods {
   203  		if compression == compressionNone {
   204  			foundCompression = true
   205  			break
   206  		}
   207  	}
   208  
   209  	if !foundCompression {
   210  		_ = c.sendAlert(alertHandshakeFailure)
   211  		return errors.New("gmtls: client does not support uncompressed connections")
   212  	}
   213  
   214  	hs.hello.random = make([]byte, 32)
   215  	serverRandom := hs.hello.random
   216  	// Downgrade protection canaries. See RFC 8446, Section 4.1.3.
   217  	maxVers := c.config.maxSupportedVersion()
   218  	if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
   219  		if c.vers == VersionTLS12 {
   220  			copy(serverRandom[24:], downgradeCanaryTLS12)
   221  		} else {
   222  			copy(serverRandom[24:], downgradeCanaryTLS11)
   223  		}
   224  		serverRandom = serverRandom[:24]
   225  	}
   226  	_, err := io.ReadFull(c.config.rand(), serverRandom)
   227  	if err != nil {
   228  		_ = c.sendAlert(alertInternalError)
   229  		return fmt.Errorf("gmtls: 创建serverRandom失败: %s", err)
   230  	}
   231  
   232  	if len(hs.clientHello.secureRenegotiation) != 0 {
   233  		_ = c.sendAlert(alertHandshakeFailure)
   234  		return errors.New("gmtls: initial handshake had non-empty renegotiation extension")
   235  	}
   236  
   237  	hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
   238  	hs.hello.compressionMethod = compressionNone
   239  	if len(hs.clientHello.serverName) > 0 {
   240  		c.serverName = hs.clientHello.serverName
   241  	}
   242  
   243  	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols)
   244  	if err != nil {
   245  		_ = c.sendAlert(alertNoApplicationProtocol)
   246  		return err
   247  	}
   248  	hs.hello.alpnProtocol = selectedProto
   249  	c.clientProtocol = selectedProto
   250  
   251  	hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
   252  	if err != nil {
   253  		var alt alert
   254  		if err == errNoCertificates {
   255  			alt = alertUnrecognizedName
   256  		} else {
   257  			alt = alertInternalError
   258  		}
   259  		_ = c.sendAlert(alt)
   260  		return err
   261  	}
   262  	if hs.clientHello.scts {
   263  		hs.hello.scts = hs.cert.SignedCertificateTimestamps
   264  	}
   265  
   266  	hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
   267  
   268  	if hs.ecdheOk {
   269  		// Although omitting the ec_point_formats extension is permitted, some
   270  		// old OpenSSL version will refuse to handshake if not present.
   271  		//
   272  		// Per RFC 4492, section 5.1.2, implementations MUST support the
   273  		// uncompressed point format. See golang.org/issue/31943.
   274  		hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
   275  	}
   276  
   277  	if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
   278  		switch priv.Public().(type) {
   279  		case *sm2.PublicKey, *ecdsa.PublicKey:
   280  			hs.ecSignOk = true
   281  		case ed25519.PublicKey:
   282  			hs.ecSignOk = true
   283  		case *rsa.PublicKey:
   284  			hs.rsaSignOk = true
   285  		default:
   286  			_ = c.sendAlert(alertInternalError)
   287  			return fmt.Errorf("gmtls: unsupported signing key type (%T)", priv.Public())
   288  		}
   289  	}
   290  	if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
   291  		switch priv.Public().(type) {
   292  		case *rsa.PublicKey:
   293  			hs.rsaDecryptOk = true
   294  		default:
   295  			_ = c.sendAlert(alertInternalError)
   296  			return fmt.Errorf("gmtls: unsupported decryption key type (%T)", priv.Public())
   297  		}
   298  	}
   299  
   300  	return nil
   301  }
   302  
   303  // negotiateALPN picks a shared ALPN protocol that both sides support in server
   304  // preference order. If ALPN is not configured or the peer doesn't support it,
   305  // it returns "" and no error.
   306  func negotiateALPN(serverProtos, clientProtos []string) (string, error) {
   307  	if len(serverProtos) == 0 || len(clientProtos) == 0 {
   308  		return "", nil
   309  	}
   310  	var http11fallback bool
   311  	for _, s := range serverProtos {
   312  		for _, c := range clientProtos {
   313  			if s == c {
   314  				return s, nil
   315  			}
   316  			if s == "h2" && c == "http/1.1" {
   317  				http11fallback = true
   318  			}
   319  		}
   320  	}
   321  	// As a special case, let http/1.1 clients connect to h2 servers as if they
   322  	// didn't support ALPN. We used not to enforce protocol overlap, so over
   323  	// time a number of HTTP servers were configured with only "h2", but
   324  	// expected to accept connections from "http/1.1" clients. See Issue 46310.
   325  	if http11fallback {
   326  		return "", nil
   327  	}
   328  	return "", fmt.Errorf("gmtls: client requested unsupported application protocols (%s)", clientProtos)
   329  }
   330  
   331  // supportsECDHE returns whether ECDHE key exchanges can be used with this
   332  // pre-TLS 1.3 client.
   333  func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool {
   334  	supportsCurve := false
   335  	for _, curve := range supportedCurves {
   336  		if c.supportsCurve(curve) {
   337  			supportsCurve = true
   338  			break
   339  		}
   340  	}
   341  
   342  	supportsPointFormat := false
   343  	for _, pointFormat := range supportedPoints {
   344  		if pointFormat == pointFormatUncompressed {
   345  			supportsPointFormat = true
   346  			break
   347  		}
   348  	}
   349  
   350  	return supportsCurve && supportsPointFormat
   351  }
   352  
   353  func (hs *serverHandshakeState) pickCipherSuite() error {
   354  	c := hs.c
   355  
   356  	preferenceOrder := cipherSuitesPreferenceOrder
   357  	if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
   358  		preferenceOrder = cipherSuitesPreferenceOrderNoAES
   359  	}
   360  
   361  	configCipherSuites := c.config.cipherSuites()
   362  	preferenceList := make([]uint16, 0, len(configCipherSuites))
   363  	for _, suiteID := range preferenceOrder {
   364  		for _, id := range configCipherSuites {
   365  			if id == suiteID {
   366  				preferenceList = append(preferenceList, id)
   367  				break
   368  			}
   369  		}
   370  	}
   371  
   372  	hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
   373  	if hs.suite == nil {
   374  		_ = c.sendAlert(alertHandshakeFailure)
   375  		return errors.New("gmtls: no cipher suite supported by both client and server")
   376  	}
   377  	c.cipherSuite = hs.suite.id
   378  
   379  	for _, id := range hs.clientHello.cipherSuites {
   380  		if id == TLS_FALLBACK_SCSV {
   381  			// The client is doing a fallback connection. See RFC 7507.
   382  			if hs.clientHello.vers < c.config.maxSupportedVersion() {
   383  				_ = c.sendAlert(alertInappropriateFallback)
   384  				return errors.New("gmtls: client using inappropriate protocol fallback")
   385  			}
   386  			break
   387  		}
   388  	}
   389  
   390  	return nil
   391  }
   392  
   393  func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
   394  	if c.flags&suiteECDHE != 0 {
   395  		if !hs.ecdheOk {
   396  			return false
   397  		}
   398  		if c.flags&suiteECSign != 0 {
   399  			if !hs.ecSignOk {
   400  				return false
   401  			}
   402  		} else if !hs.rsaSignOk {
   403  			return false
   404  		}
   405  	} else if !hs.rsaDecryptOk {
   406  		return false
   407  	}
   408  	if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
   409  		return false
   410  	}
   411  	return true
   412  }
   413  
   414  // checkForResumption reports whether we should perform resumption on this connection.
   415  func (hs *serverHandshakeState) checkForResumption() bool {
   416  	c := hs.c
   417  
   418  	if c.config.SessionTicketsDisabled {
   419  		return false
   420  	}
   421  
   422  	plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket)
   423  	if plaintext == nil {
   424  		return false
   425  	}
   426  	hs.sessionState = &sessionState{usedOldKey: usedOldKey}
   427  	ok := hs.sessionState.unmarshal(plaintext)
   428  	if !ok {
   429  		return false
   430  	}
   431  
   432  	createdAt := time.Unix(int64(hs.sessionState.createdAt), 0)
   433  	if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   434  		return false
   435  	}
   436  
   437  	// Never resume a session for a different TLS version.
   438  	if c.vers != hs.sessionState.vers {
   439  		return false
   440  	}
   441  
   442  	cipherSuiteOk := false
   443  	// Check that the client is still offering the ciphersuite in the session.
   444  	for _, id := range hs.clientHello.cipherSuites {
   445  		if id == hs.sessionState.cipherSuite {
   446  			cipherSuiteOk = true
   447  			break
   448  		}
   449  	}
   450  	if !cipherSuiteOk {
   451  		return false
   452  	}
   453  
   454  	// Check that we also support the ciphersuite from the session.
   455  	hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite},
   456  		c.config.cipherSuites(), hs.cipherSuiteOk)
   457  	if hs.suite == nil {
   458  		return false
   459  	}
   460  
   461  	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
   462  	needClientCerts := requiresClientCert(c.config.ClientAuth)
   463  	if needClientCerts && !sessionHasClientCerts {
   464  		return false
   465  	}
   466  	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   467  		return false
   468  	}
   469  
   470  	return true
   471  }
   472  
   473  func (hs *serverHandshakeState) doResumeHandshake() error {
   474  	c := hs.c
   475  
   476  	hs.hello.cipherSuite = hs.suite.id
   477  	c.cipherSuite = hs.suite.id
   478  	// We echo the client's session ID in the ServerHello to let it know
   479  	// that we're doing a resumption.
   480  	hs.hello.sessionId = hs.clientHello.sessionId
   481  	hs.hello.ticketSupported = hs.sessionState.usedOldKey
   482  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   483  	hs.finishedHash.discardHandshakeBuffer()
   484  	_, _ = hs.finishedHash.Write(hs.clientHello.marshal())
   485  	_, _ = hs.finishedHash.Write(hs.hello.marshal())
   486  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   487  		return err
   488  	}
   489  
   490  	if err := c.processCertsFromClient(Certificate{
   491  		Certificate: hs.sessionState.certificates,
   492  	}); err != nil {
   493  		return err
   494  	}
   495  
   496  	if c.config.VerifyConnection != nil {
   497  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   498  			_ = c.sendAlert(alertBadCertificate)
   499  			return fmt.Errorf("gmtls: VerifyConnection时发生错误: %s", err)
   500  		}
   501  	}
   502  
   503  	hs.masterSecret = hs.sessionState.masterSecret
   504  
   505  	return nil
   506  }
   507  
   508  // 完整握手过程 tls1.2
   509  func (hs *serverHandshakeState) doFullHandshake() error {
   510  	c := hs.c
   511  
   512  	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
   513  		hs.hello.ocspStapling = true
   514  	}
   515  
   516  	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
   517  	hs.hello.cipherSuite = hs.suite.id
   518  
   519  	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
   520  	if c.config.ClientAuth == NoClientCert {
   521  		// No need to keep a full record of the handshake if client
   522  		// certificates won't be used.
   523  		hs.finishedHash.discardHandshakeBuffer()
   524  	}
   525  	_, _ = hs.finishedHash.Write(hs.clientHello.marshal())
   526  	_, _ = hs.finishedHash.Write(hs.hello.marshal())
   527  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   528  		return err
   529  	}
   530  
   531  	certMsg := new(certificateMsg)
   532  	certMsg.certificates = hs.cert.Certificate
   533  	_, _ = hs.finishedHash.Write(certMsg.marshal())
   534  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   535  		return err
   536  	}
   537  
   538  	if hs.hello.ocspStapling {
   539  		certStatus := new(certificateStatusMsg)
   540  		certStatus.response = hs.cert.OCSPStaple
   541  		_, _ = hs.finishedHash.Write(certStatus.marshal())
   542  		if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
   543  			return err
   544  		}
   545  	}
   546  
   547  	keyAgreement := hs.suite.ka(c.vers)
   548  	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
   549  	if err != nil {
   550  		_ = c.sendAlert(alertHandshakeFailure)
   551  		return fmt.Errorf("gmtls: generateServerKeyExchange时发生错误: %s", err)
   552  	}
   553  	if skx != nil {
   554  		_, _ = hs.finishedHash.Write(skx.marshal())
   555  		if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
   556  			return err
   557  		}
   558  	}
   559  
   560  	var certReq *certificateRequestMsg
   561  	if c.config.ClientAuth >= RequestClientCert {
   562  		// Request a client certificate
   563  		certReq = new(certificateRequestMsg)
   564  		certReq.certificateTypes = []byte{
   565  			byte(certTypeRSASign),
   566  			byte(certTypeECDSASign),
   567  		}
   568  		if c.vers >= VersionTLS12 {
   569  			certReq.hasSignatureAlgorithm = true
   570  			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   571  		}
   572  
   573  		// An empty list of certificateAuthorities signals to
   574  		// the client that it may send any certificate in response
   575  		// to our request. When we know the CAs we trust, then
   576  		// we can send them down, so that the client can choose
   577  		// an appropriate certificate to give to us.
   578  		if c.config.ClientCAs != nil {
   579  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   580  		}
   581  		_, _ = hs.finishedHash.Write(certReq.marshal())
   582  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   583  			return err
   584  		}
   585  	}
   586  
   587  	helloDone := new(serverHelloDoneMsg)
   588  	_, _ = hs.finishedHash.Write(helloDone.marshal())
   589  	if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
   590  		return err
   591  	}
   592  
   593  	if _, err := c.flush(); err != nil {
   594  		return err
   595  	}
   596  
   597  	var pub crypto.PublicKey // public key for client auth, if any
   598  
   599  	msg, err := c.readHandshake()
   600  	if err != nil {
   601  		return err
   602  	}
   603  
   604  	// If we requested a client certificate, then the client must send a
   605  	// certificate message, even if it's empty.
   606  	if c.config.ClientAuth >= RequestClientCert {
   607  		certMsg, ok := msg.(*certificateMsg)
   608  		if !ok {
   609  			_ = c.sendAlert(alertUnexpectedMessage)
   610  			return unexpectedMessageError(certMsg, msg)
   611  		}
   612  		_, _ = hs.finishedHash.Write(certMsg.marshal())
   613  		hs.finishedHash.Write(certMsg.marshal())
   614  
   615  		if err := c.processCertsFromClient(Certificate{
   616  			Certificate: certMsg.certificates,
   617  		}); err != nil {
   618  			return err
   619  		}
   620  		if len(certMsg.certificates) != 0 {
   621  			pub = c.peerCertificates[0].PublicKey
   622  		}
   623  
   624  		msg, err = c.readHandshake()
   625  		if err != nil {
   626  			return err
   627  		}
   628  	}
   629  	if c.config.VerifyConnection != nil {
   630  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   631  			_ = c.sendAlert(alertBadCertificate)
   632  			return err
   633  		}
   634  	}
   635  
   636  	// Get client key exchange
   637  	ckx, ok := msg.(*clientKeyExchangeMsg)
   638  	if !ok {
   639  		_ = c.sendAlert(alertUnexpectedMessage)
   640  		return unexpectedMessageError(ckx, msg)
   641  	}
   642  	_, _ = hs.finishedHash.Write(ckx.marshal())
   643  
   644  	// 获取预主密钥, 分为RSA与ECDHE
   645  	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
   646  	if err != nil {
   647  		_ = c.sendAlert(alertHandshakeFailure)
   648  		return err
   649  	}
   650  	// 根据预主密钥,随机数C、S,使用PRF函数计算主密钥
   651  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
   652  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
   653  		_ = c.sendAlert(alertInternalError)
   654  		return err
   655  	}
   656  
   657  	// If we received a client cert in response to our certificate request message,
   658  	// the client will send us a certificateVerifyMsg immediately after the
   659  	// clientKeyExchangeMsg. This message is a digest of all preceding
   660  	// handshake-layer messages that is signed using the private key corresponding
   661  	// to the client's certificate. This allows us to verify that the client is in
   662  	// possession of the private key of the certificate.
   663  	if len(c.peerCertificates) > 0 {
   664  		msg, err = c.readHandshake()
   665  		if err != nil {
   666  			return err
   667  		}
   668  		certVerify, ok := msg.(*certificateVerifyMsg)
   669  		if !ok {
   670  			_ = c.sendAlert(alertUnexpectedMessage)
   671  			return unexpectedMessageError(certVerify, msg)
   672  		}
   673  
   674  		var sigType uint8
   675  		var sigHash x509.Hash
   676  		if c.vers >= VersionTLS12 {
   677  			if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
   678  				_ = c.sendAlert(alertIllegalParameter)
   679  				return errors.New("gmtls: client certificate used with invalid signature algorithm")
   680  			}
   681  			sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   682  			if err != nil {
   683  				return c.sendAlert(alertInternalError)
   684  			}
   685  		} else {
   686  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
   687  			if err != nil {
   688  				_ = c.sendAlert(alertIllegalParameter)
   689  				return err
   690  			}
   691  		}
   692  
   693  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
   694  		if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
   695  			_ = c.sendAlert(alertDecryptError)
   696  			return fmt.Errorf("gmtls: invalid signature by the client certificate: %s", err)
   697  		}
   698  
   699  		_, _ = hs.finishedHash.Write(certVerify.marshal())
   700  	}
   701  
   702  	hs.finishedHash.discardHandshakeBuffer()
   703  
   704  	return nil
   705  }
   706  
   707  // 派生会话密钥 tls1.2
   708  func (hs *serverHandshakeState) establishKeys() error {
   709  	c := hs.c
   710  
   711  	// 根据主密钥、随机数C/S,使用PRF函数派生出6个会话密钥
   712  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   713  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   714  
   715  	var clientCipher, serverCipher interface{}
   716  	var clientHash, serverHash hash.Hash
   717  
   718  	if hs.suite.aead == nil {
   719  		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
   720  		clientHash = hs.suite.mac(clientMAC)
   721  		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
   722  		serverHash = hs.suite.mac(serverMAC)
   723  	} else {
   724  		clientCipher = hs.suite.aead(clientKey, clientIV)
   725  		serverCipher = hs.suite.aead(serverKey, serverIV)
   726  	}
   727  
   728  	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
   729  	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
   730  
   731  	return nil
   732  }
   733  
   734  func (hs *serverHandshakeState) readFinished(out []byte) error {
   735  	c := hs.c
   736  
   737  	if err := c.readChangeCipherSpec(); err != nil {
   738  		return err
   739  	}
   740  
   741  	msg, err := c.readHandshake()
   742  	if err != nil {
   743  		return err
   744  	}
   745  	clientFinished, ok := msg.(*finishedMsg)
   746  	if !ok {
   747  		_ = c.sendAlert(alertUnexpectedMessage)
   748  		return unexpectedMessageError(clientFinished, msg)
   749  	}
   750  
   751  	verify := hs.finishedHash.clientSum(hs.masterSecret)
   752  	if len(verify) != len(clientFinished.verifyData) ||
   753  		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
   754  		_ = c.sendAlert(alertHandshakeFailure)
   755  		return errors.New("gmtls: client's Finished message is incorrect")
   756  	}
   757  
   758  	_, _ = hs.finishedHash.Write(clientFinished.marshal())
   759  	copy(out, verify)
   760  	return nil
   761  }
   762  
   763  func (hs *serverHandshakeState) sendSessionTicket() error {
   764  	// ticketSupported is set in a resumption handshake if the
   765  	// ticket from the client was encrypted with an old session
   766  	// ticket key and thus a refreshed ticket should be sent.
   767  	if !hs.hello.ticketSupported {
   768  		return nil
   769  	}
   770  
   771  	c := hs.c
   772  	m := new(newSessionTicketMsg)
   773  
   774  	createdAt := uint64(c.config.time().Unix())
   775  	if hs.sessionState != nil {
   776  		// If this is re-wrapping an old key, then keep
   777  		// the original time it was created.
   778  		createdAt = hs.sessionState.createdAt
   779  	}
   780  
   781  	var certsFromClient [][]byte
   782  	for _, cert := range c.peerCertificates {
   783  		certsFromClient = append(certsFromClient, cert.Raw)
   784  	}
   785  	state := sessionState{
   786  		vers:         c.vers,
   787  		cipherSuite:  hs.suite.id,
   788  		createdAt:    createdAt,
   789  		masterSecret: hs.masterSecret,
   790  		certificates: certsFromClient,
   791  	}
   792  	var err error
   793  	m.ticket, err = c.encryptTicket(state.marshal())
   794  	if err != nil {
   795  		return err
   796  	}
   797  
   798  	_, _ = hs.finishedHash.Write(m.marshal())
   799  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   800  		return err
   801  	}
   802  
   803  	return nil
   804  }
   805  
   806  func (hs *serverHandshakeState) sendFinished(out []byte) error {
   807  	c := hs.c
   808  
   809  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   810  		return err
   811  	}
   812  
   813  	finished := new(finishedMsg)
   814  	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
   815  	_, _ = hs.finishedHash.Write(finished.marshal())
   816  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   817  		return err
   818  	}
   819  
   820  	copy(out, finished.verifyData)
   821  
   822  	return nil
   823  }
   824  
   825  // 检查客户端证书。
   826  // processCertsFromClient takes a chain of client certificates either from a
   827  // Certificates message or from a sessionState and verifies them. It returns
   828  // the public key of the leaf certificate.
   829  func (c *Conn) processCertsFromClient(certificate Certificate) error {
   830  	certificates := certificate.Certificate
   831  	certs := make([]*x509.Certificate, len(certificates))
   832  	var err error
   833  	for i, asn1Data := range certificates {
   834  		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
   835  			_ = c.sendAlert(alertBadCertificate)
   836  			return fmt.Errorf("gmtls: failed to parse client certificate: %s", err)
   837  		}
   838  	}
   839  
   840  	if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
   841  		_ = c.sendAlert(alertBadCertificate)
   842  		return errors.New("gmtls: client didn't provide a certificate")
   843  	}
   844  
   845  	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
   846  		opts := x509.VerifyOptions{
   847  			Roots:         c.config.ClientCAs,
   848  			CurrentTime:   c.config.time(),
   849  			Intermediates: x509.NewCertPool(),
   850  			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
   851  		}
   852  
   853  		for _, cert := range certs[1:] {
   854  			opts.Intermediates.AddCert(cert)
   855  		}
   856  		// 从子证书开始验证签名并尝试构建信任链
   857  		chains, err := certs[0].Verify(opts)
   858  		if err != nil {
   859  			_ = c.sendAlert(alertBadCertificate)
   860  			return fmt.Errorf("gmtls: failed to verify client certificate: %s", err)
   861  		}
   862  
   863  		c.verifiedChains = chains
   864  	}
   865  
   866  	c.peerCertificates = certs
   867  	c.ocspResponse = certificate.OCSPStaple
   868  	c.scts = certificate.SignedCertificateTimestamps
   869  
   870  	if len(certs) > 0 {
   871  		// 补充sm2条件
   872  		switch certs[0].PublicKey.(type) {
   873  		case *sm2.PublicKey, *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
   874  		default:
   875  			_ = c.sendAlert(alertUnsupportedCertificate)
   876  			return fmt.Errorf("gmtls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
   877  		}
   878  	}
   879  
   880  	if c.config.VerifyPeerCertificate != nil {
   881  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   882  			_ = c.sendAlert(alertBadCertificate)
   883  			return fmt.Errorf("gmtls: VerifyPeerCertificate时发生错误: %s", err)
   884  		}
   885  	}
   886  
   887  	return nil
   888  }
   889  
   890  func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
   891  	supportedVersions := clientHello.supportedVersions
   892  	if len(clientHello.supportedVersions) == 0 {
   893  		supportedVersions = supportedVersionsFromMax(clientHello.vers)
   894  	}
   895  
   896  	return &ClientHelloInfo{
   897  		CipherSuites:      clientHello.cipherSuites,
   898  		ServerName:        clientHello.serverName,
   899  		SupportedCurves:   clientHello.supportedCurves,
   900  		SupportedPoints:   clientHello.supportedPoints,
   901  		SignatureSchemes:  clientHello.supportedSignatureAlgorithms,
   902  		SupportedProtos:   clientHello.alpnProtocols,
   903  		SupportedVersions: supportedVersions,
   904  		Conn:              c.conn,
   905  		config:            c.config,
   906  		ctx:               ctx,
   907  	}
   908  }