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

View as plain text