...

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  	"context"
    10  	"crypto"
    11  	"crypto/hmac"
    12  	"crypto/rsa"
    13  	"errors"
    14  	"hash"
    15  	"sync/atomic"
    16  	"time"
    17  )
    18  
    19  type clientHandshakeStateTLS13 struct {
    20  	c           *Conn
    21  	ctx         context.Context
    22  	serverHello *serverHelloMsg
    23  	hello       *clientHelloMsg
    24  	ecdheParams ecdheParameters
    25  
    26  	session     *ClientSessionState
    27  	earlySecret []byte
    28  	binderKey   []byte
    29  
    30  	certReq       *certificateRequestMsgTLS13
    31  	usingPSK      bool
    32  	sentDummyCCS  bool
    33  	suite         *cipherSuiteTLS13
    34  	transcript    hash.Hash
    35  	masterSecret  []byte
    36  	trafficSecret []byte // client_application_traffic_secret_0
    37  }
    38  
    39  // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and,
    40  // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
    41  func (hs *clientHandshakeStateTLS13) handshake() error {
    42  	c := hs.c
    43  
    44  	if needFIPS() {
    45  		return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
    46  	}
    47  
    48  	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
    49  	// sections 4.1.2 and 4.1.3.
    50  	if c.handshakes > 0 {
    51  		c.sendAlert(alertProtocolVersion)
    52  		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
    53  	}
    54  
    55  	// Consistency check on the presence of a keyShare and its parameters.
    56  	if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 {
    57  		return c.sendAlert(alertInternalError)
    58  	}
    59  
    60  	if err := hs.checkServerHelloOrHRR(); err != nil {
    61  		return err
    62  	}
    63  
    64  	hs.transcript = hs.suite.hash.New()
    65  	hs.transcript.Write(hs.hello.marshal())
    66  
    67  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
    68  		if err := hs.sendDummyChangeCipherSpec(); err != nil {
    69  			return err
    70  		}
    71  		if err := hs.processHelloRetryRequest(); err != nil {
    72  			return err
    73  		}
    74  	}
    75  
    76  	hs.transcript.Write(hs.serverHello.marshal())
    77  
    78  	c.buffering = true
    79  	if err := hs.processServerHello(); err != nil {
    80  		return err
    81  	}
    82  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
    83  		return err
    84  	}
    85  	if err := hs.establishHandshakeKeys(); err != nil {
    86  		return err
    87  	}
    88  	if err := hs.readServerParameters(); err != nil {
    89  		return err
    90  	}
    91  	if err := hs.readServerCertificate(); err != nil {
    92  		return err
    93  	}
    94  	if err := hs.readServerFinished(); err != nil {
    95  		return err
    96  	}
    97  	if err := hs.sendClientCertificate(); err != nil {
    98  		return err
    99  	}
   100  	if err := hs.sendClientFinished(); err != nil {
   101  		return err
   102  	}
   103  	if _, err := c.flush(); err != nil {
   104  		return err
   105  	}
   106  
   107  	atomic.StoreUint32(&c.handshakeStatus, 1)
   108  
   109  	return nil
   110  }
   111  
   112  // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
   113  // HelloRetryRequest messages. It sets hs.suite.
   114  func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
   115  	c := hs.c
   116  
   117  	if hs.serverHello.supportedVersion == 0 {
   118  		c.sendAlert(alertMissingExtension)
   119  		return errors.New("tls: server selected TLS 1.3 using the legacy version field")
   120  	}
   121  
   122  	if hs.serverHello.supportedVersion != VersionTLS13 {
   123  		c.sendAlert(alertIllegalParameter)
   124  		return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
   125  	}
   126  
   127  	if hs.serverHello.vers != VersionTLS12 {
   128  		c.sendAlert(alertIllegalParameter)
   129  		return errors.New("tls: server sent an incorrect legacy version")
   130  	}
   131  
   132  	if hs.serverHello.ocspStapling ||
   133  		hs.serverHello.ticketSupported ||
   134  		hs.serverHello.secureRenegotiationSupported ||
   135  		len(hs.serverHello.secureRenegotiation) != 0 ||
   136  		len(hs.serverHello.alpnProtocol) != 0 ||
   137  		len(hs.serverHello.scts) != 0 {
   138  		c.sendAlert(alertUnsupportedExtension)
   139  		return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
   140  	}
   141  
   142  	if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
   143  		c.sendAlert(alertIllegalParameter)
   144  		return errors.New("tls: server did not echo the legacy session ID")
   145  	}
   146  
   147  	if hs.serverHello.compressionMethod != compressionNone {
   148  		c.sendAlert(alertIllegalParameter)
   149  		return errors.New("tls: server selected unsupported compression format")
   150  	}
   151  
   152  	selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
   153  	if hs.suite != nil && selectedSuite != hs.suite {
   154  		c.sendAlert(alertIllegalParameter)
   155  		return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
   156  	}
   157  	if selectedSuite == nil {
   158  		c.sendAlert(alertIllegalParameter)
   159  		return errors.New("tls: server chose an unconfigured cipher suite")
   160  	}
   161  	hs.suite = selectedSuite
   162  	c.cipherSuite = hs.suite.id
   163  
   164  	return nil
   165  }
   166  
   167  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   168  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   169  func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   170  	if hs.sentDummyCCS {
   171  		return nil
   172  	}
   173  	hs.sentDummyCCS = true
   174  
   175  	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
   176  	return err
   177  }
   178  
   179  // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
   180  // resends hs.hello, and reads the new ServerHello into hs.serverHello.
   181  func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
   182  	c := hs.c
   183  
   184  	// The first ClientHello gets double-hashed into the transcript upon a
   185  	// HelloRetryRequest. (The idea is that the server might offload transcript
   186  	// storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
   187  	chHash := hs.transcript.Sum(nil)
   188  	hs.transcript.Reset()
   189  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   190  	hs.transcript.Write(chHash)
   191  	hs.transcript.Write(hs.serverHello.marshal())
   192  
   193  	// The only HelloRetryRequest extensions we support are key_share and
   194  	// cookie, and clients must abort the handshake if the HRR would not result
   195  	// in any change in the ClientHello.
   196  	if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
   197  		c.sendAlert(alertIllegalParameter)
   198  		return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
   199  	}
   200  
   201  	if hs.serverHello.cookie != nil {
   202  		hs.hello.cookie = hs.serverHello.cookie
   203  	}
   204  
   205  	if hs.serverHello.serverShare.group != 0 {
   206  		c.sendAlert(alertDecodeError)
   207  		return errors.New("tls: received malformed key_share extension")
   208  	}
   209  
   210  	// If the server sent a key_share extension selecting a group, ensure it's
   211  	// a group we advertised but did not send a key share for, and send a key
   212  	// share for it this time.
   213  	if curveID := hs.serverHello.selectedGroup; curveID != 0 {
   214  		curveOK := false
   215  		for _, id := range hs.hello.supportedCurves {
   216  			if id == curveID {
   217  				curveOK = true
   218  				break
   219  			}
   220  		}
   221  		if !curveOK {
   222  			c.sendAlert(alertIllegalParameter)
   223  			return errors.New("tls: server selected unsupported group")
   224  		}
   225  		if hs.ecdheParams.CurveID() == curveID {
   226  			c.sendAlert(alertIllegalParameter)
   227  			return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
   228  		}
   229  		if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   230  			c.sendAlert(alertInternalError)
   231  			return errors.New("tls: CurvePreferences includes unsupported curve")
   232  		}
   233  		params, err := generateECDHEParameters(c.config.rand(), curveID)
   234  		if err != nil {
   235  			c.sendAlert(alertInternalError)
   236  			return err
   237  		}
   238  		hs.ecdheParams = params
   239  		hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
   240  	}
   241  
   242  	hs.hello.raw = nil
   243  	if len(hs.hello.pskIdentities) > 0 {
   244  		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   245  		if pskSuite == nil {
   246  			return c.sendAlert(alertInternalError)
   247  		}
   248  		if pskSuite.hash == hs.suite.hash {
   249  			// Update binders and obfuscated_ticket_age.
   250  			ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
   251  			hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
   252  
   253  			transcript := hs.suite.hash.New()
   254  			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   255  			transcript.Write(chHash)
   256  			transcript.Write(hs.serverHello.marshal())
   257  			transcript.Write(hs.hello.marshalWithoutBinders())
   258  			pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
   259  			hs.hello.updateBinders(pskBinders)
   260  		} else {
   261  			// Server selected a cipher suite incompatible with the PSK.
   262  			hs.hello.pskIdentities = nil
   263  			hs.hello.pskBinders = nil
   264  		}
   265  	}
   266  
   267  	hs.transcript.Write(hs.hello.marshal())
   268  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   269  		return err
   270  	}
   271  
   272  	msg, err := c.readHandshake()
   273  	if err != nil {
   274  		return err
   275  	}
   276  
   277  	serverHello, ok := msg.(*serverHelloMsg)
   278  	if !ok {
   279  		c.sendAlert(alertUnexpectedMessage)
   280  		return unexpectedMessageError(serverHello, msg)
   281  	}
   282  	hs.serverHello = serverHello
   283  
   284  	if err := hs.checkServerHelloOrHRR(); err != nil {
   285  		return err
   286  	}
   287  
   288  	return nil
   289  }
   290  
   291  func (hs *clientHandshakeStateTLS13) processServerHello() error {
   292  	c := hs.c
   293  
   294  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
   295  		c.sendAlert(alertUnexpectedMessage)
   296  		return errors.New("tls: server sent two HelloRetryRequest messages")
   297  	}
   298  
   299  	if len(hs.serverHello.cookie) != 0 {
   300  		c.sendAlert(alertUnsupportedExtension)
   301  		return errors.New("tls: server sent a cookie in a normal ServerHello")
   302  	}
   303  
   304  	if hs.serverHello.selectedGroup != 0 {
   305  		c.sendAlert(alertDecodeError)
   306  		return errors.New("tls: malformed key_share extension")
   307  	}
   308  
   309  	if hs.serverHello.serverShare.group == 0 {
   310  		c.sendAlert(alertIllegalParameter)
   311  		return errors.New("tls: server did not send a key share")
   312  	}
   313  	if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() {
   314  		c.sendAlert(alertIllegalParameter)
   315  		return errors.New("tls: server selected unsupported group")
   316  	}
   317  
   318  	if !hs.serverHello.selectedIdentityPresent {
   319  		return nil
   320  	}
   321  
   322  	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
   323  		c.sendAlert(alertIllegalParameter)
   324  		return errors.New("tls: server selected an invalid PSK")
   325  	}
   326  
   327  	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
   328  		return c.sendAlert(alertInternalError)
   329  	}
   330  	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   331  	if pskSuite == nil {
   332  		return c.sendAlert(alertInternalError)
   333  	}
   334  	if pskSuite.hash != hs.suite.hash {
   335  		c.sendAlert(alertIllegalParameter)
   336  		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
   337  	}
   338  
   339  	hs.usingPSK = true
   340  	c.didResume = true
   341  	c.peerCertificates = hs.session.serverCertificates
   342  	c.verifiedChains = hs.session.verifiedChains
   343  	c.ocspResponse = hs.session.ocspResponse
   344  	c.scts = hs.session.scts
   345  	return nil
   346  }
   347  
   348  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
   349  	c := hs.c
   350  
   351  	sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data)
   352  	if sharedKey == nil {
   353  		c.sendAlert(alertIllegalParameter)
   354  		return errors.New("tls: invalid server key share")
   355  	}
   356  
   357  	earlySecret := hs.earlySecret
   358  	if !hs.usingPSK {
   359  		earlySecret = hs.suite.extract(nil, nil)
   360  	}
   361  	handshakeSecret := hs.suite.extract(sharedKey,
   362  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   363  
   364  	clientSecret := hs.suite.deriveSecret(handshakeSecret,
   365  		clientHandshakeTrafficLabel, hs.transcript)
   366  	c.out.setTrafficSecret(hs.suite, clientSecret)
   367  	serverSecret := hs.suite.deriveSecret(handshakeSecret,
   368  		serverHandshakeTrafficLabel, hs.transcript)
   369  	c.in.setTrafficSecret(hs.suite, serverSecret)
   370  
   371  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
   372  	if err != nil {
   373  		c.sendAlert(alertInternalError)
   374  		return err
   375  	}
   376  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
   377  	if err != nil {
   378  		c.sendAlert(alertInternalError)
   379  		return err
   380  	}
   381  
   382  	hs.masterSecret = hs.suite.extract(nil,
   383  		hs.suite.deriveSecret(handshakeSecret, "derived", nil))
   384  
   385  	return nil
   386  }
   387  
   388  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
   389  	c := hs.c
   390  
   391  	msg, err := c.readHandshake()
   392  	if err != nil {
   393  		return err
   394  	}
   395  
   396  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
   397  	if !ok {
   398  		c.sendAlert(alertUnexpectedMessage)
   399  		return unexpectedMessageError(encryptedExtensions, msg)
   400  	}
   401  	hs.transcript.Write(encryptedExtensions.marshal())
   402  
   403  	if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil {
   404  		c.sendAlert(alertUnsupportedExtension)
   405  		return err
   406  	}
   407  	c.clientProtocol = encryptedExtensions.alpnProtocol
   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  		ctx:              hs.ctx,
   559  	})
   560  	if err != nil {
   561  		return err
   562  	}
   563  
   564  	certMsg := new(certificateMsgTLS13)
   565  
   566  	certMsg.certificate = *cert
   567  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   568  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   569  
   570  	hs.transcript.Write(certMsg.marshal())
   571  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   572  		return err
   573  	}
   574  
   575  	// If we sent an empty certificate message, skip the CertificateVerify.
   576  	if len(cert.Certificate) == 0 {
   577  		return nil
   578  	}
   579  
   580  	certVerifyMsg := new(certificateVerifyMsg)
   581  	certVerifyMsg.hasSignatureAlgorithm = true
   582  
   583  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
   584  	if err != nil {
   585  		// getClientCertificate returned a certificate incompatible with the
   586  		// CertificateRequestInfo supported signature algorithms.
   587  		c.sendAlert(alertHandshakeFailure)
   588  		return err
   589  	}
   590  
   591  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   592  	if err != nil {
   593  		return c.sendAlert(alertInternalError)
   594  	}
   595  
   596  	signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   597  	signOpts := crypto.SignerOpts(sigHash)
   598  	if sigType == signatureRSAPSS {
   599  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   600  	}
   601  	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   602  	if err != nil {
   603  		c.sendAlert(alertInternalError)
   604  		return errors.New("tls: failed to sign handshake: " + err.Error())
   605  	}
   606  	certVerifyMsg.signature = sig
   607  
   608  	hs.transcript.Write(certVerifyMsg.marshal())
   609  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   610  		return err
   611  	}
   612  
   613  	return nil
   614  }
   615  
   616  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   617  	c := hs.c
   618  
   619  	finished := &finishedMsg{
   620  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   621  	}
   622  
   623  	hs.transcript.Write(finished.marshal())
   624  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   625  		return err
   626  	}
   627  
   628  	c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
   629  
   630  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   631  		c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
   632  			resumptionLabel, hs.transcript)
   633  	}
   634  
   635  	return nil
   636  }
   637  
   638  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   639  	if !c.isClient {
   640  		c.sendAlert(alertUnexpectedMessage)
   641  		return errors.New("tls: received new session ticket from a client")
   642  	}
   643  
   644  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   645  		return nil
   646  	}
   647  
   648  	// See RFC 8446, Section 4.6.1.
   649  	if msg.lifetime == 0 {
   650  		return nil
   651  	}
   652  	lifetime := time.Duration(msg.lifetime) * time.Second
   653  	if lifetime > maxSessionTicketLifetime {
   654  		c.sendAlert(alertIllegalParameter)
   655  		return errors.New("tls: received a session ticket with invalid lifetime")
   656  	}
   657  
   658  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   659  	if cipherSuite == nil || c.resumptionSecret == nil {
   660  		return c.sendAlert(alertInternalError)
   661  	}
   662  
   663  	// Save the resumption_master_secret and nonce instead of deriving the PSK
   664  	// to do the least amount of work on NewSessionTicket messages before we
   665  	// know if the ticket will be used. Forward secrecy of resumed connections
   666  	// is guaranteed by the requirement for pskModeDHE.
   667  	session := &ClientSessionState{
   668  		sessionTicket:      msg.label,
   669  		vers:               c.vers,
   670  		cipherSuite:        c.cipherSuite,
   671  		masterSecret:       c.resumptionSecret,
   672  		serverCertificates: c.peerCertificates,
   673  		verifiedChains:     c.verifiedChains,
   674  		receivedAt:         c.config.time(),
   675  		nonce:              msg.nonce,
   676  		useBy:              c.config.time().Add(lifetime),
   677  		ageAdd:             msg.ageAdd,
   678  		ocspResponse:       c.ocspResponse,
   679  		scts:               c.scts,
   680  	}
   681  
   682  	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   683  	c.config.ClientSessionCache.Put(cacheKey, session)
   684  
   685  	return nil
   686  }
   687  

View as plain text