github.com/gidoBOSSftw5731/go/src@v0.0.0-20210226122457-d24b0edbf019/crypto/tls/handshake_client_tls13.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"crypto"
    10  	"crypto/hmac"
    11  	"crypto/rsa"
    12  	"errors"
    13  	"hash"
    14  	"sync/atomic"
    15  	"time"
    16  )
    17  
    18  type clientHandshakeStateTLS13 struct {
    19  	c           *Conn
    20  	serverHello *serverHelloMsg
    21  	hello       *clientHelloMsg
    22  	ecdheParams ecdheParameters
    23  
    24  	session     *ClientSessionState
    25  	earlySecret []byte
    26  	binderKey   []byte
    27  
    28  	certReq       *certificateRequestMsgTLS13
    29  	usingPSK      bool
    30  	sentDummyCCS  bool
    31  	suite         *cipherSuiteTLS13
    32  	transcript    hash.Hash
    33  	masterSecret  []byte
    34  	trafficSecret []byte // client_application_traffic_secret_0
    35  }
    36  
    37  // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and,
    38  // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
    39  func (hs *clientHandshakeStateTLS13) handshake() error {
    40  	c := hs.c
    41  
    42  	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
    43  	// sections 4.1.2 and 4.1.3.
    44  	if c.handshakes > 0 {
    45  		c.sendAlert(alertProtocolVersion)
    46  		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
    47  	}
    48  
    49  	// Consistency check on the presence of a keyShare and its parameters.
    50  	if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 {
    51  		return c.sendAlert(alertInternalError)
    52  	}
    53  
    54  	if err := hs.checkServerHelloOrHRR(); err != nil {
    55  		return err
    56  	}
    57  
    58  	hs.transcript = hs.suite.hash.New()
    59  	hs.transcript.Write(hs.hello.marshal())
    60  
    61  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
    62  		if err := hs.sendDummyChangeCipherSpec(); err != nil {
    63  			return err
    64  		}
    65  		if err := hs.processHelloRetryRequest(); err != nil {
    66  			return err
    67  		}
    68  	}
    69  
    70  	hs.transcript.Write(hs.serverHello.marshal())
    71  
    72  	c.buffering = true
    73  	if err := hs.processServerHello(); err != nil {
    74  		return err
    75  	}
    76  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
    77  		return err
    78  	}
    79  	if err := hs.establishHandshakeKeys(); err != nil {
    80  		return err
    81  	}
    82  	if err := hs.readServerParameters(); err != nil {
    83  		return err
    84  	}
    85  	if err := hs.readServerCertificate(); err != nil {
    86  		return err
    87  	}
    88  	if err := hs.readServerFinished(); err != nil {
    89  		return err
    90  	}
    91  	if err := hs.sendClientCertificate(); err != nil {
    92  		return err
    93  	}
    94  	if err := hs.sendClientFinished(); err != nil {
    95  		return err
    96  	}
    97  	if _, err := c.flush(); err != nil {
    98  		return err
    99  	}
   100  
   101  	atomic.StoreUint32(&c.handshakeStatus, 1)
   102  
   103  	return nil
   104  }
   105  
   106  // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
   107  // HelloRetryRequest messages. It sets hs.suite.
   108  func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
   109  	c := hs.c
   110  
   111  	if hs.serverHello.supportedVersion == 0 {
   112  		c.sendAlert(alertMissingExtension)
   113  		return errors.New("tls: server selected TLS 1.3 using the legacy version field")
   114  	}
   115  
   116  	if hs.serverHello.supportedVersion != VersionTLS13 {
   117  		c.sendAlert(alertIllegalParameter)
   118  		return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
   119  	}
   120  
   121  	if hs.serverHello.vers != VersionTLS12 {
   122  		c.sendAlert(alertIllegalParameter)
   123  		return errors.New("tls: server sent an incorrect legacy version")
   124  	}
   125  
   126  	if hs.serverHello.ocspStapling ||
   127  		hs.serverHello.ticketSupported ||
   128  		hs.serverHello.secureRenegotiationSupported ||
   129  		len(hs.serverHello.secureRenegotiation) != 0 ||
   130  		len(hs.serverHello.alpnProtocol) != 0 ||
   131  		len(hs.serverHello.scts) != 0 {
   132  		c.sendAlert(alertUnsupportedExtension)
   133  		return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
   134  	}
   135  
   136  	if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
   137  		c.sendAlert(alertIllegalParameter)
   138  		return errors.New("tls: server did not echo the legacy session ID")
   139  	}
   140  
   141  	if hs.serverHello.compressionMethod != compressionNone {
   142  		c.sendAlert(alertIllegalParameter)
   143  		return errors.New("tls: server selected unsupported compression format")
   144  	}
   145  
   146  	selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
   147  	if hs.suite != nil && selectedSuite != hs.suite {
   148  		c.sendAlert(alertIllegalParameter)
   149  		return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
   150  	}
   151  	if selectedSuite == nil {
   152  		c.sendAlert(alertIllegalParameter)
   153  		return errors.New("tls: server chose an unconfigured cipher suite")
   154  	}
   155  	hs.suite = selectedSuite
   156  	c.cipherSuite = hs.suite.id
   157  
   158  	return nil
   159  }
   160  
   161  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   162  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   163  func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   164  	if hs.sentDummyCCS {
   165  		return nil
   166  	}
   167  	hs.sentDummyCCS = true
   168  
   169  	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
   170  	return err
   171  }
   172  
   173  // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
   174  // resends hs.hello, and reads the new ServerHello into hs.serverHello.
   175  func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
   176  	c := hs.c
   177  
   178  	// The first ClientHello gets double-hashed into the transcript upon a
   179  	// HelloRetryRequest. (The idea is that the server might offload transcript
   180  	// storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
   181  	chHash := hs.transcript.Sum(nil)
   182  	hs.transcript.Reset()
   183  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   184  	hs.transcript.Write(chHash)
   185  	hs.transcript.Write(hs.serverHello.marshal())
   186  
   187  	// The only HelloRetryRequest extensions we support are key_share and
   188  	// cookie, and clients must abort the handshake if the HRR would not result
   189  	// in any change in the ClientHello.
   190  	if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
   191  		c.sendAlert(alertIllegalParameter)
   192  		return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
   193  	}
   194  
   195  	if hs.serverHello.cookie != nil {
   196  		hs.hello.cookie = hs.serverHello.cookie
   197  	}
   198  
   199  	if hs.serverHello.serverShare.group != 0 {
   200  		c.sendAlert(alertDecodeError)
   201  		return errors.New("tls: received malformed key_share extension")
   202  	}
   203  
   204  	// If the server sent a key_share extension selecting a group, ensure it's
   205  	// a group we advertised but did not send a key share for, and send a key
   206  	// share for it this time.
   207  	if curveID := hs.serverHello.selectedGroup; curveID != 0 {
   208  		curveOK := false
   209  		for _, id := range hs.hello.supportedCurves {
   210  			if id == curveID {
   211  				curveOK = true
   212  				break
   213  			}
   214  		}
   215  		if !curveOK {
   216  			c.sendAlert(alertIllegalParameter)
   217  			return errors.New("tls: server selected unsupported group")
   218  		}
   219  		if hs.ecdheParams.CurveID() == curveID {
   220  			c.sendAlert(alertIllegalParameter)
   221  			return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
   222  		}
   223  		if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   224  			c.sendAlert(alertInternalError)
   225  			return errors.New("tls: CurvePreferences includes unsupported curve")
   226  		}
   227  		params, err := generateECDHEParameters(c.config.rand(), curveID)
   228  		if err != nil {
   229  			c.sendAlert(alertInternalError)
   230  			return err
   231  		}
   232  		hs.ecdheParams = params
   233  		hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
   234  	}
   235  
   236  	hs.hello.raw = nil
   237  	if len(hs.hello.pskIdentities) > 0 {
   238  		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   239  		if pskSuite == nil {
   240  			return c.sendAlert(alertInternalError)
   241  		}
   242  		if pskSuite.hash == hs.suite.hash {
   243  			// Update binders and obfuscated_ticket_age.
   244  			ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
   245  			hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
   246  
   247  			transcript := hs.suite.hash.New()
   248  			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   249  			transcript.Write(chHash)
   250  			transcript.Write(hs.serverHello.marshal())
   251  			transcript.Write(hs.hello.marshalWithoutBinders())
   252  			pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
   253  			hs.hello.updateBinders(pskBinders)
   254  		} else {
   255  			// Server selected a cipher suite incompatible with the PSK.
   256  			hs.hello.pskIdentities = nil
   257  			hs.hello.pskBinders = nil
   258  		}
   259  	}
   260  
   261  	hs.transcript.Write(hs.hello.marshal())
   262  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   263  		return err
   264  	}
   265  
   266  	msg, err := c.readHandshake()
   267  	if err != nil {
   268  		return err
   269  	}
   270  
   271  	serverHello, ok := msg.(*serverHelloMsg)
   272  	if !ok {
   273  		c.sendAlert(alertUnexpectedMessage)
   274  		return unexpectedMessageError(serverHello, msg)
   275  	}
   276  	hs.serverHello = serverHello
   277  
   278  	if err := hs.checkServerHelloOrHRR(); err != nil {
   279  		return err
   280  	}
   281  
   282  	return nil
   283  }
   284  
   285  func (hs *clientHandshakeStateTLS13) processServerHello() error {
   286  	c := hs.c
   287  
   288  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
   289  		c.sendAlert(alertUnexpectedMessage)
   290  		return errors.New("tls: server sent two HelloRetryRequest messages")
   291  	}
   292  
   293  	if len(hs.serverHello.cookie) != 0 {
   294  		c.sendAlert(alertUnsupportedExtension)
   295  		return errors.New("tls: server sent a cookie in a normal ServerHello")
   296  	}
   297  
   298  	if hs.serverHello.selectedGroup != 0 {
   299  		c.sendAlert(alertDecodeError)
   300  		return errors.New("tls: malformed key_share extension")
   301  	}
   302  
   303  	if hs.serverHello.serverShare.group == 0 {
   304  		c.sendAlert(alertIllegalParameter)
   305  		return errors.New("tls: server did not send a key share")
   306  	}
   307  	if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
   308  		c.sendAlert(alertIllegalParameter)
   309  		return errors.New("tls: server selected unsupported group")
   310  	}
   311  
   312  	if !hs.serverHello.selectedIdentityPresent {
   313  		return nil
   314  	}
   315  
   316  	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
   317  		c.sendAlert(alertIllegalParameter)
   318  		return errors.New("tls: server selected an invalid PSK")
   319  	}
   320  
   321  	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
   322  		return c.sendAlert(alertInternalError)
   323  	}
   324  	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   325  	if pskSuite == nil {
   326  		return c.sendAlert(alertInternalError)
   327  	}
   328  	if pskSuite.hash != hs.suite.hash {
   329  		c.sendAlert(alertIllegalParameter)
   330  		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
   331  	}
   332  
   333  	hs.usingPSK = true
   334  	c.didResume = true
   335  	c.peerCertificates = hs.session.serverCertificates
   336  	c.verifiedChains = hs.session.verifiedChains
   337  	c.ocspResponse = hs.session.ocspResponse
   338  	c.scts = hs.session.scts
   339  	return nil
   340  }
   341  
   342  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
   343  	c := hs.c
   344  
   345  	sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
   346  	if sharedKey == nil {
   347  		c.sendAlert(alertIllegalParameter)
   348  		return errors.New("tls: invalid server key share")
   349  	}
   350  
   351  	earlySecret := hs.earlySecret
   352  	if !hs.usingPSK {
   353  		earlySecret = hs.suite.extract(nil, nil)
   354  	}
   355  	handshakeSecret := hs.suite.extract(sharedKey,
   356  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   357  
   358  	clientSecret := hs.suite.deriveSecret(handshakeSecret,
   359  		clientHandshakeTrafficLabel, hs.transcript)
   360  	c.out.setTrafficSecret(hs.suite, clientSecret)
   361  	serverSecret := hs.suite.deriveSecret(handshakeSecret,
   362  		serverHandshakeTrafficLabel, hs.transcript)
   363  	c.in.setTrafficSecret(hs.suite, serverSecret)
   364  
   365  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
   366  	if err != nil {
   367  		c.sendAlert(alertInternalError)
   368  		return err
   369  	}
   370  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
   371  	if err != nil {
   372  		c.sendAlert(alertInternalError)
   373  		return err
   374  	}
   375  
   376  	hs.masterSecret = hs.suite.extract(nil,
   377  		hs.suite.deriveSecret(handshakeSecret, "derived", nil))
   378  
   379  	return nil
   380  }
   381  
   382  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
   383  	c := hs.c
   384  
   385  	msg, err := c.readHandshake()
   386  	if err != nil {
   387  		return err
   388  	}
   389  
   390  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
   391  	if !ok {
   392  		c.sendAlert(alertUnexpectedMessage)
   393  		return unexpectedMessageError(encryptedExtensions, msg)
   394  	}
   395  	hs.transcript.Write(encryptedExtensions.marshal())
   396  
   397  	if encryptedExtensions.alpnProtocol != "" {
   398  		if len(hs.hello.alpnProtocols) == 0 {
   399  			c.sendAlert(alertUnsupportedExtension)
   400  			return errors.New("tls: server advertised unrequested ALPN extension")
   401  		}
   402  		if mutualProtocol([]string{encryptedExtensions.alpnProtocol}, hs.hello.alpnProtocols) == "" {
   403  			c.sendAlert(alertUnsupportedExtension)
   404  			return errors.New("tls: server selected unadvertised ALPN protocol")
   405  		}
   406  		c.clientProtocol = encryptedExtensions.alpnProtocol
   407  	}
   408  
   409  	return nil
   410  }
   411  
   412  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
   413  	c := hs.c
   414  
   415  	// Either a PSK or a certificate is always used, but not both.
   416  	// See RFC 8446, Section 4.1.1.
   417  	if hs.usingPSK {
   418  		// Make sure the connection is still being verified whether or not this
   419  		// is a resumption. Resumptions currently don't reverify certificates so
   420  		// they don't call verifyServerCertificate. See Issue 31641.
   421  		if c.config.VerifyConnection != nil {
   422  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   423  				c.sendAlert(alertBadCertificate)
   424  				return err
   425  			}
   426  		}
   427  		return nil
   428  	}
   429  
   430  	msg, err := c.readHandshake()
   431  	if err != nil {
   432  		return err
   433  	}
   434  
   435  	certReq, ok := msg.(*certificateRequestMsgTLS13)
   436  	if ok {
   437  		hs.transcript.Write(certReq.marshal())
   438  
   439  		hs.certReq = certReq
   440  
   441  		msg, err = c.readHandshake()
   442  		if err != nil {
   443  			return err
   444  		}
   445  	}
   446  
   447  	certMsg, ok := msg.(*certificateMsgTLS13)
   448  	if !ok {
   449  		c.sendAlert(alertUnexpectedMessage)
   450  		return unexpectedMessageError(certMsg, msg)
   451  	}
   452  	if len(certMsg.certificate.Certificate) == 0 {
   453  		c.sendAlert(alertDecodeError)
   454  		return errors.New("tls: received empty certificates message")
   455  	}
   456  	hs.transcript.Write(certMsg.marshal())
   457  
   458  	c.scts = certMsg.certificate.SignedCertificateTimestamps
   459  	c.ocspResponse = certMsg.certificate.OCSPStaple
   460  
   461  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
   462  		return err
   463  	}
   464  
   465  	msg, err = c.readHandshake()
   466  	if err != nil {
   467  		return err
   468  	}
   469  
   470  	certVerify, ok := msg.(*certificateVerifyMsg)
   471  	if !ok {
   472  		c.sendAlert(alertUnexpectedMessage)
   473  		return unexpectedMessageError(certVerify, msg)
   474  	}
   475  
   476  	// See RFC 8446, Section 4.4.3.
   477  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
   478  		c.sendAlert(alertIllegalParameter)
   479  		return errors.New("tls: certificate used with invalid signature algorithm")
   480  	}
   481  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   482  	if err != nil {
   483  		return c.sendAlert(alertInternalError)
   484  	}
   485  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   486  		c.sendAlert(alertIllegalParameter)
   487  		return errors.New("tls: certificate used with invalid signature algorithm")
   488  	}
   489  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   490  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   491  		sigHash, signed, certVerify.signature); err != nil {
   492  		c.sendAlert(alertDecryptError)
   493  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
   494  	}
   495  
   496  	hs.transcript.Write(certVerify.marshal())
   497  
   498  	return nil
   499  }
   500  
   501  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
   502  	c := hs.c
   503  
   504  	msg, err := c.readHandshake()
   505  	if err != nil {
   506  		return err
   507  	}
   508  
   509  	finished, ok := msg.(*finishedMsg)
   510  	if !ok {
   511  		c.sendAlert(alertUnexpectedMessage)
   512  		return unexpectedMessageError(finished, msg)
   513  	}
   514  
   515  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   516  	if !hmac.Equal(expectedMAC, finished.verifyData) {
   517  		c.sendAlert(alertDecryptError)
   518  		return errors.New("tls: invalid server finished hash")
   519  	}
   520  
   521  	hs.transcript.Write(finished.marshal())
   522  
   523  	// Derive secrets that take context through the server Finished.
   524  
   525  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   526  		clientApplicationTrafficLabel, hs.transcript)
   527  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   528  		serverApplicationTrafficLabel, hs.transcript)
   529  	c.in.setTrafficSecret(hs.suite, serverSecret)
   530  
   531  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
   532  	if err != nil {
   533  		c.sendAlert(alertInternalError)
   534  		return err
   535  	}
   536  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
   537  	if err != nil {
   538  		c.sendAlert(alertInternalError)
   539  		return err
   540  	}
   541  
   542  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   543  
   544  	return nil
   545  }
   546  
   547  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
   548  	c := hs.c
   549  
   550  	if hs.certReq == nil {
   551  		return nil
   552  	}
   553  
   554  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
   555  		AcceptableCAs:    hs.certReq.certificateAuthorities,
   556  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
   557  		Version:          c.vers,
   558  	})
   559  	if err != nil {
   560  		return err
   561  	}
   562  
   563  	certMsg := new(certificateMsgTLS13)
   564  
   565  	certMsg.certificate = *cert
   566  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   567  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   568  
   569  	hs.transcript.Write(certMsg.marshal())
   570  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   571  		return err
   572  	}
   573  
   574  	// If we sent an empty certificate message, skip the CertificateVerify.
   575  	if len(cert.Certificate) == 0 {
   576  		return nil
   577  	}
   578  
   579  	certVerifyMsg := new(certificateVerifyMsg)
   580  	certVerifyMsg.hasSignatureAlgorithm = true
   581  
   582  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
   583  	if err != nil {
   584  		// getClientCertificate returned a certificate incompatible with the
   585  		// CertificateRequestInfo supported signature algorithms.
   586  		c.sendAlert(alertHandshakeFailure)
   587  		return err
   588  	}
   589  
   590  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   591  	if err != nil {
   592  		return c.sendAlert(alertInternalError)
   593  	}
   594  
   595  	signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   596  	signOpts := crypto.SignerOpts(sigHash)
   597  	if sigType == signatureRSAPSS {
   598  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   599  	}
   600  	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   601  	if err != nil {
   602  		c.sendAlert(alertInternalError)
   603  		return errors.New("tls: failed to sign handshake: " + err.Error())
   604  	}
   605  	certVerifyMsg.signature = sig
   606  
   607  	hs.transcript.Write(certVerifyMsg.marshal())
   608  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   609  		return err
   610  	}
   611  
   612  	return nil
   613  }
   614  
   615  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   616  	c := hs.c
   617  
   618  	finished := &finishedMsg{
   619  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   620  	}
   621  
   622  	hs.transcript.Write(finished.marshal())
   623  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   624  		return err
   625  	}
   626  
   627  	c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
   628  
   629  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   630  		c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
   631  			resumptionLabel, hs.transcript)
   632  	}
   633  
   634  	return nil
   635  }
   636  
   637  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   638  	if !c.isClient {
   639  		c.sendAlert(alertUnexpectedMessage)
   640  		return errors.New("tls: received new session ticket from a client")
   641  	}
   642  
   643  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   644  		return nil
   645  	}
   646  
   647  	// See RFC 8446, Section 4.6.1.
   648  	if msg.lifetime == 0 {
   649  		return nil
   650  	}
   651  	lifetime := time.Duration(msg.lifetime) * time.Second
   652  	if lifetime > maxSessionTicketLifetime {
   653  		c.sendAlert(alertIllegalParameter)
   654  		return errors.New("tls: received a session ticket with invalid lifetime")
   655  	}
   656  
   657  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   658  	if cipherSuite == nil || c.resumptionSecret == nil {
   659  		return c.sendAlert(alertInternalError)
   660  	}
   661  
   662  	// Save the resumption_master_secret and nonce instead of deriving the PSK
   663  	// to do the least amount of work on NewSessionTicket messages before we
   664  	// know if the ticket will be used. Forward secrecy of resumed connections
   665  	// is guaranteed by the requirement for pskModeDHE.
   666  	session := &ClientSessionState{
   667  		sessionTicket:      msg.label,
   668  		vers:               c.vers,
   669  		cipherSuite:        c.cipherSuite,
   670  		masterSecret:       c.resumptionSecret,
   671  		serverCertificates: c.peerCertificates,
   672  		verifiedChains:     c.verifiedChains,
   673  		receivedAt:         c.config.time(),
   674  		nonce:              msg.nonce,
   675  		useBy:              c.config.time().Add(lifetime),
   676  		ageAdd:             msg.ageAdd,
   677  		ocspResponse:       c.ocspResponse,
   678  		scts:               c.scts,
   679  	}
   680  
   681  	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   682  	c.config.ClientSessionCache.Put(cacheKey, session)
   683  
   684  	return nil
   685  }