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

View as plain text