Source file src/crypto/tls/handshake_server_tls13.go

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

View as plain text