Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/tls/handshake_client_tls13.go

Documentation: crypto/tls

     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 len(encryptedExtensions.alpnProtocol) != 0 && len(hs.hello.alpnProtocols) == 0 {
   398  		c.sendAlert(alertUnsupportedExtension)
   399  		return errors.New("tls: server advertised unrequested ALPN extension")
   400  	}
   401  	c.clientProtocol = encryptedExtensions.alpnProtocol
   402  
   403  	return nil
   404  }
   405  
   406  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
   407  	c := hs.c
   408  
   409  	// Either a PSK or a certificate is always used, but not both.
   410  	// See RFC 8446, Section 4.1.1.
   411  	if hs.usingPSK {
   412  		// Make sure the connection is still being verified whether or not this
   413  		// is a resumption. Resumptions currently don't reverify certificates so
   414  		// they don't call verifyServerCertificate. See Issue 31641.
   415  		if c.config.VerifyConnection != nil {
   416  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   417  				c.sendAlert(alertBadCertificate)
   418  				return err
   419  			}
   420  		}
   421  		return nil
   422  	}
   423  
   424  	msg, err := c.readHandshake()
   425  	if err != nil {
   426  		return err
   427  	}
   428  
   429  	certReq, ok := msg.(*certificateRequestMsgTLS13)
   430  	if ok {
   431  		hs.transcript.Write(certReq.marshal())
   432  
   433  		hs.certReq = certReq
   434  
   435  		msg, err = c.readHandshake()
   436  		if err != nil {
   437  			return err
   438  		}
   439  	}
   440  
   441  	certMsg, ok := msg.(*certificateMsgTLS13)
   442  	if !ok {
   443  		c.sendAlert(alertUnexpectedMessage)
   444  		return unexpectedMessageError(certMsg, msg)
   445  	}
   446  	if len(certMsg.certificate.Certificate) == 0 {
   447  		c.sendAlert(alertDecodeError)
   448  		return errors.New("tls: received empty certificates message")
   449  	}
   450  	hs.transcript.Write(certMsg.marshal())
   451  
   452  	c.scts = certMsg.certificate.SignedCertificateTimestamps
   453  	c.ocspResponse = certMsg.certificate.OCSPStaple
   454  
   455  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
   456  		return err
   457  	}
   458  
   459  	msg, err = c.readHandshake()
   460  	if err != nil {
   461  		return err
   462  	}
   463  
   464  	certVerify, ok := msg.(*certificateVerifyMsg)
   465  	if !ok {
   466  		c.sendAlert(alertUnexpectedMessage)
   467  		return unexpectedMessageError(certVerify, msg)
   468  	}
   469  
   470  	// See RFC 8446, Section 4.4.3.
   471  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
   472  		c.sendAlert(alertIllegalParameter)
   473  		return errors.New("tls: certificate used with invalid signature algorithm")
   474  	}
   475  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   476  	if err != nil {
   477  		return c.sendAlert(alertInternalError)
   478  	}
   479  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   480  		c.sendAlert(alertIllegalParameter)
   481  		return errors.New("tls: certificate used with invalid signature algorithm")
   482  	}
   483  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   484  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   485  		sigHash, signed, certVerify.signature); err != nil {
   486  		c.sendAlert(alertDecryptError)
   487  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
   488  	}
   489  
   490  	hs.transcript.Write(certVerify.marshal())
   491  
   492  	return nil
   493  }
   494  
   495  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
   496  	c := hs.c
   497  
   498  	msg, err := c.readHandshake()
   499  	if err != nil {
   500  		return err
   501  	}
   502  
   503  	finished, ok := msg.(*finishedMsg)
   504  	if !ok {
   505  		c.sendAlert(alertUnexpectedMessage)
   506  		return unexpectedMessageError(finished, msg)
   507  	}
   508  
   509  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   510  	if !hmac.Equal(expectedMAC, finished.verifyData) {
   511  		c.sendAlert(alertDecryptError)
   512  		return errors.New("tls: invalid server finished hash")
   513  	}
   514  
   515  	hs.transcript.Write(finished.marshal())
   516  
   517  	// Derive secrets that take context through the server Finished.
   518  
   519  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   520  		clientApplicationTrafficLabel, hs.transcript)
   521  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   522  		serverApplicationTrafficLabel, hs.transcript)
   523  	c.in.setTrafficSecret(hs.suite, serverSecret)
   524  
   525  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
   526  	if err != nil {
   527  		c.sendAlert(alertInternalError)
   528  		return err
   529  	}
   530  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
   531  	if err != nil {
   532  		c.sendAlert(alertInternalError)
   533  		return err
   534  	}
   535  
   536  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   537  
   538  	return nil
   539  }
   540  
   541  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
   542  	c := hs.c
   543  
   544  	if hs.certReq == nil {
   545  		return nil
   546  	}
   547  
   548  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
   549  		AcceptableCAs:    hs.certReq.certificateAuthorities,
   550  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
   551  		Version:          c.vers,
   552  	})
   553  	if err != nil {
   554  		return err
   555  	}
   556  
   557  	certMsg := new(certificateMsgTLS13)
   558  
   559  	certMsg.certificate = *cert
   560  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   561  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   562  
   563  	hs.transcript.Write(certMsg.marshal())
   564  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   565  		return err
   566  	}
   567  
   568  	// If we sent an empty certificate message, skip the CertificateVerify.
   569  	if len(cert.Certificate) == 0 {
   570  		return nil
   571  	}
   572  
   573  	certVerifyMsg := new(certificateVerifyMsg)
   574  	certVerifyMsg.hasSignatureAlgorithm = true
   575  
   576  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
   577  	if err != nil {
   578  		// getClientCertificate returned a certificate incompatible with the
   579  		// CertificateRequestInfo supported signature algorithms.
   580  		c.sendAlert(alertHandshakeFailure)
   581  		return err
   582  	}
   583  
   584  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   585  	if err != nil {
   586  		return c.sendAlert(alertInternalError)
   587  	}
   588  
   589  	signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   590  	signOpts := crypto.SignerOpts(sigHash)
   591  	if sigType == signatureRSAPSS {
   592  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   593  	}
   594  	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   595  	if err != nil {
   596  		c.sendAlert(alertInternalError)
   597  		return errors.New("tls: failed to sign handshake: " + err.Error())
   598  	}
   599  	certVerifyMsg.signature = sig
   600  
   601  	hs.transcript.Write(certVerifyMsg.marshal())
   602  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   603  		return err
   604  	}
   605  
   606  	return nil
   607  }
   608  
   609  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   610  	c := hs.c
   611  
   612  	finished := &finishedMsg{
   613  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   614  	}
   615  
   616  	hs.transcript.Write(finished.marshal())
   617  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   618  		return err
   619  	}
   620  
   621  	c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
   622  
   623  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   624  		c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
   625  			resumptionLabel, hs.transcript)
   626  	}
   627  
   628  	return nil
   629  }
   630  
   631  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   632  	if !c.isClient {
   633  		c.sendAlert(alertUnexpectedMessage)
   634  		return errors.New("tls: received new session ticket from a client")
   635  	}
   636  
   637  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   638  		return nil
   639  	}
   640  
   641  	// See RFC 8446, Section 4.6.1.
   642  	if msg.lifetime == 0 {
   643  		return nil
   644  	}
   645  	lifetime := time.Duration(msg.lifetime) * time.Second
   646  	if lifetime > maxSessionTicketLifetime {
   647  		c.sendAlert(alertIllegalParameter)
   648  		return errors.New("tls: received a session ticket with invalid lifetime")
   649  	}
   650  
   651  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   652  	if cipherSuite == nil || c.resumptionSecret == nil {
   653  		return c.sendAlert(alertInternalError)
   654  	}
   655  
   656  	// Save the resumption_master_secret and nonce instead of deriving the PSK
   657  	// to do the least amount of work on NewSessionTicket messages before we
   658  	// know if the ticket will be used. Forward secrecy of resumed connections
   659  	// is guaranteed by the requirement for pskModeDHE.
   660  	session := &ClientSessionState{
   661  		sessionTicket:      msg.label,
   662  		vers:               c.vers,
   663  		cipherSuite:        c.cipherSuite,
   664  		masterSecret:       c.resumptionSecret,
   665  		serverCertificates: c.peerCertificates,
   666  		verifiedChains:     c.verifiedChains,
   667  		receivedAt:         c.config.time(),
   668  		nonce:              msg.nonce,
   669  		useBy:              c.config.time().Add(lifetime),
   670  		ageAdd:             msg.ageAdd,
   671  		ocspResponse:       c.ocspResponse,
   672  		scts:               c.scts,
   673  	}
   674  
   675  	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   676  	c.config.ClientSessionCache.Put(cacheKey, session)
   677  
   678  	return nil
   679  }
   680  

View as plain text