github.com/Hyperledger-TWGC/tjfoc-gm@v1.4.0/gmtls/gm_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  // +build single_cert
     6  
     7  package gmtls
     8  
     9  import (
    10  	"crypto"
    11  	"crypto/ecdsa"
    12  	"crypto/rsa"
    13  	"crypto/subtle"
    14  	"errors"
    15  	"fmt"
    16  	"github.com/Hyperledger-TWGC/tjfoc-gm/sm2"
    17  	"github.com/Hyperledger-TWGC/tjfoc-gm/x509"
    18  	"io"
    19  	"sync/atomic"
    20  )
    21  
    22  // serverHandshakeStateGM contains details of a server handshake in progress.
    23  // It's discarded once the handshake has completed.
    24  type serverHandshakeStateGM struct {
    25  	c                     *Conn
    26  	clientHello           *clientHelloMsg
    27  	hello                 *serverHelloMsg
    28  	suite                 *cipherSuite
    29  	sessionState          *sessionState
    30  	finishedHash          finishedHash
    31  	masterSecret          []byte
    32  	certsFromClient       [][]byte
    33  	cert                  *Certificate
    34  	cachedClientHelloInfo *ClientHelloInfo
    35  }
    36  
    37  // serverHandshake performs a TLS handshake as a server.
    38  func (c *Conn) serverHandshakeGM() error {
    39  	// If this is the first server handshake, we generate a random key to
    40  	// encrypt the tickets with.
    41  	c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
    42  
    43  	hs := serverHandshakeStateGM{
    44  		c: c,
    45  	}
    46  	isResume, err := hs.readClientHello()
    47  	if err != nil {
    48  		return err
    49  	}
    50  
    51  	// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
    52  	c.buffering = true
    53  	if isResume {
    54  		// The client has included a session ticket and so we do an abbreviated handshake.
    55  		if err := hs.doResumeHandshake(); err != nil {
    56  			return err
    57  		}
    58  		if err := hs.establishKeys(); err != nil {
    59  			return err
    60  		}
    61  		// ticketSupported is set in a resumption handshake if the
    62  		// ticket from the client was encrypted with an old session
    63  		// ticket key and thus a refreshed ticket should be sent.
    64  		if hs.hello.ticketSupported {
    65  			if err := hs.sendSessionTicket(); err != nil {
    66  				return err
    67  			}
    68  		}
    69  		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
    70  			return err
    71  		}
    72  		if _, err := c.flush(); err != nil {
    73  			return err
    74  		}
    75  		c.clientFinishedIsFirst = false
    76  		if err := hs.readFinished(nil); err != nil {
    77  			return err
    78  		}
    79  		c.didResume = true
    80  	} else {
    81  		// The client didn't include a session ticket, or it wasn't
    82  		// valid so we do a full handshake.
    83  		if err := hs.doFullHandshake(); err != nil {
    84  			return err
    85  		}
    86  		if err := hs.establishKeys(); err != nil {
    87  			return err
    88  		}
    89  		if err := hs.readFinished(c.clientFinished[:]); err != nil {
    90  			return err
    91  		}
    92  		c.clientFinishedIsFirst = true
    93  		c.buffering = true
    94  		if err := hs.sendSessionTicket(); err != nil {
    95  			return err
    96  		}
    97  		if err := hs.sendFinished(nil); err != nil {
    98  			return err
    99  		}
   100  		if _, err := c.flush(); err != nil {
   101  			return err
   102  		}
   103  	}
   104  
   105  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
   106  	atomic.StoreUint32(&c.handshakeStatus, 1)
   107  
   108  	return nil
   109  }
   110  
   111  // readClientHello reads a ClientHello message from the client and decides
   112  // whether we will perform session resumption.
   113  func (hs *serverHandshakeStateGM) readClientHello() (isResume bool, err error) {
   114  	c := hs.c
   115  
   116  	msg, err := c.readHandshake()
   117  	if err != nil {
   118  		return false, err
   119  	}
   120  	var ok bool
   121  	hs.clientHello, ok = msg.(*clientHelloMsg)
   122  	if !ok {
   123  		c.sendAlert(alertUnexpectedMessage)
   124  		return false, unexpectedMessageError(hs.clientHello, msg)
   125  	}
   126  
   127  	if c.config.GetConfigForClient != nil {
   128  		if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
   129  			c.sendAlert(alertInternalError)
   130  			return false, err
   131  		} else if newConfig != nil {
   132  			newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
   133  			c.config = newConfig
   134  		}
   135  	}
   136  
   137  	c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
   138  	if !ok {
   139  		c.sendAlert(alertProtocolVersion)
   140  		return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
   141  	}
   142  	c.haveVers = true
   143  
   144  	hs.hello = new(serverHelloMsg)
   145  
   146  	//supportedCurve := false
   147  	//	preferredCurves := c.config.curvePreferences()
   148  	//Curves:
   149  	//	for _, curve := range hs.clientHello.supportedCurves {
   150  	//		for _, supported := range preferredCurves {
   151  	//			if supported == curve {
   152  	//				supportedCurve = true
   153  	//				break Curves
   154  	//			}
   155  	//		}
   156  	//	}
   157  	//
   158  	//	supportedPointFormat := false
   159  	//	for _, pointFormat := range hs.clientHello.supportedPoints {
   160  	//		if pointFormat == pointFormatUncompressed {
   161  	//			supportedPointFormat = true
   162  	//			break
   163  	//		}
   164  	//	}
   165  	//	hs.ellipticOk = supportedCurve && supportedPointFormat
   166  
   167  	foundCompression := false
   168  	// We only support null compression, so check that the client offered it.
   169  	for _, compression := range hs.clientHello.compressionMethods {
   170  		if compression == compressionNone {
   171  			foundCompression = true
   172  			break
   173  		}
   174  	}
   175  
   176  	if !foundCompression {
   177  		c.sendAlert(alertHandshakeFailure)
   178  		return false, errors.New("tls: client does not support uncompressed connections")
   179  	}
   180  
   181  	hs.hello.vers = c.vers
   182  	hs.hello.random = make([]byte, 32)
   183  	_, err = io.ReadFull(c.config.rand(), hs.hello.random)
   184  	if err != nil {
   185  		c.sendAlert(alertInternalError)
   186  		return false, err
   187  	}
   188  
   189  	if len(hs.clientHello.secureRenegotiation) != 0 {
   190  		c.sendAlert(alertHandshakeFailure)
   191  		return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   192  	}
   193  
   194  	hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
   195  	hs.hello.compressionMethod = compressionNone
   196  	if len(hs.clientHello.serverName) > 0 {
   197  		c.serverName = hs.clientHello.serverName
   198  	}
   199  
   200  	if len(hs.clientHello.alpnProtocols) > 0 {
   201  		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
   202  			hs.hello.alpnProtocol = selectedProto
   203  			c.clientProtocol = selectedProto
   204  		}
   205  	} else {
   206  		// Although sending an empty NPN extension is reasonable, Firefox has
   207  		// had a bug around this. Best to send nothing at all if
   208  		// c.config.NextProtos is empty. See
   209  		// https://golang.org/issue/5445.
   210  		if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 {
   211  			hs.hello.nextProtoNeg = true
   212  			hs.hello.nextProtos = c.config.NextProtos
   213  		}
   214  	}
   215  
   216  	hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
   217  	if err != nil {
   218  		c.sendAlert(alertInternalError)
   219  		return false, err
   220  	}
   221  	// GMT0024
   222  	// mod by syl just for test change two certs into one cert
   223  	//if len(hs.cert.Certificate) < 2 {
   224  	//	c.sendAlert(alertInternalError)
   225  	//	return false, fmt.Errorf("tls: amount of server certificates must be greater than 2, which will sign and encipher respectively")
   226  	//}
   227  	if len(hs.cert.Certificate) < 1 {
   228  		c.sendAlert(alertInternalError)
   229  		return false, fmt.Errorf("tls: amount of server certificates must be greater than 0")
   230  	}
   231  	if hs.clientHello.scts {
   232  		hs.hello.scts = hs.cert.SignedCertificateTimestamps
   233  	}
   234  
   235  	if hs.checkForResumption() {
   236  		return true, nil
   237  	}
   238  
   239  	var preferenceList, supportedList []uint16
   240  	if c.config.PreferServerCipherSuites {
   241  		preferenceList = getCipherSuites(c.config)
   242  		supportedList = hs.clientHello.cipherSuites
   243  	} else {
   244  		preferenceList = hs.clientHello.cipherSuites
   245  		supportedList = getCipherSuites(c.config)
   246  	}
   247  
   248  	for _, id := range preferenceList {
   249  		if hs.setCipherSuite(id, supportedList, c.vers) {
   250  			break
   251  		}
   252  	}
   253  
   254  	if hs.suite == nil {
   255  		c.sendAlert(alertHandshakeFailure)
   256  		return false, errors.New("tls: no cipher suite supported by both client and server")
   257  	}
   258  
   259  	// See https://tools.ietf.org/html/rfc7507.
   260  	for _, id := range hs.clientHello.cipherSuites {
   261  		if id == TLS_FALLBACK_SCSV {
   262  			// The client is doing a fallback connection.
   263  			if hs.clientHello.vers < c.config.maxVersion() {
   264  				c.sendAlert(alertInappropriateFallback)
   265  				return false, errors.New("tls: client using inappropriate protocol fallback")
   266  			}
   267  			break
   268  		}
   269  	}
   270  
   271  	return false, nil
   272  }
   273  
   274  // checkForResumption reports whether we should perform resumption on this connection.
   275  func (hs *serverHandshakeStateGM) checkForResumption() bool {
   276  	c := hs.c
   277  
   278  	if c.config.SessionTicketsDisabled {
   279  		return false
   280  	}
   281  
   282  	var ok bool
   283  	var sessionTicket = append([]uint8{}, hs.clientHello.sessionTicket...)
   284  	if hs.sessionState, ok = c.decryptTicket(sessionTicket); !ok {
   285  		return false
   286  	}
   287  
   288  	// Never resume a session for a different TLS version.
   289  	if c.vers != hs.sessionState.vers {
   290  		return false
   291  	}
   292  
   293  	cipherSuiteOk := false
   294  	// Check that the client is still offering the ciphersuite in the session.
   295  	for _, id := range hs.clientHello.cipherSuites {
   296  		if id == hs.sessionState.cipherSuite {
   297  			cipherSuiteOk = true
   298  			break
   299  		}
   300  	}
   301  	if !cipherSuiteOk {
   302  		return false
   303  	}
   304  
   305  	// Check that we also support the ciphersuite from the session.
   306  	if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
   307  		return false
   308  	}
   309  
   310  	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
   311  	needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
   312  	if needClientCerts && !sessionHasClientCerts {
   313  		return false
   314  	}
   315  	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   316  		return false
   317  	}
   318  
   319  	return true
   320  }
   321  
   322  func (hs *serverHandshakeStateGM) doResumeHandshake() error {
   323  	c := hs.c
   324  
   325  	hs.hello.cipherSuite = hs.suite.id
   326  	// We echo the client's session ID in the ServerHello to let it know
   327  	// that we're doing a resumption.
   328  	hs.hello.sessionId = hs.clientHello.sessionId
   329  	hs.hello.ticketSupported = hs.sessionState.usedOldKey
   330  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   331  	hs.finishedHash.discardHandshakeBuffer()
   332  	hs.finishedHash.Write(hs.clientHello.marshal())
   333  	hs.finishedHash.Write(hs.hello.marshal())
   334  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   335  		return err
   336  	}
   337  
   338  	if len(hs.sessionState.certificates) > 0 {
   339  		if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
   340  			return err
   341  		}
   342  	}
   343  
   344  	hs.masterSecret = hs.sessionState.masterSecret
   345  
   346  	return nil
   347  }
   348  
   349  func (hs *serverHandshakeStateGM) doFullHandshake() error {
   350  	c := hs.c
   351  
   352  	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
   353  		hs.hello.ocspStapling = true
   354  	}
   355  
   356  	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
   357  	hs.hello.cipherSuite = hs.suite.id
   358  
   359  	hs.finishedHash = newFinishedHashGM(hs.suite)
   360  	if c.config.ClientAuth == NoClientCert {
   361  		// No need to keep a full record of the handshake if client
   362  		// certificates won't be used.
   363  		hs.finishedHash.discardHandshakeBuffer()
   364  	}
   365  	hs.finishedHash.Write(hs.clientHello.marshal())
   366  	hs.finishedHash.Write(hs.hello.marshal())
   367  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   368  		return err
   369  	}
   370  
   371  	certMsg := new(certificateMsg)
   372  	certMsg.certificates = hs.cert.Certificate
   373  	hs.finishedHash.Write(certMsg.marshal())
   374  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   375  		return err
   376  	}
   377  
   378  	if hs.hello.ocspStapling {
   379  		certStatus := new(certificateStatusMsg)
   380  		certStatus.statusType = statusTypeOCSP
   381  		certStatus.response = hs.cert.OCSPStaple
   382  		hs.finishedHash.Write(certStatus.marshal())
   383  		if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
   384  			return err
   385  		}
   386  	}
   387  
   388  	keyAgreement := hs.suite.ka(c.vers)
   389  	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.cert, hs.clientHello, hs.hello)
   390  	if err != nil {
   391  		c.sendAlert(alertHandshakeFailure)
   392  		return err
   393  	}
   394  	if skx != nil {
   395  		hs.finishedHash.Write(skx.marshal())
   396  		if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
   397  			return err
   398  		}
   399  	}
   400  
   401  	if c.config.ClientAuth >= RequestClientCert {
   402  		// Request a client certificate
   403  		certReq := new(certificateRequestMsgGM)
   404  		certReq.certificateTypes = []byte{
   405  			byte(certTypeRSASign),
   406  			byte(certTypeECDSASign),
   407  		}
   408  		//if c.vers >= VersionTLS12 {
   409  		//	certReq.hasSignatureAndHash = true
   410  		//	certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   411  		//}
   412  
   413  		// An empty list of certificateAuthorities signals to
   414  		// the client that it may send any certificate in response
   415  		// to our request. When we know the CAs we trust, then
   416  		// we can send them down, so that the client can choose
   417  		// an appropriate certificate to give to us.
   418  		if c.config.ClientCAs != nil {
   419  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   420  		}
   421  		hs.finishedHash.Write(certReq.marshal())
   422  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   423  			return err
   424  		}
   425  	}
   426  
   427  	helloDone := new(serverHelloDoneMsg)
   428  	hs.finishedHash.Write(helloDone.marshal())
   429  	if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
   430  		return err
   431  	}
   432  
   433  	if _, err := c.flush(); err != nil {
   434  		return err
   435  	}
   436  
   437  	var pub crypto.PublicKey // public key for client auth, if any
   438  
   439  	msg, err := c.readHandshake()
   440  	if err != nil {
   441  		fmt.Println("readHandshake error:", err)
   442  		return err
   443  	}
   444  
   445  	var ok bool
   446  	// If we requested a client certificate, then the client must send a
   447  	// certificate message, even if it's empty.
   448  	if c.config.ClientAuth >= RequestClientCert {
   449  		if certMsg, ok = msg.(*certificateMsg); !ok {
   450  			c.sendAlert(alertUnexpectedMessage)
   451  			return unexpectedMessageError(certMsg, msg)
   452  		}
   453  		hs.finishedHash.Write(certMsg.marshal())
   454  
   455  		if len(certMsg.certificates) == 0 {
   456  			// The client didn't actually send a certificate
   457  			switch c.config.ClientAuth {
   458  			case RequireAnyClientCert, RequireAndVerifyClientCert:
   459  				c.sendAlert(alertBadCertificate)
   460  				return errors.New("tls: client didn't provide a certificate")
   461  			}
   462  		}
   463  
   464  		pub, err = hs.processCertsFromClient(certMsg.certificates)
   465  		if err != nil {
   466  			return err
   467  		}
   468  
   469  		msg, err = c.readHandshake()
   470  		if err != nil {
   471  			return err
   472  		}
   473  	}
   474  
   475  	// Get client key exchange
   476  	ckx, ok := msg.(*clientKeyExchangeMsg)
   477  	if !ok {
   478  		c.sendAlert(alertUnexpectedMessage)
   479  		return unexpectedMessageError(ckx, msg)
   480  	}
   481  	hs.finishedHash.Write(ckx.marshal())
   482  
   483  	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
   484  	if err != nil {
   485  		c.sendAlert(alertHandshakeFailure)
   486  		return err
   487  	}
   488  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
   489  	if err := c.config.writeKeyLog(hs.clientHello.random, hs.masterSecret); err != nil {
   490  		c.sendAlert(alertInternalError)
   491  		return err
   492  	}
   493  
   494  	// If we received a client cert in response to our certificate request message,
   495  	// the client will send us a certificateVerifyMsg immediately after the
   496  	// clientKeyExchangeMsg. This message is a digest of all preceding
   497  	// handshake-layer messages that is signed using the private key corresponding
   498  	// to the client's certificate. This allows us to verify that the client is in
   499  	// possession of the private key of the certificate.
   500  	if len(c.peerCertificates) > 0 {
   501  		msg, err = c.readHandshake()
   502  		if err != nil {
   503  			return err
   504  		}
   505  		certVerify, ok := msg.(*certificateVerifyMsg)
   506  		if !ok {
   507  			c.sendAlert(alertUnexpectedMessage)
   508  			return unexpectedMessageError(certVerify, msg)
   509  		}
   510  
   511  		// Determine the signature type.
   512  		_, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
   513  		if err != nil {
   514  			c.sendAlert(alertIllegalParameter)
   515  			return err
   516  		}
   517  
   518  		var digest []byte
   519  		if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
   520  			err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
   521  		}
   522  		if err != nil {
   523  			c.sendAlert(alertBadCertificate)
   524  			return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
   525  		}
   526  
   527  		hs.finishedHash.Write(certVerify.marshal())
   528  	}
   529  
   530  	hs.finishedHash.discardHandshakeBuffer()
   531  
   532  	return nil
   533  }
   534  
   535  func (hs *serverHandshakeStateGM) establishKeys() error {
   536  	c := hs.c
   537  
   538  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   539  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   540  
   541  	var clientCipher, serverCipher interface{}
   542  	var clientHash, serverHash macFunction
   543  
   544  	if hs.suite.aead == nil {
   545  		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
   546  		clientHash = hs.suite.mac(c.vers, clientMAC)
   547  		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
   548  		serverHash = hs.suite.mac(c.vers, serverMAC)
   549  	} else {
   550  		clientCipher = hs.suite.aead(clientKey, clientIV)
   551  		serverCipher = hs.suite.aead(serverKey, serverIV)
   552  	}
   553  
   554  	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
   555  	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
   556  
   557  	return nil
   558  }
   559  
   560  func (hs *serverHandshakeStateGM) readFinished(out []byte) error {
   561  	c := hs.c
   562  
   563  	c.readRecord(recordTypeChangeCipherSpec)
   564  	if c.in.err != nil {
   565  		return c.in.err
   566  	}
   567  
   568  	if hs.hello.nextProtoNeg {
   569  		msg, err := c.readHandshake()
   570  		if err != nil {
   571  			return err
   572  		}
   573  		nextProto, ok := msg.(*nextProtoMsg)
   574  		if !ok {
   575  			c.sendAlert(alertUnexpectedMessage)
   576  			return unexpectedMessageError(nextProto, msg)
   577  		}
   578  		hs.finishedHash.Write(nextProto.marshal())
   579  		c.clientProtocol = nextProto.proto
   580  	}
   581  
   582  	msg, err := c.readHandshake()
   583  	if err != nil {
   584  		return err
   585  	}
   586  	clientFinished, ok := msg.(*finishedMsg)
   587  	if !ok {
   588  		c.sendAlert(alertUnexpectedMessage)
   589  		return unexpectedMessageError(clientFinished, msg)
   590  	}
   591  
   592  	verify := hs.finishedHash.clientSum(hs.masterSecret)
   593  	if len(verify) != len(clientFinished.verifyData) ||
   594  		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
   595  		c.sendAlert(alertHandshakeFailure)
   596  		return errors.New("tls: client's Finished message is incorrect")
   597  	}
   598  
   599  	hs.finishedHash.Write(clientFinished.marshal())
   600  	copy(out, verify)
   601  	return nil
   602  }
   603  
   604  func (hs *serverHandshakeStateGM) sendSessionTicket() error {
   605  	if !hs.hello.ticketSupported {
   606  		return nil
   607  	}
   608  
   609  	c := hs.c
   610  	m := new(newSessionTicketMsg)
   611  
   612  	var err error
   613  	state := sessionState{
   614  		vers:         c.vers,
   615  		cipherSuite:  hs.suite.id,
   616  		masterSecret: hs.masterSecret,
   617  		certificates: hs.certsFromClient,
   618  	}
   619  	m.ticket, err = c.encryptTicket(&state)
   620  	if err != nil {
   621  		return err
   622  	}
   623  
   624  	hs.finishedHash.Write(m.marshal())
   625  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   626  		return err
   627  	}
   628  
   629  	return nil
   630  }
   631  
   632  func (hs *serverHandshakeStateGM) sendFinished(out []byte) error {
   633  	c := hs.c
   634  
   635  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   636  		return err
   637  	}
   638  
   639  	finished := new(finishedMsg)
   640  	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
   641  	hs.finishedHash.Write(finished.marshal())
   642  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   643  		return err
   644  	}
   645  
   646  	c.cipherSuite = hs.suite.id
   647  	copy(out, finished.verifyData)
   648  
   649  	return nil
   650  }
   651  
   652  // processCertsFromClient takes a chain of client certificates either from a
   653  // Certificates message or from a sessionState and verifies them. It returns
   654  // the public key of the leaf certificate.
   655  func (hs *serverHandshakeStateGM) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
   656  	c := hs.c
   657  
   658  	hs.certsFromClient = certificates
   659  	certs := make([]*x509.Certificate, len(certificates))
   660  	var err error
   661  	for i, asn1Data := range certificates {
   662  		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
   663  			c.sendAlert(alertBadCertificate)
   664  			return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
   665  		}
   666  	}
   667  
   668  	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
   669  		opts := x509.VerifyOptions{
   670  			Roots:         c.config.ClientCAs,
   671  			CurrentTime:   c.config.time(),
   672  			Intermediates: x509.NewCertPool(),
   673  			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
   674  		}
   675  
   676  		for _, cert := range certs[1:] {
   677  			opts.Intermediates.AddCert(cert)
   678  		}
   679  
   680  		chains, err := certs[0].Verify(opts)
   681  		if err != nil {
   682  			c.sendAlert(alertBadCertificate)
   683  			return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
   684  		}
   685  
   686  		c.verifiedChains = chains
   687  	}
   688  
   689  	if c.config.VerifyPeerCertificate != nil {
   690  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   691  			c.sendAlert(alertBadCertificate)
   692  			return nil, err
   693  		}
   694  	}
   695  
   696  	if len(certs) == 0 {
   697  		return nil, nil
   698  	}
   699  
   700  	var pub crypto.PublicKey
   701  	switch key := certs[0].PublicKey.(type) {
   702  	case *ecdsa.PublicKey, *rsa.PublicKey, *sm2.PublicKey:
   703  		pub = key
   704  	default:
   705  		c.sendAlert(alertUnsupportedCertificate)
   706  		return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
   707  	}
   708  	c.peerCertificates = certs
   709  	return pub, nil
   710  }
   711  
   712  // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeStateGM
   713  // suite if that cipher suite is acceptable to use.
   714  // It returns a bool indicating if the suite was set.
   715  func (hs *serverHandshakeStateGM) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
   716  	for _, supported := range supportedCipherSuites {
   717  		if id == supported {
   718  			var candidate *cipherSuite
   719  
   720  			for _, s := range gmCipherSuites {
   721  				if s.id == id {
   722  					candidate = s
   723  					break
   724  				}
   725  			}
   726  			if candidate == nil {
   727  				continue
   728  			}
   729  			if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
   730  				continue
   731  			}
   732  			hs.suite = candidate
   733  			return true
   734  		}
   735  	}
   736  	return false
   737  }
   738  
   739  func (hs *serverHandshakeStateGM) clientHelloInfo() *ClientHelloInfo {
   740  	if hs.cachedClientHelloInfo != nil {
   741  		return hs.cachedClientHelloInfo
   742  	}
   743  
   744  	var supportedVersions []uint16
   745  	if hs.clientHello.vers > VersionTLS12 {
   746  		supportedVersions = suppVersArray[:]
   747  	} else if hs.clientHello.vers >= VersionSSL30 {
   748  		supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
   749  	}
   750  
   751  	hs.cachedClientHelloInfo = &ClientHelloInfo{
   752  		CipherSuites:      hs.clientHello.cipherSuites,
   753  		ServerName:        hs.clientHello.serverName,
   754  		SupportedCurves:   hs.clientHello.supportedCurves,
   755  		SupportedPoints:   hs.clientHello.supportedPoints,
   756  		SignatureSchemes:  hs.clientHello.supportedSignatureAlgorithms,
   757  		SupportedProtos:   hs.clientHello.alpnProtocols,
   758  		SupportedVersions: supportedVersions,
   759  		Conn:              hs.c.conn,
   760  	}
   761  
   762  	return hs.cachedClientHelloInfo
   763  }