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

View as plain text