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  pskIdentityLoop:
   358  	for i, identity := range hs.clientHello.pskIdentities {
   359  		if i >= maxClientPSKIdentities {
   360  			break
   361  		}
   362  
   363  		var sessionState *SessionState
   364  		if c.config.UnwrapSession != nil {
   365  			var err error
   366  			sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
   367  			if err != nil {
   368  				return err
   369  			}
   370  			if sessionState == nil {
   371  				continue
   372  			}
   373  		} else {
   374  			plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
   375  			if plaintext == nil {
   376  				continue
   377  			}
   378  			var err error
   379  			sessionState, err = ParseSessionState(plaintext)
   380  			if err != nil {
   381  				continue
   382  			}
   383  		}
   384  
   385  		if sessionState.version != VersionTLS13 {
   386  			continue
   387  		}
   388  
   389  		createdAt := time.Unix(int64(sessionState.createdAt), 0)
   390  		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   391  			continue
   392  		}
   393  
   394  		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
   395  		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
   396  			continue
   397  		}
   398  
   399  		// PSK connections don't re-establish client certificates, but carry
   400  		// them over in the session ticket. Ensure the presence of client certs
   401  		// in the ticket is consistent with the configured requirements.
   402  		sessionHasClientCerts := len(sessionState.peerCertificates) != 0
   403  		needClientCerts := requiresClientCert(c.config.ClientAuth)
   404  		if needClientCerts && !sessionHasClientCerts {
   405  			continue
   406  		}
   407  		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   408  			continue
   409  		}
   410  		if sessionHasClientCerts {
   411  			now := c.config.time()
   412  			for _, c := range sessionState.peerCertificates {
   413  				if now.After(c.NotAfter) {
   414  					continue pskIdentityLoop
   415  				}
   416  			}
   417  		}
   418  		if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
   419  			len(sessionState.verifiedChains) == 0 {
   420  			continue
   421  		}
   422  
   423  		if c.quic != nil && c.quic.enableSessionEvents {
   424  			if err := c.quicResumeSession(sessionState); err != nil {
   425  				return err
   426  			}
   427  		}
   428  
   429  		hs.earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, sessionState.secret)
   430  		binderKey := hs.earlySecret.ResumptionBinderKey()
   431  		// Clone the transcript in case a HelloRetryRequest was recorded.
   432  		transcript := cloneHash(hs.transcript, hs.suite.hash)
   433  		if transcript == nil {
   434  			c.sendAlert(alertInternalError)
   435  			return errors.New("tls: internal error: failed to clone hash")
   436  		}
   437  		clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
   438  		if err != nil {
   439  			c.sendAlert(alertInternalError)
   440  			return err
   441  		}
   442  		transcript.Write(clientHelloBytes)
   443  		pskBinder := hs.suite.finishedHash(binderKey, transcript)
   444  		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
   445  			c.sendAlert(alertDecryptError)
   446  			return errors.New("tls: invalid PSK binder")
   447  		}
   448  
   449  		if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
   450  			sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
   451  			sessionState.alpnProtocol == c.clientProtocol {
   452  			hs.earlyData = true
   453  
   454  			transcript := hs.suite.hash.New()
   455  			if err := transcriptMsg(hs.clientHello, transcript); err != nil {
   456  				return err
   457  			}
   458  			earlyTrafficSecret := hs.earlySecret.ClientEarlyTrafficSecret(transcript)
   459  			if err := c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret); err != nil {
   460  				return err
   461  			}
   462  		}
   463  
   464  		c.didResume = true
   465  		c.peerCertificates = sessionState.peerCertificates
   466  		c.ocspResponse = sessionState.ocspResponse
   467  		c.scts = sessionState.scts
   468  		c.verifiedChains = sessionState.verifiedChains
   469  
   470  		hs.hello.selectedIdentityPresent = true
   471  		hs.hello.selectedIdentity = uint16(i)
   472  		hs.usingPSK = true
   473  		return nil
   474  	}
   475  
   476  	return nil
   477  }
   478  
   479  // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
   480  // interfaces implemented by standard library hashes to clone the state of in
   481  // to a new instance of h. It returns nil if the operation fails.
   482  func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
   483  	// Recreate the interface to avoid importing encoding.
   484  	type binaryMarshaler interface {
   485  		MarshalBinary() (data []byte, err error)
   486  		UnmarshalBinary(data []byte) error
   487  	}
   488  	marshaler, ok := in.(binaryMarshaler)
   489  	if !ok {
   490  		return nil
   491  	}
   492  	state, err := marshaler.MarshalBinary()
   493  	if err != nil {
   494  		return nil
   495  	}
   496  	out := h.New()
   497  	unmarshaler, ok := out.(binaryMarshaler)
   498  	if !ok {
   499  		return nil
   500  	}
   501  	if err := unmarshaler.UnmarshalBinary(state); err != nil {
   502  		return nil
   503  	}
   504  	return out
   505  }
   506  
   507  func (hs *serverHandshakeStateTLS13) pickCertificate() error {
   508  	c := hs.c
   509  
   510  	// Only one of PSK and certificates are used at a time.
   511  	if hs.usingPSK {
   512  		return nil
   513  	}
   514  
   515  	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
   516  	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
   517  		return c.sendAlert(alertMissingExtension)
   518  	}
   519  
   520  	certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
   521  	if err != nil {
   522  		if err == errNoCertificates {
   523  			c.sendAlert(alertUnrecognizedName)
   524  		} else {
   525  			c.sendAlert(alertInternalError)
   526  		}
   527  		return err
   528  	}
   529  	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
   530  	if err != nil {
   531  		// getCertificate returned a certificate that is unsupported or
   532  		// incompatible with the client's signature algorithms.
   533  		c.sendAlert(alertHandshakeFailure)
   534  		return err
   535  	}
   536  	hs.cert = certificate
   537  
   538  	return nil
   539  }
   540  
   541  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   542  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   543  func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   544  	if hs.c.quic != nil {
   545  		return nil
   546  	}
   547  	if hs.sentDummyCCS {
   548  		return nil
   549  	}
   550  	hs.sentDummyCCS = true
   551  
   552  	return hs.c.writeChangeCipherRecord()
   553  }
   554  
   555  func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error) {
   556  	c := hs.c
   557  
   558  	// Make sure the client didn't send extra handshake messages alongside
   559  	// their initial client_hello. If they sent two client_hello messages,
   560  	// we will consume the second before they respond to the server_hello.
   561  	if c.hand.Len() != 0 {
   562  		c.sendAlert(alertUnexpectedMessage)
   563  		return nil, errors.New("tls: handshake buffer not empty before HelloRetryRequest")
   564  	}
   565  
   566  	// The first ClientHello gets double-hashed into the transcript upon a
   567  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   568  	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
   569  		return nil, err
   570  	}
   571  	chHash := hs.transcript.Sum(nil)
   572  	hs.transcript.Reset()
   573  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   574  	hs.transcript.Write(chHash)
   575  
   576  	helloRetryRequest := &serverHelloMsg{
   577  		vers:              hs.hello.vers,
   578  		random:            helloRetryRequestRandom,
   579  		sessionId:         hs.hello.sessionId,
   580  		cipherSuite:       hs.hello.cipherSuite,
   581  		compressionMethod: hs.hello.compressionMethod,
   582  		supportedVersion:  hs.hello.supportedVersion,
   583  		selectedGroup:     selectedGroup,
   584  	}
   585  
   586  	if hs.echContext != nil {
   587  		// Compute the acceptance message.
   588  		helloRetryRequest.encryptedClientHello = make([]byte, 8)
   589  		confTranscript := cloneHash(hs.transcript, hs.suite.hash)
   590  		if err := transcriptMsg(helloRetryRequest, confTranscript); err != nil {
   591  			return nil, err
   592  		}
   593  		h := hs.suite.hash.New
   594  		prf, err := hkdf.Extract(h, hs.clientHello.random, nil)
   595  		if err != nil {
   596  			c.sendAlert(alertInternalError)
   597  			return nil, err
   598  		}
   599  		acceptConfirmation := tls13.ExpandLabel(h, prf, "hrr ech accept confirmation", confTranscript.Sum(nil), 8)
   600  		helloRetryRequest.encryptedClientHello = acceptConfirmation
   601  	}
   602  
   603  	if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
   604  		return nil, err
   605  	}
   606  
   607  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   608  		return nil, err
   609  	}
   610  
   611  	// clientHelloMsg is not included in the transcript.
   612  	msg, err := c.readHandshake(nil)
   613  	if err != nil {
   614  		return nil, err
   615  	}
   616  
   617  	clientHello, ok := msg.(*clientHelloMsg)
   618  	if !ok {
   619  		c.sendAlert(alertUnexpectedMessage)
   620  		return nil, unexpectedMessageError(clientHello, msg)
   621  	}
   622  
   623  	if hs.echContext != nil {
   624  		if len(clientHello.encryptedClientHello) == 0 {
   625  			c.sendAlert(alertMissingExtension)
   626  			return nil, errors.New("tls: second client hello missing encrypted client hello extension")
   627  		}
   628  
   629  		echType, echCiphersuite, configID, encap, payload, err := parseECHExt(clientHello.encryptedClientHello)
   630  		if err != nil {
   631  			c.sendAlert(alertDecodeError)
   632  			return nil, errors.New("tls: client sent invalid encrypted client hello extension")
   633  		}
   634  
   635  		if echType == outerECHExt && hs.echContext.inner || echType == innerECHExt && !hs.echContext.inner {
   636  			c.sendAlert(alertDecodeError)
   637  			return nil, errors.New("tls: unexpected switch in encrypted client hello extension type")
   638  		}
   639  
   640  		if echType == outerECHExt {
   641  			if echCiphersuite != hs.echContext.ciphersuite || configID != hs.echContext.configID || len(encap) != 0 {
   642  				c.sendAlert(alertIllegalParameter)
   643  				return nil, errors.New("tls: second client hello encrypted client hello extension does not match")
   644  			}
   645  
   646  			encodedInner, err := decryptECHPayload(hs.echContext.hpkeContext, clientHello.original, payload)
   647  			if err != nil {
   648  				c.sendAlert(alertDecryptError)
   649  				return nil, errors.New("tls: failed to decrypt second client hello encrypted client hello extension payload")
   650  			}
   651  
   652  			echInner, err := decodeInnerClientHello(clientHello, encodedInner)
   653  			if err != nil {
   654  				c.sendAlert(alertIllegalParameter)
   655  				return nil, errors.New("tls: client sent invalid encrypted client hello extension")
   656  			}
   657  
   658  			clientHello = echInner
   659  		}
   660  	}
   661  
   662  	if len(clientHello.keyShares) != 1 {
   663  		c.sendAlert(alertIllegalParameter)
   664  		return nil, errors.New("tls: client didn't send one key share in second ClientHello")
   665  	}
   666  	ks := &clientHello.keyShares[0]
   667  
   668  	if ks.group != selectedGroup {
   669  		c.sendAlert(alertIllegalParameter)
   670  		return nil, errors.New("tls: client sent unexpected key share in second ClientHello")
   671  	}
   672  
   673  	if clientHello.earlyData {
   674  		c.sendAlert(alertIllegalParameter)
   675  		return nil, errors.New("tls: client indicated early data in second ClientHello")
   676  	}
   677  
   678  	if illegalClientHelloChange(clientHello, hs.clientHello) {
   679  		c.sendAlert(alertIllegalParameter)
   680  		return nil, errors.New("tls: client illegally modified second ClientHello")
   681  	}
   682  
   683  	c.didHRR = true
   684  	hs.clientHello = clientHello
   685  	return ks, nil
   686  }
   687  
   688  // illegalClientHelloChange reports whether the two ClientHello messages are
   689  // different, with the exception of the changes allowed before and after a
   690  // HelloRetryRequest. See RFC 8446, Section 4.1.2.
   691  func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
   692  	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
   693  		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
   694  		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
   695  		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
   696  		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
   697  		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
   698  		return true
   699  	}
   700  	for i := range ch.supportedVersions {
   701  		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
   702  			return true
   703  		}
   704  	}
   705  	for i := range ch.cipherSuites {
   706  		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
   707  			return true
   708  		}
   709  	}
   710  	for i := range ch.supportedCurves {
   711  		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
   712  			return true
   713  		}
   714  	}
   715  	for i := range ch.supportedSignatureAlgorithms {
   716  		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
   717  			return true
   718  		}
   719  	}
   720  	for i := range ch.supportedSignatureAlgorithmsCert {
   721  		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
   722  			return true
   723  		}
   724  	}
   725  	for i := range ch.alpnProtocols {
   726  		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
   727  			return true
   728  		}
   729  	}
   730  	return ch.vers != ch1.vers ||
   731  		!bytes.Equal(ch.random, ch1.random) ||
   732  		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
   733  		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
   734  		ch.serverName != ch1.serverName ||
   735  		ch.ocspStapling != ch1.ocspStapling ||
   736  		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
   737  		ch.ticketSupported != ch1.ticketSupported ||
   738  		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
   739  		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
   740  		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
   741  		ch.scts != ch1.scts ||
   742  		!bytes.Equal(ch.cookie, ch1.cookie) ||
   743  		!bytes.Equal(ch.pskModes, ch1.pskModes)
   744  }
   745  
   746  func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
   747  	c := hs.c
   748  
   749  	if hs.echContext != nil {
   750  		copy(hs.hello.random[32-8:], make([]byte, 8))
   751  		echTranscript := cloneHash(hs.transcript, hs.suite.hash)
   752  		echTranscript.Write(hs.clientHello.original)
   753  		if err := transcriptMsg(hs.hello, echTranscript); err != nil {
   754  			return err
   755  		}
   756  		// compute the acceptance message
   757  		h := hs.suite.hash.New
   758  		prk, err := hkdf.Extract(h, hs.clientHello.random, nil)
   759  		if err != nil {
   760  			c.sendAlert(alertInternalError)
   761  			return err
   762  		}
   763  		acceptConfirmation := tls13.ExpandLabel(h, prk, "ech accept confirmation", echTranscript.Sum(nil), 8)
   764  		copy(hs.hello.random[32-8:], acceptConfirmation)
   765  	}
   766  
   767  	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
   768  		return err
   769  	}
   770  
   771  	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
   772  		return err
   773  	}
   774  
   775  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   776  		return err
   777  	}
   778  
   779  	earlySecret := hs.earlySecret
   780  	if earlySecret == nil {
   781  		earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
   782  	}
   783  	hs.handshakeSecret = earlySecret.HandshakeSecret(hs.sharedKey)
   784  
   785  	serverSecret := hs.handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
   786  	c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
   787  	clientSecret := hs.handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
   788  	if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret); err != nil {
   789  		return err
   790  	}
   791  
   792  	if c.quic != nil {
   793  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
   794  		if err := c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret); err != nil {
   795  			return err
   796  		}
   797  	}
   798  
   799  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
   800  	if err != nil {
   801  		c.sendAlert(alertInternalError)
   802  		return err
   803  	}
   804  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
   805  	if err != nil {
   806  		c.sendAlert(alertInternalError)
   807  		return err
   808  	}
   809  
   810  	encryptedExtensions := new(encryptedExtensionsMsg)
   811  	encryptedExtensions.alpnProtocol = c.clientProtocol
   812  
   813  	if c.quic != nil {
   814  		p, err := c.quicGetTransportParameters()
   815  		if err != nil {
   816  			return err
   817  		}
   818  		encryptedExtensions.quicTransportParameters = p
   819  		encryptedExtensions.earlyData = hs.earlyData
   820  	}
   821  
   822  	if !hs.c.didResume && hs.clientHello.serverName != "" {
   823  		encryptedExtensions.serverNameAck = true
   824  	}
   825  
   826  	// If client sent ECH extension, but we didn't accept it,
   827  	// send retry configs, if available.
   828  	echKeys := hs.c.config.EncryptedClientHelloKeys
   829  	if hs.c.config.GetEncryptedClientHelloKeys != nil {
   830  		echKeys, err = hs.c.config.GetEncryptedClientHelloKeys(clientHelloInfo(hs.ctx, c, hs.clientHello))
   831  		if err != nil {
   832  			c.sendAlert(alertInternalError)
   833  			return err
   834  		}
   835  	}
   836  	if len(echKeys) > 0 && len(hs.clientHello.encryptedClientHello) > 0 && hs.echContext == nil {
   837  		encryptedExtensions.echRetryConfigs, err = buildRetryConfigList(echKeys)
   838  		if err != nil {
   839  			c.sendAlert(alertInternalError)
   840  			return err
   841  		}
   842  	}
   843  
   844  	if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
   845  		return err
   846  	}
   847  
   848  	return nil
   849  }
   850  
   851  func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
   852  	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
   853  }
   854  
   855  func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
   856  	c := hs.c
   857  
   858  	// Only one of PSK and certificates are used at a time.
   859  	if hs.usingPSK {
   860  		return nil
   861  	}
   862  
   863  	if hs.requestClientCert() {
   864  		// Request a client certificate
   865  		certReq := new(certificateRequestMsgTLS13)
   866  		certReq.ocspStapling = true
   867  		certReq.scts = true
   868  		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms(c.vers)
   869  		certReq.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert()
   870  		if c.config.ClientCAs != nil {
   871  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   872  		}
   873  
   874  		if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
   875  			return err
   876  		}
   877  	}
   878  
   879  	certMsg := new(certificateMsgTLS13)
   880  
   881  	certMsg.certificate = *hs.cert
   882  	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
   883  	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
   884  
   885  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
   886  		return err
   887  	}
   888  
   889  	certVerifyMsg := new(certificateVerifyMsg)
   890  	certVerifyMsg.hasSignatureAlgorithm = true
   891  	certVerifyMsg.signatureAlgorithm = hs.sigAlg
   892  
   893  	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
   894  	if err != nil {
   895  		return c.sendAlert(alertInternalError)
   896  	}
   897  
   898  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   899  	signOpts := crypto.SignerOpts(sigHash)
   900  	if sigType == signatureRSAPSS {
   901  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   902  	}
   903  	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   904  	if err != nil {
   905  		public := hs.cert.PrivateKey.(crypto.Signer).Public()
   906  		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
   907  			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
   908  			c.sendAlert(alertHandshakeFailure)
   909  		} else {
   910  			c.sendAlert(alertInternalError)
   911  		}
   912  		return errors.New("tls: failed to sign handshake: " + err.Error())
   913  	}
   914  	certVerifyMsg.signature = sig
   915  
   916  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
   917  		return err
   918  	}
   919  
   920  	return nil
   921  }
   922  
   923  func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
   924  	c := hs.c
   925  
   926  	finished := &finishedMsg{
   927  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   928  	}
   929  
   930  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
   931  		return err
   932  	}
   933  
   934  	// Derive secrets that take context through the server Finished.
   935  
   936  	hs.masterSecret = hs.handshakeSecret.MasterSecret()
   937  
   938  	hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
   939  	serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
   940  	c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
   941  
   942  	if c.quic != nil {
   943  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
   944  	}
   945  
   946  	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
   947  	if err != nil {
   948  		c.sendAlert(alertInternalError)
   949  		return err
   950  	}
   951  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
   952  	if err != nil {
   953  		c.sendAlert(alertInternalError)
   954  		return err
   955  	}
   956  
   957  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   958  
   959  	// If we did not request client certificates, at this point we can
   960  	// precompute the client finished and roll the transcript forward to send
   961  	// session tickets in our first flight.
   962  	if !hs.requestClientCert() {
   963  		if err := hs.sendSessionTickets(); err != nil {
   964  			return err
   965  		}
   966  	}
   967  
   968  	return nil
   969  }
   970  
   971  func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
   972  	if hs.c.config.SessionTicketsDisabled {
   973  		return false
   974  	}
   975  
   976  	// QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically.
   977  	if hs.c.quic != nil {
   978  		return false
   979  	}
   980  
   981  	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
   982  	return slices.Contains(hs.clientHello.pskModes, pskModeDHE)
   983  }
   984  
   985  func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
   986  	c := hs.c
   987  
   988  	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   989  	finishedMsg := &finishedMsg{
   990  		verifyData: hs.clientFinished,
   991  	}
   992  	if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
   993  		return err
   994  	}
   995  
   996  	c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
   997  
   998  	if !hs.shouldSendSessionTickets() {
   999  		return nil
  1000  	}
  1001  	return c.sendSessionTicket(false, nil)
  1002  }
  1003  
  1004  func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error {
  1005  	suite := cipherSuiteTLS13ByID(c.cipherSuite)
  1006  	if suite == nil {
  1007  		return errors.New("tls: internal error: unknown cipher suite")
  1008  	}
  1009  	// ticket_nonce, which must be unique per connection, is always left at
  1010  	// zero because we only ever send one ticket per connection.
  1011  	psk := tls13.ExpandLabel(suite.hash.New, c.resumptionSecret, "resumption",
  1012  		nil, suite.hash.Size())
  1013  
  1014  	m := new(newSessionTicketMsgTLS13)
  1015  
  1016  	state := c.sessionState()
  1017  	state.secret = psk
  1018  	state.EarlyData = earlyData
  1019  	state.Extra = extra
  1020  	if c.config.WrapSession != nil {
  1021  		var err error
  1022  		m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
  1023  		if err != nil {
  1024  			return err
  1025  		}
  1026  	} else {
  1027  		stateBytes, err := state.Bytes()
  1028  		if err != nil {
  1029  			c.sendAlert(alertInternalError)
  1030  			return err
  1031  		}
  1032  		m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
  1033  		if err != nil {
  1034  			return err
  1035  		}
  1036  	}
  1037  	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
  1038  
  1039  	// ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1
  1040  	// The value is not stored anywhere; we never need to check the ticket age
  1041  	// because 0-RTT is not supported.
  1042  	ageAdd := make([]byte, 4)
  1043  	if _, err := c.config.rand().Read(ageAdd); err != nil {
  1044  		return err
  1045  	}
  1046  	m.ageAdd = byteorder.LEUint32(ageAdd)
  1047  
  1048  	if earlyData {
  1049  		// RFC 9001, Section 4.6.1
  1050  		m.maxEarlyData = 0xffffffff
  1051  	}
  1052  
  1053  	if _, err := c.writeHandshakeRecord(m, nil); err != nil {
  1054  		return err
  1055  	}
  1056  
  1057  	return nil
  1058  }
  1059  
  1060  func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
  1061  	c := hs.c
  1062  
  1063  	if !hs.requestClientCert() {
  1064  		// Make sure the connection is still being verified whether or not
  1065  		// the server requested a client certificate.
  1066  		if c.config.VerifyConnection != nil {
  1067  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1068  				c.sendAlert(alertBadCertificate)
  1069  				return err
  1070  			}
  1071  		}
  1072  		return nil
  1073  	}
  1074  
  1075  	// If we requested a client certificate, then the client must send a
  1076  	// certificate message. If it's empty, no CertificateVerify is sent.
  1077  
  1078  	msg, err := c.readHandshake(hs.transcript)
  1079  	if err != nil {
  1080  		return err
  1081  	}
  1082  
  1083  	certMsg, ok := msg.(*certificateMsgTLS13)
  1084  	if !ok {
  1085  		c.sendAlert(alertUnexpectedMessage)
  1086  		return unexpectedMessageError(certMsg, msg)
  1087  	}
  1088  
  1089  	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
  1090  		return err
  1091  	}
  1092  
  1093  	if c.config.VerifyConnection != nil {
  1094  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1095  			c.sendAlert(alertBadCertificate)
  1096  			return err
  1097  		}
  1098  	}
  1099  
  1100  	if len(certMsg.certificate.Certificate) != 0 {
  1101  		// certificateVerifyMsg is included in the transcript, but not until
  1102  		// after we verify the handshake signature, since the state before
  1103  		// this message was sent is used.
  1104  		msg, err = c.readHandshake(nil)
  1105  		if err != nil {
  1106  			return err
  1107  		}
  1108  
  1109  		certVerify, ok := msg.(*certificateVerifyMsg)
  1110  		if !ok {
  1111  			c.sendAlert(alertUnexpectedMessage)
  1112  			return unexpectedMessageError(certVerify, msg)
  1113  		}
  1114  
  1115  		// See RFC 8446, Section 4.4.3.
  1116  		// We don't use certReq.supportedSignatureAlgorithms because it would
  1117  		// require keeping the certificateRequestMsgTLS13 around in the hs.
  1118  		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers)) ||
  1119  			!isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, signatureSchemesForPublicKey(c.vers, c.peerCertificates[0].PublicKey)) {
  1120  			c.sendAlert(alertIllegalParameter)
  1121  			return errors.New("tls: client certificate used with invalid signature algorithm")
  1122  		}
  1123  		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  1124  		if err != nil {
  1125  			return c.sendAlert(alertInternalError)
  1126  		}
  1127  		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
  1128  			return c.sendAlert(alertInternalError)
  1129  		}
  1130  		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
  1131  		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
  1132  			sigHash, signed, certVerify.signature); err != nil {
  1133  			c.sendAlert(alertDecryptError)
  1134  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
  1135  		}
  1136  		c.peerSigAlg = certVerify.signatureAlgorithm
  1137  
  1138  		if err := transcriptMsg(certVerify, hs.transcript); err != nil {
  1139  			return err
  1140  		}
  1141  	}
  1142  
  1143  	// If we waited until the client certificates to send session tickets, we
  1144  	// are ready to do it now.
  1145  	if err := hs.sendSessionTickets(); err != nil {
  1146  		return err
  1147  	}
  1148  
  1149  	return nil
  1150  }
  1151  
  1152  func (hs *serverHandshakeStateTLS13) readClientFinished() error {
  1153  	c := hs.c
  1154  
  1155  	// finishedMsg is not included in the transcript.
  1156  	msg, err := c.readHandshake(nil)
  1157  	if err != nil {
  1158  		return err
  1159  	}
  1160  
  1161  	finished, ok := msg.(*finishedMsg)
  1162  	if !ok {
  1163  		c.sendAlert(alertUnexpectedMessage)
  1164  		return unexpectedMessageError(finished, msg)
  1165  	}
  1166  
  1167  	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
  1168  		c.sendAlert(alertDecryptError)
  1169  		return errors.New("tls: invalid client finished hash")
  1170  	}
  1171  
  1172  	if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret); err != nil {
  1173  		return err
  1174  	}
  1175  
  1176  	return nil
  1177  }
  1178  

View as plain text