Source file src/crypto/tls/handshake_client_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/rsa"
    16  	"crypto/subtle"
    17  	"errors"
    18  	"hash"
    19  	"slices"
    20  	"time"
    21  )
    22  
    23  type clientHandshakeStateTLS13 struct {
    24  	c            *Conn
    25  	ctx          context.Context
    26  	serverHello  *serverHelloMsg
    27  	hello        *clientHelloMsg
    28  	keyShareKeys *keySharePrivateKeys
    29  
    30  	session     *SessionState
    31  	earlySecret *tls13.EarlySecret
    32  	binderKey   []byte
    33  
    34  	certReq       *certificateRequestMsgTLS13
    35  	usingPSK      bool
    36  	sentDummyCCS  bool
    37  	suite         *cipherSuiteTLS13
    38  	transcript    hash.Hash
    39  	masterSecret  *tls13.MasterSecret
    40  	trafficSecret []byte // client_application_traffic_secret_0
    41  
    42  	echContext *echClientContext
    43  }
    44  
    45  // handshake requires hs.c, hs.hello, hs.serverHello, hs.keyShareKeys, and,
    46  // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
    47  func (hs *clientHandshakeStateTLS13) handshake() error {
    48  	c := hs.c
    49  
    50  	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
    51  	// sections 4.1.2 and 4.1.3.
    52  	if c.handshakes > 0 {
    53  		c.sendAlert(alertProtocolVersion)
    54  		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
    55  	}
    56  
    57  	// Consistency check on the presence of a keyShare and its parameters.
    58  	if hs.keyShareKeys == nil || hs.keyShareKeys.ecdhe == nil || len(hs.hello.keyShares) == 0 {
    59  		return c.sendAlert(alertInternalError)
    60  	}
    61  
    62  	if err := hs.checkServerHelloOrHRR(); err != nil {
    63  		return err
    64  	}
    65  
    66  	hs.transcript = hs.suite.hash.New()
    67  
    68  	if err := transcriptMsg(hs.hello, hs.transcript); err != nil {
    69  		return err
    70  	}
    71  
    72  	if hs.echContext != nil {
    73  		hs.echContext.innerTranscript = hs.suite.hash.New()
    74  		if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
    75  			return err
    76  		}
    77  	}
    78  
    79  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
    80  		if err := hs.sendDummyChangeCipherSpec(); err != nil {
    81  			return err
    82  		}
    83  		if err := hs.processHelloRetryRequest(); err != nil {
    84  			return err
    85  		}
    86  	}
    87  
    88  	if hs.echContext != nil {
    89  		confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
    90  		confTranscript.Write(hs.serverHello.original[:30])
    91  		confTranscript.Write(make([]byte, 8))
    92  		confTranscript.Write(hs.serverHello.original[38:])
    93  		acceptConfirmation := tls13.ExpandLabel(hs.suite.hash.New,
    94  			hkdf.Extract(hs.suite.hash.New, hs.echContext.innerHello.random, nil),
    95  			"ech accept confirmation",
    96  			confTranscript.Sum(nil),
    97  			8,
    98  		)
    99  		if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.random[len(hs.serverHello.random)-8:]) == 1 {
   100  			hs.hello = hs.echContext.innerHello
   101  			c.serverName = c.config.ServerName
   102  			hs.transcript = hs.echContext.innerTranscript
   103  			c.echAccepted = true
   104  
   105  			if hs.serverHello.encryptedClientHello != nil {
   106  				c.sendAlert(alertUnsupportedExtension)
   107  				return errors.New("tls: unexpected encrypted client hello extension in server hello despite ECH being accepted")
   108  			}
   109  
   110  			if hs.hello.serverName == "" && hs.serverHello.serverNameAck {
   111  				c.sendAlert(alertUnsupportedExtension)
   112  				return errors.New("tls: unexpected server_name extension in server hello")
   113  			}
   114  		} else {
   115  			hs.echContext.echRejected = true
   116  		}
   117  	}
   118  
   119  	if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
   120  		return err
   121  	}
   122  
   123  	c.buffering = true
   124  	if err := hs.processServerHello(); err != nil {
   125  		return err
   126  	}
   127  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   128  		return err
   129  	}
   130  	if err := hs.establishHandshakeKeys(); err != nil {
   131  		return err
   132  	}
   133  	if err := hs.readServerParameters(); err != nil {
   134  		return err
   135  	}
   136  	if err := hs.readServerCertificate(); err != nil {
   137  		return err
   138  	}
   139  	if err := hs.readServerFinished(); err != nil {
   140  		return err
   141  	}
   142  	if err := hs.sendClientCertificate(); err != nil {
   143  		return err
   144  	}
   145  	if err := hs.sendClientFinished(); err != nil {
   146  		return err
   147  	}
   148  	if _, err := c.flush(); err != nil {
   149  		return err
   150  	}
   151  
   152  	if hs.echContext != nil && hs.echContext.echRejected {
   153  		c.sendAlert(alertECHRequired)
   154  		return &ECHRejectionError{hs.echContext.retryConfigs}
   155  	}
   156  
   157  	c.isHandshakeComplete.Store(true)
   158  
   159  	return nil
   160  }
   161  
   162  // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
   163  // HelloRetryRequest messages. It sets hs.suite.
   164  func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
   165  	c := hs.c
   166  
   167  	if hs.serverHello.supportedVersion == 0 {
   168  		c.sendAlert(alertMissingExtension)
   169  		return errors.New("tls: server selected TLS 1.3 using the legacy version field")
   170  	}
   171  
   172  	if hs.serverHello.supportedVersion != VersionTLS13 {
   173  		c.sendAlert(alertIllegalParameter)
   174  		return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
   175  	}
   176  
   177  	if hs.serverHello.vers != VersionTLS12 {
   178  		c.sendAlert(alertIllegalParameter)
   179  		return errors.New("tls: server sent an incorrect legacy version")
   180  	}
   181  
   182  	if hs.serverHello.ocspStapling ||
   183  		hs.serverHello.ticketSupported ||
   184  		hs.serverHello.extendedMasterSecret ||
   185  		hs.serverHello.secureRenegotiationSupported ||
   186  		len(hs.serverHello.secureRenegotiation) != 0 ||
   187  		len(hs.serverHello.alpnProtocol) != 0 ||
   188  		len(hs.serverHello.scts) != 0 {
   189  		c.sendAlert(alertUnsupportedExtension)
   190  		return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
   191  	}
   192  
   193  	if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
   194  		c.sendAlert(alertIllegalParameter)
   195  		return errors.New("tls: server did not echo the legacy session ID")
   196  	}
   197  
   198  	if hs.serverHello.compressionMethod != compressionNone {
   199  		c.sendAlert(alertIllegalParameter)
   200  		return errors.New("tls: server selected unsupported compression format")
   201  	}
   202  
   203  	selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
   204  	if hs.suite != nil && selectedSuite != hs.suite {
   205  		c.sendAlert(alertIllegalParameter)
   206  		return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
   207  	}
   208  	if selectedSuite == nil {
   209  		c.sendAlert(alertIllegalParameter)
   210  		return errors.New("tls: server chose an unconfigured cipher suite")
   211  	}
   212  	hs.suite = selectedSuite
   213  	c.cipherSuite = hs.suite.id
   214  
   215  	return nil
   216  }
   217  
   218  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   219  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   220  func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   221  	if hs.c.quic != nil {
   222  		return nil
   223  	}
   224  	if hs.sentDummyCCS {
   225  		return nil
   226  	}
   227  	hs.sentDummyCCS = true
   228  
   229  	return hs.c.writeChangeCipherRecord()
   230  }
   231  
   232  // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
   233  // resends hs.hello, and reads the new ServerHello into hs.serverHello.
   234  func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
   235  	c := hs.c
   236  
   237  	// The first ClientHello gets double-hashed into the transcript upon a
   238  	// HelloRetryRequest. (The idea is that the server might offload transcript
   239  	// storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
   240  	chHash := hs.transcript.Sum(nil)
   241  	hs.transcript.Reset()
   242  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   243  	hs.transcript.Write(chHash)
   244  	if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
   245  		return err
   246  	}
   247  
   248  	var isInnerHello bool
   249  	hello := hs.hello
   250  	if hs.echContext != nil {
   251  		chHash = hs.echContext.innerTranscript.Sum(nil)
   252  		hs.echContext.innerTranscript.Reset()
   253  		hs.echContext.innerTranscript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   254  		hs.echContext.innerTranscript.Write(chHash)
   255  
   256  		if hs.serverHello.encryptedClientHello != nil {
   257  			if len(hs.serverHello.encryptedClientHello) != 8 {
   258  				hs.c.sendAlert(alertDecodeError)
   259  				return errors.New("tls: malformed encrypted client hello extension")
   260  			}
   261  
   262  			confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
   263  			hrrHello := make([]byte, len(hs.serverHello.original))
   264  			copy(hrrHello, hs.serverHello.original)
   265  			hrrHello = bytes.Replace(hrrHello, hs.serverHello.encryptedClientHello, make([]byte, 8), 1)
   266  			confTranscript.Write(hrrHello)
   267  			acceptConfirmation := tls13.ExpandLabel(hs.suite.hash.New,
   268  				hkdf.Extract(hs.suite.hash.New, hs.echContext.innerHello.random, nil),
   269  				"hrr ech accept confirmation",
   270  				confTranscript.Sum(nil),
   271  				8,
   272  			)
   273  			if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.encryptedClientHello) == 1 {
   274  				hello = hs.echContext.innerHello
   275  				c.serverName = c.config.ServerName
   276  				isInnerHello = true
   277  				c.echAccepted = true
   278  			}
   279  		}
   280  
   281  		if err := transcriptMsg(hs.serverHello, hs.echContext.innerTranscript); err != nil {
   282  			return err
   283  		}
   284  	} else if hs.serverHello.encryptedClientHello != nil {
   285  		// Unsolicited ECH extension should be rejected
   286  		c.sendAlert(alertUnsupportedExtension)
   287  		return errors.New("tls: unexpected encrypted client hello extension in serverHello")
   288  	}
   289  
   290  	// The only HelloRetryRequest extensions we support are key_share and
   291  	// cookie, and clients must abort the handshake if the HRR would not result
   292  	// in any change in the ClientHello.
   293  	if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
   294  		c.sendAlert(alertIllegalParameter)
   295  		return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
   296  	}
   297  
   298  	if hs.serverHello.cookie != nil {
   299  		hello.cookie = hs.serverHello.cookie
   300  	}
   301  
   302  	if hs.serverHello.serverShare.group != 0 {
   303  		c.sendAlert(alertDecodeError)
   304  		return errors.New("tls: received malformed key_share extension")
   305  	}
   306  
   307  	// If the server sent a key_share extension selecting a group, ensure it's
   308  	// a group we advertised but did not send a key share for, and send a key
   309  	// share for it this time.
   310  	if curveID := hs.serverHello.selectedGroup; curveID != 0 {
   311  		if !slices.Contains(hello.supportedCurves, curveID) {
   312  			c.sendAlert(alertIllegalParameter)
   313  			return errors.New("tls: server selected unsupported group")
   314  		}
   315  		if slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
   316  			return ks.group == curveID
   317  		}) {
   318  			c.sendAlert(alertIllegalParameter)
   319  			return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
   320  		}
   321  		// Note: we don't support selecting X25519MLKEM768 in a HRR, because it
   322  		// is currently first in preference order, so if it's enabled we'll
   323  		// always send a key share for it.
   324  		//
   325  		// This will have to change once we support multiple hybrid KEMs.
   326  		if _, ok := curveForCurveID(curveID); !ok {
   327  			c.sendAlert(alertInternalError)
   328  			return errors.New("tls: CurvePreferences includes unsupported curve")
   329  		}
   330  		key, err := generateECDHEKey(c.config.rand(), curveID)
   331  		if err != nil {
   332  			c.sendAlert(alertInternalError)
   333  			return err
   334  		}
   335  		hs.keyShareKeys = &keySharePrivateKeys{curveID: curveID, ecdhe: key}
   336  		hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}}
   337  	}
   338  
   339  	if len(hello.pskIdentities) > 0 {
   340  		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   341  		if pskSuite == nil {
   342  			return c.sendAlert(alertInternalError)
   343  		}
   344  		if pskSuite.hash == hs.suite.hash {
   345  			// Update binders and obfuscated_ticket_age.
   346  			ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0))
   347  			hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd
   348  
   349  			transcript := hs.suite.hash.New()
   350  			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   351  			transcript.Write(chHash)
   352  			if err := transcriptMsg(hs.serverHello, transcript); err != nil {
   353  				return err
   354  			}
   355  
   356  			if err := computeAndUpdatePSK(hello, hs.binderKey, transcript, hs.suite.finishedHash); err != nil {
   357  				return err
   358  			}
   359  		} else {
   360  			// Server selected a cipher suite incompatible with the PSK.
   361  			hello.pskIdentities = nil
   362  			hello.pskBinders = nil
   363  		}
   364  	}
   365  
   366  	if hello.earlyData {
   367  		hello.earlyData = false
   368  		c.quicRejectedEarlyData()
   369  	}
   370  
   371  	if isInnerHello {
   372  		// Any extensions which have changed in hello, but are mirrored in the
   373  		// outer hello and compressed, need to be copied to the outer hello, so
   374  		// they can be properly decompressed by the server. For now, the only
   375  		// extension which may have changed is keyShares.
   376  		hs.hello.keyShares = hello.keyShares
   377  		hs.echContext.innerHello = hello
   378  		if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
   379  			return err
   380  		}
   381  
   382  		if err := computeAndUpdateOuterECHExtension(hs.hello, hs.echContext.innerHello, hs.echContext, false); err != nil {
   383  			return err
   384  		}
   385  	} else {
   386  		hs.hello = hello
   387  	}
   388  
   389  	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
   390  		return err
   391  	}
   392  
   393  	// serverHelloMsg is not included in the transcript
   394  	msg, err := c.readHandshake(nil)
   395  	if err != nil {
   396  		return err
   397  	}
   398  
   399  	serverHello, ok := msg.(*serverHelloMsg)
   400  	if !ok {
   401  		c.sendAlert(alertUnexpectedMessage)
   402  		return unexpectedMessageError(serverHello, msg)
   403  	}
   404  	hs.serverHello = serverHello
   405  
   406  	if err := hs.checkServerHelloOrHRR(); err != nil {
   407  		return err
   408  	}
   409  
   410  	c.didHRR = true
   411  	return nil
   412  }
   413  
   414  func (hs *clientHandshakeStateTLS13) processServerHello() error {
   415  	c := hs.c
   416  
   417  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
   418  		c.sendAlert(alertUnexpectedMessage)
   419  		return errors.New("tls: server sent two HelloRetryRequest messages")
   420  	}
   421  
   422  	if len(hs.serverHello.cookie) != 0 {
   423  		c.sendAlert(alertUnsupportedExtension)
   424  		return errors.New("tls: server sent a cookie in a normal ServerHello")
   425  	}
   426  
   427  	if hs.serverHello.selectedGroup != 0 {
   428  		c.sendAlert(alertDecodeError)
   429  		return errors.New("tls: malformed key_share extension")
   430  	}
   431  
   432  	if hs.serverHello.serverShare.group == 0 {
   433  		c.sendAlert(alertIllegalParameter)
   434  		return errors.New("tls: server did not send a key share")
   435  	}
   436  	if !slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
   437  		return ks.group == hs.serverHello.serverShare.group
   438  	}) {
   439  		c.sendAlert(alertIllegalParameter)
   440  		return errors.New("tls: server selected unsupported group")
   441  	}
   442  
   443  	if !hs.serverHello.selectedIdentityPresent {
   444  		return nil
   445  	}
   446  
   447  	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
   448  		c.sendAlert(alertIllegalParameter)
   449  		return errors.New("tls: server selected an invalid PSK")
   450  	}
   451  
   452  	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
   453  		return c.sendAlert(alertInternalError)
   454  	}
   455  	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   456  	if pskSuite == nil {
   457  		return c.sendAlert(alertInternalError)
   458  	}
   459  	if pskSuite.hash != hs.suite.hash {
   460  		c.sendAlert(alertIllegalParameter)
   461  		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
   462  	}
   463  
   464  	hs.usingPSK = true
   465  	c.didResume = true
   466  	c.peerCertificates = hs.session.peerCertificates
   467  	c.activeCertHandles = hs.session.activeCertHandles
   468  	c.verifiedChains = hs.session.verifiedChains
   469  	c.ocspResponse = hs.session.ocspResponse
   470  	c.scts = hs.session.scts
   471  	return nil
   472  }
   473  
   474  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
   475  	c := hs.c
   476  
   477  	ecdhePeerData := hs.serverHello.serverShare.data
   478  	if hs.serverHello.serverShare.group == X25519MLKEM768 {
   479  		if len(ecdhePeerData) != mlkem.CiphertextSize768+x25519PublicKeySize {
   480  			c.sendAlert(alertIllegalParameter)
   481  			return errors.New("tls: invalid server X25519MLKEM768 key share")
   482  		}
   483  		ecdhePeerData = hs.serverHello.serverShare.data[mlkem.CiphertextSize768:]
   484  	}
   485  	peerKey, err := hs.keyShareKeys.ecdhe.Curve().NewPublicKey(ecdhePeerData)
   486  	if err != nil {
   487  		c.sendAlert(alertIllegalParameter)
   488  		return errors.New("tls: invalid server key share")
   489  	}
   490  	sharedKey, err := hs.keyShareKeys.ecdhe.ECDH(peerKey)
   491  	if err != nil {
   492  		c.sendAlert(alertIllegalParameter)
   493  		return errors.New("tls: invalid server key share")
   494  	}
   495  	if hs.serverHello.serverShare.group == X25519MLKEM768 {
   496  		if hs.keyShareKeys.mlkem == nil {
   497  			return c.sendAlert(alertInternalError)
   498  		}
   499  		ciphertext := hs.serverHello.serverShare.data[:mlkem.CiphertextSize768]
   500  		mlkemShared, err := hs.keyShareKeys.mlkem.Decapsulate(ciphertext)
   501  		if err != nil {
   502  			c.sendAlert(alertIllegalParameter)
   503  			return errors.New("tls: invalid X25519MLKEM768 server key share")
   504  		}
   505  		sharedKey = append(mlkemShared, sharedKey...)
   506  	}
   507  	c.curveID = hs.serverHello.serverShare.group
   508  
   509  	earlySecret := hs.earlySecret
   510  	if !hs.usingPSK {
   511  		earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
   512  	}
   513  
   514  	handshakeSecret := earlySecret.HandshakeSecret(sharedKey)
   515  
   516  	clientSecret := handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
   517  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
   518  	serverSecret := handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
   519  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
   520  
   521  	if c.quic != nil {
   522  		if c.hand.Len() != 0 {
   523  			c.sendAlert(alertUnexpectedMessage)
   524  		}
   525  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
   526  		c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
   527  	}
   528  
   529  	err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
   530  	if err != nil {
   531  		c.sendAlert(alertInternalError)
   532  		return err
   533  	}
   534  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
   535  	if err != nil {
   536  		c.sendAlert(alertInternalError)
   537  		return err
   538  	}
   539  
   540  	hs.masterSecret = handshakeSecret.MasterSecret()
   541  
   542  	return nil
   543  }
   544  
   545  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
   546  	c := hs.c
   547  
   548  	msg, err := c.readHandshake(hs.transcript)
   549  	if err != nil {
   550  		return err
   551  	}
   552  
   553  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
   554  	if !ok {
   555  		c.sendAlert(alertUnexpectedMessage)
   556  		return unexpectedMessageError(encryptedExtensions, msg)
   557  	}
   558  
   559  	if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
   560  		// RFC 8446 specifies that no_application_protocol is sent by servers, but
   561  		// does not specify how clients handle the selection of an incompatible protocol.
   562  		// RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
   563  		// in this case. Always sending no_application_protocol seems reasonable.
   564  		c.sendAlert(alertNoApplicationProtocol)
   565  		return err
   566  	}
   567  	c.clientProtocol = encryptedExtensions.alpnProtocol
   568  
   569  	if c.quic != nil {
   570  		if encryptedExtensions.quicTransportParameters == nil {
   571  			// RFC 9001 Section 8.2.
   572  			c.sendAlert(alertMissingExtension)
   573  			return errors.New("tls: server did not send a quic_transport_parameters extension")
   574  		}
   575  		c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
   576  	} else {
   577  		if encryptedExtensions.quicTransportParameters != nil {
   578  			c.sendAlert(alertUnsupportedExtension)
   579  			return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
   580  		}
   581  	}
   582  
   583  	if !hs.hello.earlyData && encryptedExtensions.earlyData {
   584  		c.sendAlert(alertUnsupportedExtension)
   585  		return errors.New("tls: server sent an unexpected early_data extension")
   586  	}
   587  	if hs.hello.earlyData && !encryptedExtensions.earlyData {
   588  		c.quicRejectedEarlyData()
   589  	}
   590  	if encryptedExtensions.earlyData {
   591  		if hs.session.cipherSuite != c.cipherSuite {
   592  			c.sendAlert(alertHandshakeFailure)
   593  			return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
   594  		}
   595  		if hs.session.alpnProtocol != c.clientProtocol {
   596  			c.sendAlert(alertHandshakeFailure)
   597  			return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
   598  		}
   599  	}
   600  	if hs.echContext != nil {
   601  		if hs.echContext.echRejected {
   602  			hs.echContext.retryConfigs = encryptedExtensions.echRetryConfigs
   603  		} else if encryptedExtensions.echRetryConfigs != nil {
   604  			c.sendAlert(alertUnsupportedExtension)
   605  			return errors.New("tls: server sent encrypted client hello retry configs after accepting encrypted client hello")
   606  		}
   607  	}
   608  
   609  	return nil
   610  }
   611  
   612  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
   613  	c := hs.c
   614  
   615  	// Either a PSK or a certificate is always used, but not both.
   616  	// See RFC 8446, Section 4.1.1.
   617  	if hs.usingPSK {
   618  		// Make sure the connection is still being verified whether or not this
   619  		// is a resumption. Resumptions currently don't reverify certificates so
   620  		// they don't call verifyServerCertificate. See Issue 31641.
   621  		if c.config.VerifyConnection != nil {
   622  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   623  				c.sendAlert(alertBadCertificate)
   624  				return err
   625  			}
   626  		}
   627  		return nil
   628  	}
   629  
   630  	msg, err := c.readHandshake(hs.transcript)
   631  	if err != nil {
   632  		return err
   633  	}
   634  
   635  	certReq, ok := msg.(*certificateRequestMsgTLS13)
   636  	if ok {
   637  		hs.certReq = certReq
   638  
   639  		msg, err = c.readHandshake(hs.transcript)
   640  		if err != nil {
   641  			return err
   642  		}
   643  	}
   644  
   645  	certMsg, ok := msg.(*certificateMsgTLS13)
   646  	if !ok {
   647  		c.sendAlert(alertUnexpectedMessage)
   648  		return unexpectedMessageError(certMsg, msg)
   649  	}
   650  	if len(certMsg.certificate.Certificate) == 0 {
   651  		c.sendAlert(alertDecodeError)
   652  		return errors.New("tls: received empty certificates message")
   653  	}
   654  
   655  	c.scts = certMsg.certificate.SignedCertificateTimestamps
   656  	c.ocspResponse = certMsg.certificate.OCSPStaple
   657  
   658  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
   659  		return err
   660  	}
   661  
   662  	// certificateVerifyMsg is included in the transcript, but not until
   663  	// after we verify the handshake signature, since the state before
   664  	// this message was sent is used.
   665  	msg, err = c.readHandshake(nil)
   666  	if err != nil {
   667  		return err
   668  	}
   669  
   670  	certVerify, ok := msg.(*certificateVerifyMsg)
   671  	if !ok {
   672  		c.sendAlert(alertUnexpectedMessage)
   673  		return unexpectedMessageError(certVerify, msg)
   674  	}
   675  
   676  	// See RFC 8446, Section 4.4.3.
   677  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
   678  		c.sendAlert(alertIllegalParameter)
   679  		return errors.New("tls: certificate used with invalid signature algorithm")
   680  	}
   681  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   682  	if err != nil {
   683  		return c.sendAlert(alertInternalError)
   684  	}
   685  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   686  		c.sendAlert(alertIllegalParameter)
   687  		return errors.New("tls: certificate used with invalid signature algorithm")
   688  	}
   689  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   690  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   691  		sigHash, signed, certVerify.signature); err != nil {
   692  		c.sendAlert(alertDecryptError)
   693  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
   694  	}
   695  
   696  	if err := transcriptMsg(certVerify, hs.transcript); err != nil {
   697  		return err
   698  	}
   699  
   700  	return nil
   701  }
   702  
   703  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
   704  	c := hs.c
   705  
   706  	// finishedMsg is included in the transcript, but not until after we
   707  	// check the client version, since the state before this message was
   708  	// sent is used during verification.
   709  	msg, err := c.readHandshake(nil)
   710  	if err != nil {
   711  		return err
   712  	}
   713  
   714  	finished, ok := msg.(*finishedMsg)
   715  	if !ok {
   716  		c.sendAlert(alertUnexpectedMessage)
   717  		return unexpectedMessageError(finished, msg)
   718  	}
   719  
   720  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   721  	if !hmac.Equal(expectedMAC, finished.verifyData) {
   722  		c.sendAlert(alertDecryptError)
   723  		return errors.New("tls: invalid server finished hash")
   724  	}
   725  
   726  	if err := transcriptMsg(finished, hs.transcript); err != nil {
   727  		return err
   728  	}
   729  
   730  	// Derive secrets that take context through the server Finished.
   731  
   732  	hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
   733  	serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
   734  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
   735  
   736  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
   737  	if err != nil {
   738  		c.sendAlert(alertInternalError)
   739  		return err
   740  	}
   741  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
   742  	if err != nil {
   743  		c.sendAlert(alertInternalError)
   744  		return err
   745  	}
   746  
   747  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   748  
   749  	return nil
   750  }
   751  
   752  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
   753  	c := hs.c
   754  
   755  	if hs.certReq == nil {
   756  		return nil
   757  	}
   758  
   759  	if hs.echContext != nil && hs.echContext.echRejected {
   760  		if _, err := hs.c.writeHandshakeRecord(&certificateMsgTLS13{}, hs.transcript); err != nil {
   761  			return err
   762  		}
   763  		return nil
   764  	}
   765  
   766  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
   767  		AcceptableCAs:    hs.certReq.certificateAuthorities,
   768  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
   769  		Version:          c.vers,
   770  		ctx:              hs.ctx,
   771  	})
   772  	if err != nil {
   773  		return err
   774  	}
   775  
   776  	certMsg := new(certificateMsgTLS13)
   777  
   778  	certMsg.certificate = *cert
   779  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   780  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   781  
   782  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
   783  		return err
   784  	}
   785  
   786  	// If we sent an empty certificate message, skip the CertificateVerify.
   787  	if len(cert.Certificate) == 0 {
   788  		return nil
   789  	}
   790  
   791  	certVerifyMsg := new(certificateVerifyMsg)
   792  	certVerifyMsg.hasSignatureAlgorithm = true
   793  
   794  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
   795  	if err != nil {
   796  		// getClientCertificate returned a certificate incompatible with the
   797  		// CertificateRequestInfo supported signature algorithms.
   798  		c.sendAlert(alertHandshakeFailure)
   799  		return err
   800  	}
   801  
   802  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   803  	if err != nil {
   804  		return c.sendAlert(alertInternalError)
   805  	}
   806  
   807  	signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   808  	signOpts := crypto.SignerOpts(sigHash)
   809  	if sigType == signatureRSAPSS {
   810  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   811  	}
   812  	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   813  	if err != nil {
   814  		c.sendAlert(alertInternalError)
   815  		return errors.New("tls: failed to sign handshake: " + err.Error())
   816  	}
   817  	certVerifyMsg.signature = sig
   818  
   819  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
   820  		return err
   821  	}
   822  
   823  	return nil
   824  }
   825  
   826  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   827  	c := hs.c
   828  
   829  	finished := &finishedMsg{
   830  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   831  	}
   832  
   833  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
   834  		return err
   835  	}
   836  
   837  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
   838  
   839  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   840  		c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
   841  	}
   842  
   843  	if c.quic != nil {
   844  		if c.hand.Len() != 0 {
   845  			c.sendAlert(alertUnexpectedMessage)
   846  		}
   847  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
   848  	}
   849  
   850  	return nil
   851  }
   852  
   853  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   854  	if !c.isClient {
   855  		c.sendAlert(alertUnexpectedMessage)
   856  		return errors.New("tls: received new session ticket from a client")
   857  	}
   858  
   859  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   860  		return nil
   861  	}
   862  
   863  	// See RFC 8446, Section 4.6.1.
   864  	if msg.lifetime == 0 {
   865  		return nil
   866  	}
   867  	lifetime := time.Duration(msg.lifetime) * time.Second
   868  	if lifetime > maxSessionTicketLifetime {
   869  		c.sendAlert(alertIllegalParameter)
   870  		return errors.New("tls: received a session ticket with invalid lifetime")
   871  	}
   872  
   873  	// RFC 9001, Section 4.6.1
   874  	if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
   875  		c.sendAlert(alertIllegalParameter)
   876  		return errors.New("tls: invalid early data for QUIC connection")
   877  	}
   878  
   879  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   880  	if cipherSuite == nil || c.resumptionSecret == nil {
   881  		return c.sendAlert(alertInternalError)
   882  	}
   883  
   884  	psk := tls13.ExpandLabel(cipherSuite.hash.New, c.resumptionSecret, "resumption",
   885  		msg.nonce, cipherSuite.hash.Size())
   886  
   887  	session := c.sessionState()
   888  	session.secret = psk
   889  	session.useBy = uint64(c.config.time().Add(lifetime).Unix())
   890  	session.ageAdd = msg.ageAdd
   891  	session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1
   892  	session.ticket = msg.label
   893  	if c.quic != nil && c.quic.enableSessionEvents {
   894  		c.quicStoreSession(session)
   895  		return nil
   896  	}
   897  	cs := &ClientSessionState{session: session}
   898  	if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
   899  		c.config.ClientSessionCache.Put(cacheKey, cs)
   900  	}
   901  
   902  	return nil
   903  }
   904  

View as plain text