github.com/Carcraftz/utls@v0.0.0-20220413235215-6b7c52fd78b6/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  	"fmt"
    14  	"hash"
    15  	"sync/atomic"
    16  	"time"
    17  )
    18  
    19  type clientHandshakeStateTLS13 struct {
    20  	c           *Conn
    21  	serverHello *serverHelloMsg
    22  	hello       *clientHelloMsg
    23  	ecdheParams map[CurveID]ecdheParameters
    24  
    25  	session     *ClientSessionState
    26  	earlySecret []byte
    27  	binderKey   []byte
    28  
    29  	certReq       *certificateRequestMsgTLS13
    30  	usingPSK      bool
    31  	sentDummyCCS  bool
    32  	suite         *cipherSuiteTLS13
    33  	transcript    hash.Hash
    34  	masterSecret  []byte
    35  	trafficSecret []byte // client_application_traffic_secret_0
    36  
    37  	certCompAlgs []CertCompressionAlgo
    38  
    39  	uconn *UConn // [UTLS]
    40  }
    41  
    42  // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and,
    43  // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
    44  func (hs *clientHandshakeStateTLS13) handshake() error {
    45  	c := hs.c
    46  
    47  	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
    48  	// sections 4.1.2 and 4.1.3.
    49  	if c.handshakes > 0 {
    50  		c.sendAlert(alertProtocolVersion)
    51  		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
    52  	}
    53  
    54  	// Consistency check on the presence of a keyShare and its parameters.
    55  	if hs.ecdheParams == nil || len(hs.hello.keyShares) < 1 { // [uTLS]
    56  		// keyshares "< 1" instead of "!= 1", as uTLS may send multiple
    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.nextProtoNeg ||
   133  		len(hs.serverHello.nextProtos) != 0 ||
   134  		hs.serverHello.ocspStapling ||
   135  		hs.serverHello.ticketSupported ||
   136  		hs.serverHello.secureRenegotiationSupported ||
   137  		len(hs.serverHello.secureRenegotiation) != 0 ||
   138  		len(hs.serverHello.alpnProtocol) != 0 ||
   139  		len(hs.serverHello.scts) != 0 {
   140  		c.sendAlert(alertUnsupportedExtension)
   141  		return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
   142  	}
   143  
   144  	if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
   145  		c.sendAlert(alertIllegalParameter)
   146  		return errors.New("tls: server did not echo the legacy session ID")
   147  	}
   148  
   149  	if hs.serverHello.compressionMethod != compressionNone {
   150  		c.sendAlert(alertIllegalParameter)
   151  		return errors.New("tls: server selected unsupported compression format")
   152  	}
   153  
   154  	selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
   155  	if hs.suite != nil && selectedSuite != hs.suite {
   156  		c.sendAlert(alertIllegalParameter)
   157  		return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
   158  	}
   159  	if selectedSuite == nil {
   160  		c.sendAlert(alertIllegalParameter)
   161  		return errors.New("tls: server chose an unconfigured cipher suite")
   162  	}
   163  	hs.suite = selectedSuite
   164  	c.cipherSuite = hs.suite.id
   165  
   166  	return nil
   167  }
   168  
   169  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   170  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   171  func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   172  	if hs.sentDummyCCS {
   173  		return nil
   174  	}
   175  	hs.sentDummyCCS = true
   176  
   177  	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
   178  	return err
   179  }
   180  
   181  // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
   182  // resends hs.hello, and reads the new ServerHello into hs.serverHello.
   183  func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
   184  	c := hs.c
   185  
   186  	// The first ClientHello gets double-hashed into the transcript upon a
   187  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   188  	chHash := hs.transcript.Sum(nil)
   189  	hs.transcript.Reset()
   190  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   191  	hs.transcript.Write(chHash)
   192  	hs.transcript.Write(hs.serverHello.marshal())
   193  
   194  	if hs.serverHello.serverShare.group != 0 {
   195  		c.sendAlert(alertDecodeError)
   196  		return errors.New("tls: received malformed key_share extension")
   197  	}
   198  
   199  	curveID := hs.serverHello.selectedGroup
   200  	if curveID == 0 {
   201  		c.sendAlert(alertMissingExtension)
   202  		return errors.New("tls: received HelloRetryRequest without selected group")
   203  	}
   204  	curveOK := false
   205  	for _, id := range hs.hello.supportedCurves {
   206  		if id == curveID {
   207  			curveOK = true
   208  			break
   209  		}
   210  	}
   211  	if !curveOK || !utlsSupportedGroups[curveID] {
   212  		c.sendAlert(alertIllegalParameter)
   213  		return errors.New("tls: server selected unsupported group")
   214  	}
   215  	if _, ok := hs.ecdheParams[curveID]; !ok {
   216  		c.sendAlert(alertIllegalParameter)
   217  		return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
   218  	}
   219  
   220  	params, err := generateECDHEParameters(c.config.rand(), curveID)
   221  	if err != nil {
   222  		c.sendAlert(alertInternalError)
   223  		return err
   224  	}
   225  	hs.ecdheParams[curveID] = params
   226  	hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
   227  	hs.hello.cookie = hs.serverHello.cookie
   228  
   229  	hs.hello.raw = nil
   230  	if len(hs.hello.pskIdentities) > 0 {
   231  		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   232  		if pskSuite == nil {
   233  			return c.sendAlert(alertInternalError)
   234  		}
   235  		if pskSuite.hash == hs.suite.hash {
   236  			// Update binders and obfuscated_ticket_age.
   237  			ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
   238  			hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
   239  
   240  			transcript := hs.suite.hash.New()
   241  			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   242  			transcript.Write(chHash)
   243  			transcript.Write(hs.serverHello.marshal())
   244  			transcript.Write(hs.hello.marshalWithoutBinders())
   245  			pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
   246  			hs.hello.updateBinders(pskBinders)
   247  		} else {
   248  			// Server selected a cipher suite incompatible with the PSK.
   249  			hs.hello.pskIdentities = nil
   250  			hs.hello.pskBinders = nil
   251  		}
   252  	}
   253  
   254  	// [UTLS SECTION BEGINS]
   255  	// crypto/tls code above this point had changed crypto/tls structures in accordance with HRR, and is about
   256  	// to call default marshaller.
   257  	// Instead, we fill uTLS-specific structs and call uTLS marshaller.
   258  	// Only extensionCookie, extensionPreSharedKey, extensionKeyShare, extensionEarlyData, extensionSupportedVersions,
   259  	// and utlsExtensionPadding are supposed to change
   260  	if hs.uconn != nil {
   261  		if hs.uconn.ClientHelloID != HelloGolang {
   262  			if len(hs.hello.pskIdentities) > 0 {
   263  				// TODO: wait for someone who cares about PSK to implement
   264  				return errors.New("uTLS does not support reprocessing of PSK key triggered by HelloRetryRequest")
   265  			}
   266  
   267  			keyShareExtFound := false
   268  			for _, ext := range hs.uconn.Extensions {
   269  				// new ks seems to be generated either way
   270  				if ks, ok := ext.(*KeyShareExtension); ok {
   271  					ks.KeyShares = keyShares(hs.hello.keyShares).ToPublic()
   272  					keyShareExtFound = true
   273  				}
   274  			}
   275  			if !keyShareExtFound {
   276  				return errors.New("uTLS: received HelloRetryRequest, but keyshare not found among client's " +
   277  					"uconn.Extensions")
   278  			}
   279  
   280  			if len(hs.serverHello.cookie) > 0 {
   281  				// serverHello specified a cookie, let's echo it
   282  				cookieFound := false
   283  				for _, ext := range hs.uconn.Extensions {
   284  					if ks, ok := ext.(*CookieExtension); ok {
   285  						ks.Cookie = hs.serverHello.cookie
   286  						cookieFound = true
   287  					}
   288  				}
   289  
   290  				if !cookieFound {
   291  					// pick a random index where to add cookieExtension
   292  					// -2 instead of -1 is a lazy way to ensure that PSK is still a last extension
   293  					p, err := newPRNG()
   294  					if err != nil {
   295  						return err
   296  					}
   297  					cookieIndex := p.Intn(len(hs.uconn.Extensions) - 2)
   298  					if cookieIndex >= len(hs.uconn.Extensions) {
   299  						// this check is for empty hs.uconn.Extensions
   300  						return fmt.Errorf("cookieIndex >= len(hs.uconn.Extensions): %v >= %v",
   301  							cookieIndex, len(hs.uconn.Extensions))
   302  					}
   303  					hs.uconn.Extensions = append(hs.uconn.Extensions[:cookieIndex],
   304  						append([]TLSExtension{&CookieExtension{Cookie: hs.serverHello.cookie}},
   305  							hs.uconn.Extensions[cookieIndex:]...)...)
   306  				}
   307  			}
   308  			if err = hs.uconn.MarshalClientHello(); err != nil {
   309  				return err
   310  			}
   311  			hs.hello.raw = hs.uconn.HandshakeState.Hello.Raw
   312  		}
   313  	}
   314  	// [UTLS SECTION ENDS]
   315  
   316  	hs.transcript.Write(hs.hello.marshal())
   317  	if _, err = c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   318  		return err
   319  	}
   320  
   321  	msg, err := c.readHandshake()
   322  	if err != nil {
   323  		return err
   324  	}
   325  
   326  	serverHello, ok := msg.(*serverHelloMsg)
   327  	if !ok {
   328  		c.sendAlert(alertUnexpectedMessage)
   329  		return unexpectedMessageError(serverHello, msg)
   330  	}
   331  	hs.serverHello = serverHello
   332  
   333  	if err := hs.checkServerHelloOrHRR(); err != nil {
   334  		return err
   335  	}
   336  
   337  	return nil
   338  }
   339  
   340  func (hs *clientHandshakeStateTLS13) processServerHello() error {
   341  	c := hs.c
   342  
   343  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
   344  		c.sendAlert(alertUnexpectedMessage)
   345  		return errors.New("tls: server sent two HelloRetryRequest messages")
   346  	}
   347  
   348  	if len(hs.serverHello.cookie) != 0 {
   349  		c.sendAlert(alertUnsupportedExtension)
   350  		return errors.New("tls: server sent a cookie in a normal ServerHello")
   351  	}
   352  
   353  	if hs.serverHello.selectedGroup != 0 {
   354  		c.sendAlert(alertDecodeError)
   355  		return errors.New("tls: malformed key_share extension")
   356  	}
   357  
   358  	if hs.serverHello.serverShare.group == 0 {
   359  		c.sendAlert(alertIllegalParameter)
   360  		return errors.New("tls: server did not send a key share")
   361  	}
   362  	if _, ok := hs.ecdheParams[hs.serverHello.serverShare.group]; !ok {
   363  		c.sendAlert(alertIllegalParameter)
   364  		return errors.New("tls: server selected unsupported group")
   365  	}
   366  
   367  	if !hs.serverHello.selectedIdentityPresent {
   368  		return nil
   369  	}
   370  
   371  	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
   372  		c.sendAlert(alertIllegalParameter)
   373  		return errors.New("tls: server selected an invalid PSK")
   374  	}
   375  
   376  	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
   377  		return c.sendAlert(alertInternalError)
   378  	}
   379  	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   380  	if pskSuite == nil {
   381  		return c.sendAlert(alertInternalError)
   382  	}
   383  	if pskSuite.hash != hs.suite.hash {
   384  		c.sendAlert(alertIllegalParameter)
   385  		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
   386  	}
   387  
   388  	hs.usingPSK = true
   389  	c.didResume = true
   390  	c.peerCertificates = hs.session.serverCertificates
   391  	c.verifiedChains = hs.session.verifiedChains
   392  	return nil
   393  }
   394  
   395  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
   396  	c := hs.c
   397  
   398  	ecdheParams := hs.ecdheParams[hs.serverHello.serverShare.group]
   399  	sharedKey := ecdheParams.SharedKey(hs.serverHello.serverShare.data)
   400  	if sharedKey == nil {
   401  		c.sendAlert(alertIllegalParameter)
   402  		return errors.New("tls: invalid server key share")
   403  	}
   404  
   405  	earlySecret := hs.earlySecret
   406  	if !hs.usingPSK {
   407  		earlySecret = hs.suite.extract(nil, nil)
   408  	}
   409  	handshakeSecret := hs.suite.extract(sharedKey,
   410  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   411  
   412  	clientSecret := hs.suite.deriveSecret(handshakeSecret,
   413  		clientHandshakeTrafficLabel, hs.transcript)
   414  	c.out.setTrafficSecret(hs.suite, clientSecret)
   415  	serverSecret := hs.suite.deriveSecret(handshakeSecret,
   416  		serverHandshakeTrafficLabel, hs.transcript)
   417  	c.in.setTrafficSecret(hs.suite, serverSecret)
   418  
   419  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
   420  	if err != nil {
   421  		c.sendAlert(alertInternalError)
   422  		return err
   423  	}
   424  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
   425  	if err != nil {
   426  		c.sendAlert(alertInternalError)
   427  		return err
   428  	}
   429  
   430  	hs.masterSecret = hs.suite.extract(nil,
   431  		hs.suite.deriveSecret(handshakeSecret, "derived", nil))
   432  
   433  	return nil
   434  }
   435  
   436  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
   437  	c := hs.c
   438  
   439  	msg, err := c.readHandshake()
   440  	if err != nil {
   441  		return err
   442  	}
   443  
   444  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
   445  	if !ok {
   446  		c.sendAlert(alertUnexpectedMessage)
   447  		return unexpectedMessageError(encryptedExtensions, msg)
   448  	}
   449  	hs.transcript.Write(encryptedExtensions.marshal())
   450  
   451  	if len(encryptedExtensions.alpnProtocol) != 0 && len(hs.hello.alpnProtocols) == 0 {
   452  		c.sendAlert(alertUnsupportedExtension)
   453  		return errors.New("tls: server advertised unrequested ALPN extension")
   454  	}
   455  	c.clientProtocol = encryptedExtensions.alpnProtocol
   456  
   457  	return nil
   458  }
   459  
   460  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
   461  	c := hs.c
   462  
   463  	// Either a PSK or a certificate is always used, but not both.
   464  	// See RFC 8446, Section 4.1.1.
   465  	if hs.usingPSK {
   466  		return nil
   467  	}
   468  
   469  	msg, err := c.readHandshake()
   470  	if err != nil {
   471  		return err
   472  	}
   473  
   474  	certReq, ok := msg.(*certificateRequestMsgTLS13)
   475  	if ok {
   476  		hs.transcript.Write(certReq.marshal())
   477  
   478  		hs.certReq = certReq
   479  
   480  		msg, err = c.readHandshake()
   481  		if err != nil {
   482  			return err
   483  		}
   484  	}
   485  
   486  	var (
   487  		certMsg    *certificateMsgTLS13
   488  		rawCertMsg []byte
   489  	)
   490  	switch v := msg.(type) {
   491  	case *certificateMsgTLS13:
   492  		certMsg, rawCertMsg = v, v.marshal()
   493  	case *compressedCertificateMsg:
   494  		var algOk bool
   495  		for _, alg := range hs.certCompAlgs {
   496  			if alg == v.algorithm {
   497  				algOk = true
   498  				break
   499  			}
   500  		}
   501  		if !algOk {
   502  			c.sendAlert(alertUnexpectedMessage)
   503  			return unexpectedMessageError(certMsg, msg)
   504  		}
   505  		certMsg, err = v.toCertificateMsg()
   506  		if err != nil {
   507  			c.sendAlert(alertBadCertificate)
   508  			return err
   509  		}
   510  		rawCertMsg = v.marshal()
   511  	default:
   512  		c.sendAlert(alertUnexpectedMessage)
   513  		return unexpectedMessageError(certMsg, msg)
   514  	}
   515  
   516  	if len(certMsg.certificate.Certificate) == 0 {
   517  		c.sendAlert(alertDecodeError)
   518  		return errors.New("tls: received empty certificates message")
   519  	}
   520  	hs.transcript.Write(rawCertMsg)
   521  
   522  	c.scts = certMsg.certificate.SignedCertificateTimestamps
   523  	c.ocspResponse = certMsg.certificate.OCSPStaple
   524  
   525  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
   526  		return err
   527  	}
   528  
   529  	msg, err = c.readHandshake()
   530  	if err != nil {
   531  		return err
   532  	}
   533  
   534  	certVerify, ok := msg.(*certificateVerifyMsg)
   535  	if !ok {
   536  		c.sendAlert(alertUnexpectedMessage)
   537  		return unexpectedMessageError(certVerify, msg)
   538  	}
   539  
   540  	// See RFC 8446, Section 4.4.3.
   541  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
   542  		c.sendAlert(alertIllegalParameter)
   543  		return errors.New("tls: invalid certificate signature algorithm")
   544  	}
   545  	sigType := signatureFromSignatureScheme(certVerify.signatureAlgorithm)
   546  	sigHash, err := hashFromSignatureScheme(certVerify.signatureAlgorithm)
   547  	if sigType == 0 || err != nil {
   548  		c.sendAlert(alertInternalError)
   549  		return err
   550  	}
   551  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   552  		c.sendAlert(alertIllegalParameter)
   553  		return errors.New("tls: invalid certificate signature algorithm")
   554  	}
   555  	h := sigHash.New()
   556  	writeSignedMessage(h, serverSignatureContext, hs.transcript)
   557  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   558  		sigHash, h.Sum(nil), certVerify.signature); err != nil {
   559  		c.sendAlert(alertDecryptError)
   560  		return errors.New("tls: invalid certificate signature")
   561  	}
   562  
   563  	hs.transcript.Write(certVerify.marshal())
   564  
   565  	return nil
   566  }
   567  
   568  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
   569  	c := hs.c
   570  
   571  	msg, err := c.readHandshake()
   572  	if err != nil {
   573  		return err
   574  	}
   575  
   576  	finished, ok := msg.(*finishedMsg)
   577  	if !ok {
   578  		c.sendAlert(alertUnexpectedMessage)
   579  		return unexpectedMessageError(finished, msg)
   580  	}
   581  
   582  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   583  	if !hmac.Equal(expectedMAC, finished.verifyData) {
   584  		c.sendAlert(alertDecryptError)
   585  		return errors.New("tls: invalid server finished hash")
   586  	}
   587  
   588  	hs.transcript.Write(finished.marshal())
   589  
   590  	// Derive secrets that take context through the server Finished.
   591  
   592  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   593  		clientApplicationTrafficLabel, hs.transcript)
   594  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   595  		serverApplicationTrafficLabel, hs.transcript)
   596  	c.in.setTrafficSecret(hs.suite, serverSecret)
   597  
   598  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
   599  	if err != nil {
   600  		c.sendAlert(alertInternalError)
   601  		return err
   602  	}
   603  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
   604  	if err != nil {
   605  		c.sendAlert(alertInternalError)
   606  		return err
   607  	}
   608  
   609  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   610  
   611  	return nil
   612  }
   613  
   614  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
   615  	c := hs.c
   616  
   617  	if hs.certReq == nil {
   618  		return nil
   619  	}
   620  
   621  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
   622  		AcceptableCAs:    hs.certReq.certificateAuthorities,
   623  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
   624  	})
   625  	if err != nil {
   626  		return err
   627  	}
   628  
   629  	certMsg := new(certificateMsgTLS13)
   630  
   631  	certMsg.certificate = *cert
   632  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   633  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   634  
   635  	hs.transcript.Write(certMsg.marshal())
   636  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   637  		return err
   638  	}
   639  
   640  	// If we sent an empty certificate message, skip the CertificateVerify.
   641  	if len(cert.Certificate) == 0 {
   642  		return nil
   643  	}
   644  
   645  	certVerifyMsg := new(certificateVerifyMsg)
   646  	certVerifyMsg.hasSignatureAlgorithm = true
   647  
   648  	supportedAlgs := signatureSchemesForCertificate(c.vers, cert)
   649  	if supportedAlgs == nil {
   650  		c.sendAlert(alertInternalError)
   651  		return unsupportedCertificateError(cert)
   652  	}
   653  	// Pick signature scheme in server preference order, as the client
   654  	// preference order is not configurable.
   655  	for _, preferredAlg := range hs.certReq.supportedSignatureAlgorithms {
   656  		if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) {
   657  			certVerifyMsg.signatureAlgorithm = preferredAlg
   658  			break
   659  		}
   660  	}
   661  	if certVerifyMsg.signatureAlgorithm == 0 {
   662  		// getClientCertificate returned a certificate incompatible with the
   663  		// CertificateRequestInfo supported signature algorithms.
   664  		c.sendAlert(alertHandshakeFailure)
   665  		return errors.New("tls: server doesn't support selected certificate")
   666  	}
   667  
   668  	sigType := signatureFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   669  	sigHash, err := hashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   670  	if sigType == 0 || err != nil {
   671  		return c.sendAlert(alertInternalError)
   672  	}
   673  	h := sigHash.New()
   674  	writeSignedMessage(h, clientSignatureContext, hs.transcript)
   675  
   676  	signOpts := crypto.SignerOpts(sigHash)
   677  	if sigType == signatureRSAPSS {
   678  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   679  	}
   680  	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), h.Sum(nil), signOpts)
   681  	if err != nil {
   682  		c.sendAlert(alertInternalError)
   683  		return errors.New("tls: failed to sign handshake: " + err.Error())
   684  	}
   685  	certVerifyMsg.signature = sig
   686  
   687  	hs.transcript.Write(certVerifyMsg.marshal())
   688  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   689  		return err
   690  	}
   691  
   692  	return nil
   693  }
   694  
   695  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   696  	c := hs.c
   697  
   698  	finished := &finishedMsg{
   699  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   700  	}
   701  
   702  	hs.transcript.Write(finished.marshal())
   703  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   704  		return err
   705  	}
   706  
   707  	c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
   708  
   709  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   710  		c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
   711  			resumptionLabel, hs.transcript)
   712  	}
   713  
   714  	return nil
   715  }
   716  
   717  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   718  	if !c.isClient {
   719  		c.sendAlert(alertUnexpectedMessage)
   720  		return errors.New("tls: received new session ticket from a client")
   721  	}
   722  
   723  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   724  		return nil
   725  	}
   726  
   727  	// See RFC 8446, Section 4.6.1.
   728  	if msg.lifetime == 0 {
   729  		return nil
   730  	}
   731  	lifetime := time.Duration(msg.lifetime) * time.Second
   732  	if lifetime > maxSessionTicketLifetime {
   733  		c.sendAlert(alertIllegalParameter)
   734  		return errors.New("tls: received a session ticket with invalid lifetime")
   735  	}
   736  
   737  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   738  	if cipherSuite == nil || c.resumptionSecret == nil {
   739  		return c.sendAlert(alertInternalError)
   740  	}
   741  
   742  	// Save the resumption_master_secret and nonce instead of deriving the PSK
   743  	// to do the least amount of work on NewSessionTicket messages before we
   744  	// know if the ticket will be used. Forward secrecy of resumed connections
   745  	// is guaranteed by the requirement for pskModeDHE.
   746  	session := &ClientSessionState{
   747  		sessionTicket:      msg.label,
   748  		vers:               c.vers,
   749  		cipherSuite:        c.cipherSuite,
   750  		masterSecret:       c.resumptionSecret,
   751  		serverCertificates: c.peerCertificates,
   752  		verifiedChains:     c.verifiedChains,
   753  		receivedAt:         c.config.time(),
   754  		nonce:              msg.nonce,
   755  		useBy:              c.config.time().Add(lifetime),
   756  		ageAdd:             msg.ageAdd,
   757  	}
   758  
   759  	cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   760  	c.config.ClientSessionCache.Put(cacheKey, session)
   761  
   762  	return nil
   763  }