Source file src/crypto/tls/handshake_server_tls13.go

     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/hkdf"
    12  	"crypto/hmac"
    13  	"crypto/internal/fips140/mlkem"
    14  	"crypto/internal/fips140/tls13"
    15  	"crypto/internal/hpke"
    16  	"crypto/rsa"
    17  	"crypto/tls/internal/fips140tls"
    18  	"errors"
    19  	"fmt"
    20  	"hash"
    21  	"internal/byteorder"
    22  	"io"
    23  	"slices"
    24  	"sort"
    25  	"time"
    26  )
    27  
    28  // maxClientPSKIdentities is the number of client PSK identities the server will
    29  // attempt to validate. It will ignore the rest not to let cheap ClientHello
    30  // messages cause too much work in session ticket decryption attempts.
    31  const maxClientPSKIdentities = 5
    32  
    33  type echServerContext struct {
    34  	hpkeContext *hpke.Recipient
    35  	configID    uint8
    36  	ciphersuite echCipher
    37  	transcript  hash.Hash
    38  	// inner indicates that the initial client_hello we recieved contained an
    39  	// encrypted_client_hello extension that indicated it was an "inner" hello.
    40  	// We don't do any additional processing of the hello in this case, so all
    41  	// fields above are unset.
    42  	inner bool
    43  }
    44  
    45  type serverHandshakeStateTLS13 struct {
    46  	c               *Conn
    47  	ctx             context.Context
    48  	clientHello     *clientHelloMsg
    49  	hello           *serverHelloMsg
    50  	sentDummyCCS    bool
    51  	usingPSK        bool
    52  	earlyData       bool
    53  	suite           *cipherSuiteTLS13
    54  	cert            *Certificate
    55  	sigAlg          SignatureScheme
    56  	earlySecret     *tls13.EarlySecret
    57  	sharedKey       []byte
    58  	handshakeSecret *tls13.HandshakeSecret
    59  	masterSecret    *tls13.MasterSecret
    60  	trafficSecret   []byte // client_application_traffic_secret_0
    61  	transcript      hash.Hash
    62  	clientFinished  []byte
    63  	echContext      *echServerContext
    64  }
    65  
    66  func (hs *serverHandshakeStateTLS13) handshake() error {
    67  	c := hs.c
    68  
    69  	// For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
    70  	if err := hs.processClientHello(); err != nil {
    71  		return err
    72  	}
    73  	if err := hs.checkForResumption(); err != nil {
    74  		return err
    75  	}
    76  	if err := hs.pickCertificate(); err != nil {
    77  		return err
    78  	}
    79  	c.buffering = true
    80  	if err := hs.sendServerParameters(); err != nil {
    81  		return err
    82  	}
    83  	if err := hs.sendServerCertificate(); err != nil {
    84  		return err
    85  	}
    86  	if err := hs.sendServerFinished(); err != nil {
    87  		return err
    88  	}
    89  	// Note that at this point we could start sending application data without
    90  	// waiting for the client's second flight, but the application might not
    91  	// expect the lack of replay protection of the ClientHello parameters.
    92  	if _, err := c.flush(); err != nil {
    93  		return err
    94  	}
    95  	if err := hs.readClientCertificate(); err != nil {
    96  		return err
    97  	}
    98  	if err := hs.readClientFinished(); err != nil {
    99  		return err
   100  	}
   101  
   102  	c.isHandshakeComplete.Store(true)
   103  
   104  	return nil
   105  }
   106  
   107  func (hs *serverHandshakeStateTLS13) processClientHello() error {
   108  	c := hs.c
   109  
   110  	hs.hello = new(serverHelloMsg)
   111  
   112  	// TLS 1.3 froze the ServerHello.legacy_version field, and uses
   113  	// supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
   114  	hs.hello.vers = VersionTLS12
   115  	hs.hello.supportedVersion = c.vers
   116  
   117  	if len(hs.clientHello.supportedVersions) == 0 {
   118  		c.sendAlert(alertIllegalParameter)
   119  		return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
   120  	}
   121  
   122  	// Abort if the client is doing a fallback and landing lower than what we
   123  	// support. See RFC 7507, which however does not specify the interaction
   124  	// with supported_versions. The only difference is that with
   125  	// supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
   126  	// handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
   127  	// it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
   128  	// TLS 1.2, because a TLS 1.3 server would abort here. The situation before
   129  	// supported_versions was not better because there was just no way to do a
   130  	// TLS 1.4 handshake without risking the server selecting TLS 1.3.
   131  	for _, id := range hs.clientHello.cipherSuites {
   132  		if id == TLS_FALLBACK_SCSV {
   133  			// Use c.vers instead of max(supported_versions) because an attacker
   134  			// could defeat this by adding an arbitrary high version otherwise.
   135  			if c.vers < c.config.maxSupportedVersion(roleServer) {
   136  				c.sendAlert(alertInappropriateFallback)
   137  				return errors.New("tls: client using inappropriate protocol fallback")
   138  			}
   139  			break
   140  		}
   141  	}
   142  
   143  	if len(hs.clientHello.compressionMethods) != 1 ||
   144  		hs.clientHello.compressionMethods[0] != compressionNone {
   145  		c.sendAlert(alertIllegalParameter)
   146  		return errors.New("tls: TLS 1.3 client supports illegal compression methods")
   147  	}
   148  
   149  	hs.hello.random = make([]byte, 32)
   150  	if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
   151  		c.sendAlert(alertInternalError)
   152  		return err
   153  	}
   154  
   155  	if len(hs.clientHello.secureRenegotiation) != 0 {
   156  		c.sendAlert(alertHandshakeFailure)
   157  		return errors.New("tls: initial handshake had non-empty renegotiation extension")
   158  	}
   159  
   160  	if hs.clientHello.earlyData && c.quic != nil {
   161  		if len(hs.clientHello.pskIdentities) == 0 {
   162  			c.sendAlert(alertIllegalParameter)
   163  			return errors.New("tls: early_data without pre_shared_key")
   164  		}
   165  	} else if hs.clientHello.earlyData {
   166  		// See RFC 8446, Section 4.2.10 for the complicated behavior required
   167  		// here. The scenario is that a different server at our address offered
   168  		// to accept early data in the past, which we can't handle. For now, all
   169  		// 0-RTT enabled session tickets need to expire before a Go server can
   170  		// replace a server or join a pool. That's the same requirement that
   171  		// applies to mixing or replacing with any TLS 1.2 server.
   172  		c.sendAlert(alertUnsupportedExtension)
   173  		return errors.New("tls: client sent unexpected early data")
   174  	}
   175  
   176  	hs.hello.sessionId = hs.clientHello.sessionId
   177  	hs.hello.compressionMethod = compressionNone
   178  
   179  	preferenceList := defaultCipherSuitesTLS13
   180  	if !hasAESGCMHardwareSupport || !isAESGCMPreferred(hs.clientHello.cipherSuites) {
   181  		preferenceList = defaultCipherSuitesTLS13NoAES
   182  	}
   183  	if fips140tls.Required() {
   184  		preferenceList = allowedCipherSuitesTLS13FIPS
   185  	}
   186  	for _, suiteID := range preferenceList {
   187  		hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
   188  		if hs.suite != nil {
   189  			break
   190  		}
   191  	}
   192  	if hs.suite == nil {
   193  		c.sendAlert(alertHandshakeFailure)
   194  		return fmt.Errorf("tls: no cipher suite supported by both client and server; client offered: %x",
   195  			hs.clientHello.cipherSuites)
   196  	}
   197  	c.cipherSuite = hs.suite.id
   198  	hs.hello.cipherSuite = hs.suite.id
   199  	hs.transcript = hs.suite.hash.New()
   200  
   201  	// First, if a post-quantum key exchange is available, use one. See
   202  	// draft-ietf-tls-key-share-prediction-01, Section 4 for why this must be
   203  	// first.
   204  	//
   205  	// Second, if the client sent a key share for a group we support, use that,
   206  	// to avoid a HelloRetryRequest round-trip.
   207  	//
   208  	// Finally, pick in our fixed preference order.
   209  	preferredGroups := c.config.curvePreferences(c.vers)
   210  	preferredGroups = slices.DeleteFunc(preferredGroups, func(group CurveID) bool {
   211  		return !slices.Contains(hs.clientHello.supportedCurves, group)
   212  	})
   213  	if len(preferredGroups) == 0 {
   214  		c.sendAlert(alertHandshakeFailure)
   215  		return errors.New("tls: no key exchanges supported by both client and server")
   216  	}
   217  	hasKeyShare := func(group CurveID) bool {
   218  		for _, ks := range hs.clientHello.keyShares {
   219  			if ks.group == group {
   220  				return true
   221  			}
   222  		}
   223  		return false
   224  	}
   225  	sort.SliceStable(preferredGroups, func(i, j int) bool {
   226  		return hasKeyShare(preferredGroups[i]) && !hasKeyShare(preferredGroups[j])
   227  	})
   228  	sort.SliceStable(preferredGroups, func(i, j int) bool {
   229  		return isPQKeyExchange(preferredGroups[i]) && !isPQKeyExchange(preferredGroups[j])
   230  	})
   231  	selectedGroup := preferredGroups[0]
   232  
   233  	var clientKeyShare *keyShare
   234  	for _, ks := range hs.clientHello.keyShares {
   235  		if ks.group == selectedGroup {
   236  			clientKeyShare = &ks
   237  			break
   238  		}
   239  	}
   240  	if clientKeyShare == nil {
   241  		ks, err := hs.doHelloRetryRequest(selectedGroup)
   242  		if err != nil {
   243  			return err
   244  		}
   245  		clientKeyShare = ks
   246  	}
   247  	c.curveID = selectedGroup
   248  
   249  	ecdhGroup := selectedGroup
   250  	ecdhData := clientKeyShare.data
   251  	if selectedGroup == X25519MLKEM768 {
   252  		ecdhGroup = X25519
   253  		if len(ecdhData) != mlkem.EncapsulationKeySize768+x25519PublicKeySize {
   254  			c.sendAlert(alertIllegalParameter)
   255  			return errors.New("tls: invalid X25519MLKEM768 client key share")
   256  		}
   257  		ecdhData = ecdhData[mlkem.EncapsulationKeySize768:]
   258  	}
   259  	if _, ok := curveForCurveID(ecdhGroup); !ok {
   260  		c.sendAlert(alertInternalError)
   261  		return errors.New("tls: CurvePreferences includes unsupported curve")
   262  	}
   263  	key, err := generateECDHEKey(c.config.rand(), ecdhGroup)
   264  	if err != nil {
   265  		c.sendAlert(alertInternalError)
   266  		return err
   267  	}
   268  	hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()}
   269  	peerKey, err := key.Curve().NewPublicKey(ecdhData)
   270  	if err != nil {
   271  		c.sendAlert(alertIllegalParameter)
   272  		return errors.New("tls: invalid client key share")
   273  	}
   274  	hs.sharedKey, err = key.ECDH(peerKey)
   275  	if err != nil {
   276  		c.sendAlert(alertIllegalParameter)
   277  		return errors.New("tls: invalid client key share")
   278  	}
   279  	if selectedGroup == X25519MLKEM768 {
   280  		k, err := mlkem.NewEncapsulationKey768(clientKeyShare.data[:mlkem.EncapsulationKeySize768])
   281  		if err != nil {
   282  			c.sendAlert(alertIllegalParameter)
   283  			return errors.New("tls: invalid X25519MLKEM768 client key share")
   284  		}
   285  		mlkemSharedSecret, ciphertext := k.Encapsulate()
   286  		// draft-kwiatkowski-tls-ecdhe-mlkem-02, Section 3.1.3: "For
   287  		// X25519MLKEM768, the shared secret is the concatenation of the ML-KEM
   288  		// shared secret and the X25519 shared secret. The shared secret is 64
   289  		// bytes (32 bytes for each part)."
   290  		hs.sharedKey = append(mlkemSharedSecret, hs.sharedKey...)
   291  		// draft-kwiatkowski-tls-ecdhe-mlkem-02, Section 3.1.2: "When the
   292  		// X25519MLKEM768 group is negotiated, the server's key exchange value
   293  		// is the concatenation of an ML-KEM ciphertext returned from
   294  		// encapsulation to the client's encapsulation key, and the server's
   295  		// ephemeral X25519 share."
   296  		hs.hello.serverShare.data = append(ciphertext, hs.hello.serverShare.data...)
   297  	}
   298  
   299  	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
   300  	if err != nil {
   301  		c.sendAlert(alertNoApplicationProtocol)
   302  		return err
   303  	}
   304  	c.clientProtocol = selectedProto
   305  
   306  	if c.quic != nil {
   307  		// RFC 9001 Section 4.2: Clients MUST NOT offer TLS versions older than 1.3.
   308  		for _, v := range hs.clientHello.supportedVersions {
   309  			if v < VersionTLS13 {
   310  				c.sendAlert(alertProtocolVersion)
   311  				return errors.New("tls: client offered TLS version older than TLS 1.3")
   312  			}
   313  		}
   314  		// RFC 9001 Section 8.2.
   315  		if hs.clientHello.quicTransportParameters == nil {
   316  			c.sendAlert(alertMissingExtension)
   317  			return errors.New("tls: client did not send a quic_transport_parameters extension")
   318  		}
   319  		c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
   320  	} else {
   321  		if hs.clientHello.quicTransportParameters != nil {
   322  			c.sendAlert(alertUnsupportedExtension)
   323  			return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
   324  		}
   325  	}
   326  
   327  	c.serverName = hs.clientHello.serverName
   328  	return nil
   329  }
   330  
   331  func (hs *serverHandshakeStateTLS13) checkForResumption() error {
   332  	c := hs.c
   333  
   334  	if c.config.SessionTicketsDisabled {
   335  		return nil
   336  	}
   337  
   338  	modeOK := false
   339  	for _, mode := range hs.clientHello.pskModes {
   340  		if mode == pskModeDHE {
   341  			modeOK = true
   342  			break
   343  		}
   344  	}
   345  	if !modeOK {
   346  		return nil
   347  	}
   348  
   349  	if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
   350  		c.sendAlert(alertIllegalParameter)
   351  		return errors.New("tls: invalid or missing PSK binders")
   352  	}
   353  	if len(hs.clientHello.pskIdentities) == 0 {
   354  		return nil
   355  	}
   356  
   357  	for i, identity := range hs.clientHello.pskIdentities {
   358  		if i >= maxClientPSKIdentities {
   359  			break
   360  		}
   361  
   362  		var sessionState *SessionState
   363  		if c.config.UnwrapSession != nil {
   364  			var err error
   365  			sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
   366  			if err != nil {
   367  				return err
   368  			}
   369  			if sessionState == nil {
   370  				continue
   371  			}
   372  		} else {
   373  			plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
   374  			if plaintext == nil {
   375  				continue
   376  			}
   377  			var err error
   378  			sessionState, err = ParseSessionState(plaintext)
   379  			if err != nil {
   380  				continue
   381  			}
   382  		}
   383  
   384  		if sessionState.version != VersionTLS13 {
   385  			continue
   386  		}
   387  
   388  		createdAt := time.Unix(int64(sessionState.createdAt), 0)
   389  		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   390  			continue
   391  		}
   392  
   393  		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
   394  		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
   395  			continue
   396  		}
   397  
   398  		// PSK connections don't re-establish client certificates, but carry
   399  		// them over in the session ticket. Ensure the presence of client certs
   400  		// in the ticket is consistent with the configured requirements.
   401  		sessionHasClientCerts := len(sessionState.peerCertificates) != 0
   402  		needClientCerts := requiresClientCert(c.config.ClientAuth)
   403  		if needClientCerts && !sessionHasClientCerts {
   404  			continue
   405  		}
   406  		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   407  			continue
   408  		}
   409  		if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
   410  			continue
   411  		}
   412  		if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
   413  			len(sessionState.verifiedChains) == 0 {
   414  			continue
   415  		}
   416  
   417  		if c.quic != nil && c.quic.enableSessionEvents {
   418  			if err := c.quicResumeSession(sessionState); err != nil {
   419  				return err
   420  			}
   421  		}
   422  
   423  		hs.earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, sessionState.secret)
   424  		binderKey := hs.earlySecret.ResumptionBinderKey()
   425  		// Clone the transcript in case a HelloRetryRequest was recorded.
   426  		transcript := cloneHash(hs.transcript, hs.suite.hash)
   427  		if transcript == nil {
   428  			c.sendAlert(alertInternalError)
   429  			return errors.New("tls: internal error: failed to clone hash")
   430  		}
   431  		clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
   432  		if err != nil {
   433  			c.sendAlert(alertInternalError)
   434  			return err
   435  		}
   436  		transcript.Write(clientHelloBytes)
   437  		pskBinder := hs.suite.finishedHash(binderKey, transcript)
   438  		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
   439  			c.sendAlert(alertDecryptError)
   440  			return errors.New("tls: invalid PSK binder")
   441  		}
   442  
   443  		if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
   444  			sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
   445  			sessionState.alpnProtocol == c.clientProtocol {
   446  			hs.earlyData = true
   447  
   448  			transcript := hs.suite.hash.New()
   449  			if err := transcriptMsg(hs.clientHello, transcript); err != nil {
   450  				return err
   451  			}
   452  			earlyTrafficSecret := hs.earlySecret.ClientEarlyTrafficSecret(transcript)
   453  			c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
   454  		}
   455  
   456  		c.didResume = true
   457  		c.peerCertificates = sessionState.peerCertificates
   458  		c.ocspResponse = sessionState.ocspResponse
   459  		c.scts = sessionState.scts
   460  		c.verifiedChains = sessionState.verifiedChains
   461  
   462  		hs.hello.selectedIdentityPresent = true
   463  		hs.hello.selectedIdentity = uint16(i)
   464  		hs.usingPSK = true
   465  		return nil
   466  	}
   467  
   468  	return nil
   469  }
   470  
   471  // cloneHash uses [hash.Cloner] to clone in. If [hash.Cloner]
   472  // is not implemented or not supported, then it falls back to the
   473  // [encoding.BinaryMarshaler] and [encoding.BinaryUnmarshaler]
   474  // interfaces implemented by standard library hashes to clone the state of in
   475  // to a new instance of h. It returns nil if the operation fails.
   476  func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
   477  	if cloner, ok := in.(hash.Cloner); ok {
   478  		if out, err := cloner.Clone(); err == nil {
   479  			return out
   480  		}
   481  	}
   482  	// Recreate the interface to avoid importing encoding.
   483  	type binaryMarshaler interface {
   484  		MarshalBinary() (data []byte, err error)
   485  		UnmarshalBinary(data []byte) error
   486  	}
   487  	marshaler, ok := in.(binaryMarshaler)
   488  	if !ok {
   489  		return nil
   490  	}
   491  	state, err := marshaler.MarshalBinary()
   492  	if err != nil {
   493  		return nil
   494  	}
   495  	out := h.New()
   496  	unmarshaler, ok := out.(binaryMarshaler)
   497  	if !ok {
   498  		return nil
   499  	}
   500  	if err := unmarshaler.UnmarshalBinary(state); err != nil {
   501  		return nil
   502  	}
   503  	return out
   504  }
   505  
   506  func (hs *serverHandshakeStateTLS13) pickCertificate() error {
   507  	c := hs.c
   508  
   509  	// Only one of PSK and certificates are used at a time.
   510  	if hs.usingPSK {
   511  		return nil
   512  	}
   513  
   514  	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
   515  	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
   516  		return c.sendAlert(alertMissingExtension)
   517  	}
   518  
   519  	certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
   520  	if err != nil {
   521  		if err == errNoCertificates {
   522  			c.sendAlert(alertUnrecognizedName)
   523  		} else {
   524  			c.sendAlert(alertInternalError)
   525  		}
   526  		return err
   527  	}
   528  	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
   529  	if err != nil {
   530  		// getCertificate returned a certificate that is unsupported or
   531  		// incompatible with the client's signature algorithms.
   532  		c.sendAlert(alertHandshakeFailure)
   533  		return err
   534  	}
   535  	hs.cert = certificate
   536  
   537  	return nil
   538  }
   539  
   540  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   541  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   542  func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   543  	if hs.c.quic != nil {
   544  		return nil
   545  	}
   546  	if hs.sentDummyCCS {
   547  		return nil
   548  	}
   549  	hs.sentDummyCCS = true
   550  
   551  	return hs.c.writeChangeCipherRecord()
   552  }
   553  
   554  func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error) {
   555  	c := hs.c
   556  
   557  	// The first ClientHello gets double-hashed into the transcript upon a
   558  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   559  	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
   560  		return nil, err
   561  	}
   562  	chHash := hs.transcript.Sum(nil)
   563  	hs.transcript.Reset()
   564  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   565  	hs.transcript.Write(chHash)
   566  
   567  	helloRetryRequest := &serverHelloMsg{
   568  		vers:              hs.hello.vers,
   569  		random:            helloRetryRequestRandom,
   570  		sessionId:         hs.hello.sessionId,
   571  		cipherSuite:       hs.hello.cipherSuite,
   572  		compressionMethod: hs.hello.compressionMethod,
   573  		supportedVersion:  hs.hello.supportedVersion,
   574  		selectedGroup:     selectedGroup,
   575  	}
   576  
   577  	if hs.echContext != nil {
   578  		// Compute the acceptance message.
   579  		helloRetryRequest.encryptedClientHello = make([]byte, 8)
   580  		confTranscript := cloneHash(hs.transcript, hs.suite.hash)
   581  		if err := transcriptMsg(helloRetryRequest, confTranscript); err != nil {
   582  			return nil, err
   583  		}
   584  		h := hs.suite.hash.New
   585  		prf, err := hkdf.Extract(h, hs.clientHello.random, nil)
   586  		if err != nil {
   587  			c.sendAlert(alertInternalError)
   588  			return nil, err
   589  		}
   590  		acceptConfirmation := tls13.ExpandLabel(h, prf, "hrr ech accept confirmation", confTranscript.Sum(nil), 8)
   591  		helloRetryRequest.encryptedClientHello = acceptConfirmation
   592  	}
   593  
   594  	if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
   595  		return nil, err
   596  	}
   597  
   598  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   599  		return nil, err
   600  	}
   601  
   602  	// clientHelloMsg is not included in the transcript.
   603  	msg, err := c.readHandshake(nil)
   604  	if err != nil {
   605  		return nil, err
   606  	}
   607  
   608  	clientHello, ok := msg.(*clientHelloMsg)
   609  	if !ok {
   610  		c.sendAlert(alertUnexpectedMessage)
   611  		return nil, unexpectedMessageError(clientHello, msg)
   612  	}
   613  
   614  	if hs.echContext != nil {
   615  		if len(clientHello.encryptedClientHello) == 0 {
   616  			c.sendAlert(alertMissingExtension)
   617  			return nil, errors.New("tls: second client hello missing encrypted client hello extension")
   618  		}
   619  
   620  		echType, echCiphersuite, configID, encap, payload, err := parseECHExt(clientHello.encryptedClientHello)
   621  		if err != nil {
   622  			c.sendAlert(alertDecodeError)
   623  			return nil, errors.New("tls: client sent invalid encrypted client hello extension")
   624  		}
   625  
   626  		if echType == outerECHExt && hs.echContext.inner || echType == innerECHExt && !hs.echContext.inner {
   627  			c.sendAlert(alertDecodeError)
   628  			return nil, errors.New("tls: unexpected switch in encrypted client hello extension type")
   629  		}
   630  
   631  		if echType == outerECHExt {
   632  			if echCiphersuite != hs.echContext.ciphersuite || configID != hs.echContext.configID || len(encap) != 0 {
   633  				c.sendAlert(alertIllegalParameter)
   634  				return nil, errors.New("tls: second client hello encrypted client hello extension does not match")
   635  			}
   636  
   637  			encodedInner, err := decryptECHPayload(hs.echContext.hpkeContext, clientHello.original, payload)
   638  			if err != nil {
   639  				c.sendAlert(alertDecryptError)
   640  				return nil, errors.New("tls: failed to decrypt second client hello encrypted client hello extension payload")
   641  			}
   642  
   643  			echInner, err := decodeInnerClientHello(clientHello, encodedInner)
   644  			if err != nil {
   645  				c.sendAlert(alertIllegalParameter)
   646  				return nil, errors.New("tls: client sent invalid encrypted client hello extension")
   647  			}
   648  
   649  			clientHello = echInner
   650  		}
   651  	}
   652  
   653  	if len(clientHello.keyShares) != 1 {
   654  		c.sendAlert(alertIllegalParameter)
   655  		return nil, errors.New("tls: client didn't send one key share in second ClientHello")
   656  	}
   657  	ks := &clientHello.keyShares[0]
   658  
   659  	if ks.group != selectedGroup {
   660  		c.sendAlert(alertIllegalParameter)
   661  		return nil, errors.New("tls: client sent unexpected key share in second ClientHello")
   662  	}
   663  
   664  	if clientHello.earlyData {
   665  		c.sendAlert(alertIllegalParameter)
   666  		return nil, errors.New("tls: client indicated early data in second ClientHello")
   667  	}
   668  
   669  	if illegalClientHelloChange(clientHello, hs.clientHello) {
   670  		c.sendAlert(alertIllegalParameter)
   671  		return nil, errors.New("tls: client illegally modified second ClientHello")
   672  	}
   673  
   674  	c.didHRR = true
   675  	hs.clientHello = clientHello
   676  	return ks, nil
   677  }
   678  
   679  // illegalClientHelloChange reports whether the two ClientHello messages are
   680  // different, with the exception of the changes allowed before and after a
   681  // HelloRetryRequest. See RFC 8446, Section 4.1.2.
   682  func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
   683  	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
   684  		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
   685  		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
   686  		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
   687  		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
   688  		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
   689  		return true
   690  	}
   691  	for i := range ch.supportedVersions {
   692  		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
   693  			return true
   694  		}
   695  	}
   696  	for i := range ch.cipherSuites {
   697  		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
   698  			return true
   699  		}
   700  	}
   701  	for i := range ch.supportedCurves {
   702  		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
   703  			return true
   704  		}
   705  	}
   706  	for i := range ch.supportedSignatureAlgorithms {
   707  		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
   708  			return true
   709  		}
   710  	}
   711  	for i := range ch.supportedSignatureAlgorithmsCert {
   712  		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
   713  			return true
   714  		}
   715  	}
   716  	for i := range ch.alpnProtocols {
   717  		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
   718  			return true
   719  		}
   720  	}
   721  	return ch.vers != ch1.vers ||
   722  		!bytes.Equal(ch.random, ch1.random) ||
   723  		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
   724  		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
   725  		ch.serverName != ch1.serverName ||
   726  		ch.ocspStapling != ch1.ocspStapling ||
   727  		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
   728  		ch.ticketSupported != ch1.ticketSupported ||
   729  		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
   730  		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
   731  		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
   732  		ch.scts != ch1.scts ||
   733  		!bytes.Equal(ch.cookie, ch1.cookie) ||
   734  		!bytes.Equal(ch.pskModes, ch1.pskModes)
   735  }
   736  
   737  func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
   738  	c := hs.c
   739  
   740  	if hs.echContext != nil {
   741  		copy(hs.hello.random[32-8:], make([]byte, 8))
   742  		echTranscript := cloneHash(hs.transcript, hs.suite.hash)
   743  		echTranscript.Write(hs.clientHello.original)
   744  		if err := transcriptMsg(hs.hello, echTranscript); err != nil {
   745  			return err
   746  		}
   747  		// compute the acceptance message
   748  		h := hs.suite.hash.New
   749  		prk, err := hkdf.Extract(h, hs.clientHello.random, nil)
   750  		if err != nil {
   751  			c.sendAlert(alertInternalError)
   752  			return err
   753  		}
   754  		acceptConfirmation := tls13.ExpandLabel(h, prk, "ech accept confirmation", echTranscript.Sum(nil), 8)
   755  		copy(hs.hello.random[32-8:], acceptConfirmation)
   756  	}
   757  
   758  	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
   759  		return err
   760  	}
   761  
   762  	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
   763  		return err
   764  	}
   765  
   766  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   767  		return err
   768  	}
   769  
   770  	earlySecret := hs.earlySecret
   771  	if earlySecret == nil {
   772  		earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
   773  	}
   774  	hs.handshakeSecret = earlySecret.HandshakeSecret(hs.sharedKey)
   775  
   776  	clientSecret := hs.handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
   777  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
   778  	serverSecret := hs.handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
   779  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
   780  
   781  	if c.quic != nil {
   782  		if c.hand.Len() != 0 {
   783  			c.sendAlert(alertUnexpectedMessage)
   784  		}
   785  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
   786  		c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
   787  	}
   788  
   789  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
   790  	if err != nil {
   791  		c.sendAlert(alertInternalError)
   792  		return err
   793  	}
   794  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
   795  	if err != nil {
   796  		c.sendAlert(alertInternalError)
   797  		return err
   798  	}
   799  
   800  	encryptedExtensions := new(encryptedExtensionsMsg)
   801  	encryptedExtensions.alpnProtocol = c.clientProtocol
   802  
   803  	if c.quic != nil {
   804  		p, err := c.quicGetTransportParameters()
   805  		if err != nil {
   806  			return err
   807  		}
   808  		encryptedExtensions.quicTransportParameters = p
   809  		encryptedExtensions.earlyData = hs.earlyData
   810  	}
   811  
   812  	if !hs.c.didResume && hs.clientHello.serverName != "" {
   813  		encryptedExtensions.serverNameAck = true
   814  	}
   815  
   816  	// If client sent ECH extension, but we didn't accept it,
   817  	// send retry configs, if available.
   818  	echKeys := hs.c.config.EncryptedClientHelloKeys
   819  	if hs.c.config.GetEncryptedClientHelloKeys != nil {
   820  		echKeys, err = hs.c.config.GetEncryptedClientHelloKeys(clientHelloInfo(hs.ctx, c, hs.clientHello))
   821  		if err != nil {
   822  			c.sendAlert(alertInternalError)
   823  			return err
   824  		}
   825  	}
   826  	if len(echKeys) > 0 && len(hs.clientHello.encryptedClientHello) > 0 && hs.echContext == nil {
   827  		encryptedExtensions.echRetryConfigs, err = buildRetryConfigList(echKeys)
   828  		if err != nil {
   829  			c.sendAlert(alertInternalError)
   830  			return err
   831  		}
   832  	}
   833  
   834  	if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
   835  		return err
   836  	}
   837  
   838  	return nil
   839  }
   840  
   841  func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
   842  	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
   843  }
   844  
   845  func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
   846  	c := hs.c
   847  
   848  	// Only one of PSK and certificates are used at a time.
   849  	if hs.usingPSK {
   850  		return nil
   851  	}
   852  
   853  	if hs.requestClientCert() {
   854  		// Request a client certificate
   855  		certReq := new(certificateRequestMsgTLS13)
   856  		certReq.ocspStapling = true
   857  		certReq.scts = true
   858  		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms(c.vers)
   859  		certReq.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert()
   860  		if c.config.ClientCAs != nil {
   861  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   862  		}
   863  
   864  		if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
   865  			return err
   866  		}
   867  	}
   868  
   869  	certMsg := new(certificateMsgTLS13)
   870  
   871  	certMsg.certificate = *hs.cert
   872  	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
   873  	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
   874  
   875  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
   876  		return err
   877  	}
   878  
   879  	certVerifyMsg := new(certificateVerifyMsg)
   880  	certVerifyMsg.hasSignatureAlgorithm = true
   881  	certVerifyMsg.signatureAlgorithm = hs.sigAlg
   882  
   883  	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
   884  	if err != nil {
   885  		return c.sendAlert(alertInternalError)
   886  	}
   887  
   888  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   889  	signOpts := crypto.SignerOpts(sigHash)
   890  	if sigType == signatureRSAPSS {
   891  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   892  	}
   893  	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   894  	if err != nil {
   895  		public := hs.cert.PrivateKey.(crypto.Signer).Public()
   896  		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
   897  			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
   898  			c.sendAlert(alertHandshakeFailure)
   899  		} else {
   900  			c.sendAlert(alertInternalError)
   901  		}
   902  		return errors.New("tls: failed to sign handshake: " + err.Error())
   903  	}
   904  	certVerifyMsg.signature = sig
   905  
   906  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
   907  		return err
   908  	}
   909  
   910  	return nil
   911  }
   912  
   913  func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
   914  	c := hs.c
   915  
   916  	finished := &finishedMsg{
   917  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   918  	}
   919  
   920  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
   921  		return err
   922  	}
   923  
   924  	// Derive secrets that take context through the server Finished.
   925  
   926  	hs.masterSecret = hs.handshakeSecret.MasterSecret()
   927  
   928  	hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
   929  	serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
   930  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
   931  
   932  	if c.quic != nil {
   933  		if c.hand.Len() != 0 {
   934  			// TODO: Handle this in setTrafficSecret?
   935  			c.sendAlert(alertUnexpectedMessage)
   936  		}
   937  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
   938  	}
   939  
   940  	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
   941  	if err != nil {
   942  		c.sendAlert(alertInternalError)
   943  		return err
   944  	}
   945  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
   946  	if err != nil {
   947  		c.sendAlert(alertInternalError)
   948  		return err
   949  	}
   950  
   951  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   952  
   953  	// If we did not request client certificates, at this point we can
   954  	// precompute the client finished and roll the transcript forward to send
   955  	// session tickets in our first flight.
   956  	if !hs.requestClientCert() {
   957  		if err := hs.sendSessionTickets(); err != nil {
   958  			return err
   959  		}
   960  	}
   961  
   962  	return nil
   963  }
   964  
   965  func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
   966  	if hs.c.config.SessionTicketsDisabled {
   967  		return false
   968  	}
   969  
   970  	// QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically.
   971  	if hs.c.quic != nil {
   972  		return false
   973  	}
   974  
   975  	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
   976  	return slices.Contains(hs.clientHello.pskModes, pskModeDHE)
   977  }
   978  
   979  func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
   980  	c := hs.c
   981  
   982  	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   983  	finishedMsg := &finishedMsg{
   984  		verifyData: hs.clientFinished,
   985  	}
   986  	if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
   987  		return err
   988  	}
   989  
   990  	c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
   991  
   992  	if !hs.shouldSendSessionTickets() {
   993  		return nil
   994  	}
   995  	return c.sendSessionTicket(false, nil)
   996  }
   997  
   998  func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error {
   999  	suite := cipherSuiteTLS13ByID(c.cipherSuite)
  1000  	if suite == nil {
  1001  		return errors.New("tls: internal error: unknown cipher suite")
  1002  	}
  1003  	// ticket_nonce, which must be unique per connection, is always left at
  1004  	// zero because we only ever send one ticket per connection.
  1005  	psk := tls13.ExpandLabel(suite.hash.New, c.resumptionSecret, "resumption",
  1006  		nil, suite.hash.Size())
  1007  
  1008  	m := new(newSessionTicketMsgTLS13)
  1009  
  1010  	state := c.sessionState()
  1011  	state.secret = psk
  1012  	state.EarlyData = earlyData
  1013  	state.Extra = extra
  1014  	if c.config.WrapSession != nil {
  1015  		var err error
  1016  		m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
  1017  		if err != nil {
  1018  			return err
  1019  		}
  1020  	} else {
  1021  		stateBytes, err := state.Bytes()
  1022  		if err != nil {
  1023  			c.sendAlert(alertInternalError)
  1024  			return err
  1025  		}
  1026  		m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
  1027  		if err != nil {
  1028  			return err
  1029  		}
  1030  	}
  1031  	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
  1032  
  1033  	// ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1
  1034  	// The value is not stored anywhere; we never need to check the ticket age
  1035  	// because 0-RTT is not supported.
  1036  	ageAdd := make([]byte, 4)
  1037  	if _, err := c.config.rand().Read(ageAdd); err != nil {
  1038  		return err
  1039  	}
  1040  	m.ageAdd = byteorder.LEUint32(ageAdd)
  1041  
  1042  	if earlyData {
  1043  		// RFC 9001, Section 4.6.1
  1044  		m.maxEarlyData = 0xffffffff
  1045  	}
  1046  
  1047  	if _, err := c.writeHandshakeRecord(m, nil); err != nil {
  1048  		return err
  1049  	}
  1050  
  1051  	return nil
  1052  }
  1053  
  1054  func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
  1055  	c := hs.c
  1056  
  1057  	if !hs.requestClientCert() {
  1058  		// Make sure the connection is still being verified whether or not
  1059  		// the server requested a client certificate.
  1060  		if c.config.VerifyConnection != nil {
  1061  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1062  				c.sendAlert(alertBadCertificate)
  1063  				return err
  1064  			}
  1065  		}
  1066  		return nil
  1067  	}
  1068  
  1069  	// If we requested a client certificate, then the client must send a
  1070  	// certificate message. If it's empty, no CertificateVerify is sent.
  1071  
  1072  	msg, err := c.readHandshake(hs.transcript)
  1073  	if err != nil {
  1074  		return err
  1075  	}
  1076  
  1077  	certMsg, ok := msg.(*certificateMsgTLS13)
  1078  	if !ok {
  1079  		c.sendAlert(alertUnexpectedMessage)
  1080  		return unexpectedMessageError(certMsg, msg)
  1081  	}
  1082  
  1083  	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
  1084  		return err
  1085  	}
  1086  
  1087  	if c.config.VerifyConnection != nil {
  1088  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1089  			c.sendAlert(alertBadCertificate)
  1090  			return err
  1091  		}
  1092  	}
  1093  
  1094  	if len(certMsg.certificate.Certificate) != 0 {
  1095  		// certificateVerifyMsg is included in the transcript, but not until
  1096  		// after we verify the handshake signature, since the state before
  1097  		// this message was sent is used.
  1098  		msg, err = c.readHandshake(nil)
  1099  		if err != nil {
  1100  			return err
  1101  		}
  1102  
  1103  		certVerify, ok := msg.(*certificateVerifyMsg)
  1104  		if !ok {
  1105  			c.sendAlert(alertUnexpectedMessage)
  1106  			return unexpectedMessageError(certVerify, msg)
  1107  		}
  1108  
  1109  		// See RFC 8446, Section 4.4.3.
  1110  		// We don't use certReq.supportedSignatureAlgorithms because it would
  1111  		// require keeping the certificateRequestMsgTLS13 around in the hs.
  1112  		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers)) ||
  1113  			!isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, signatureSchemesForPublicKey(c.vers, c.peerCertificates[0].PublicKey)) {
  1114  			c.sendAlert(alertIllegalParameter)
  1115  			return errors.New("tls: client certificate used with invalid signature algorithm")
  1116  		}
  1117  		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  1118  		if err != nil {
  1119  			return c.sendAlert(alertInternalError)
  1120  		}
  1121  		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
  1122  			return c.sendAlert(alertInternalError)
  1123  		}
  1124  		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
  1125  		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
  1126  			sigHash, signed, certVerify.signature); err != nil {
  1127  			c.sendAlert(alertDecryptError)
  1128  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
  1129  		}
  1130  		c.peerSigAlg = certVerify.signatureAlgorithm
  1131  
  1132  		if err := transcriptMsg(certVerify, hs.transcript); err != nil {
  1133  			return err
  1134  		}
  1135  	}
  1136  
  1137  	// If we waited until the client certificates to send session tickets, we
  1138  	// are ready to do it now.
  1139  	if err := hs.sendSessionTickets(); err != nil {
  1140  		return err
  1141  	}
  1142  
  1143  	return nil
  1144  }
  1145  
  1146  func (hs *serverHandshakeStateTLS13) readClientFinished() error {
  1147  	c := hs.c
  1148  
  1149  	// finishedMsg is not included in the transcript.
  1150  	msg, err := c.readHandshake(nil)
  1151  	if err != nil {
  1152  		return err
  1153  	}
  1154  
  1155  	finished, ok := msg.(*finishedMsg)
  1156  	if !ok {
  1157  		c.sendAlert(alertUnexpectedMessage)
  1158  		return unexpectedMessageError(finished, msg)
  1159  	}
  1160  
  1161  	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
  1162  		c.sendAlert(alertDecryptError)
  1163  		return errors.New("tls: invalid client finished hash")
  1164  	}
  1165  
  1166  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
  1167  
  1168  	return nil
  1169  }
  1170  

View as plain text