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

View as plain text