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

View as plain text