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

View as plain text