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

View as plain text