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(alertIllegalParameter)
   201  		return errors.New("tls: server selected unsupported compression format")
   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.activeCertHandles = hs.session.activeCertHandles
   470  	c.verifiedChains = hs.session.verifiedChains
   471  	c.ocspResponse = hs.session.ocspResponse
   472  	c.scts = hs.session.scts
   473  	return nil
   474  }
   475  
   476  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
   477  	c := hs.c
   478  
   479  	ecdhePeerData := hs.serverHello.serverShare.data
   480  	if hs.serverHello.serverShare.group == X25519MLKEM768 {
   481  		if len(ecdhePeerData) != mlkem.CiphertextSize768+x25519PublicKeySize {
   482  			c.sendAlert(alertIllegalParameter)
   483  			return errors.New("tls: invalid server X25519MLKEM768 key share")
   484  		}
   485  		ecdhePeerData = hs.serverHello.serverShare.data[mlkem.CiphertextSize768:]
   486  	}
   487  	peerKey, err := hs.keyShareKeys.ecdhe.Curve().NewPublicKey(ecdhePeerData)
   488  	if err != nil {
   489  		c.sendAlert(alertIllegalParameter)
   490  		return errors.New("tls: invalid server key share")
   491  	}
   492  	sharedKey, err := hs.keyShareKeys.ecdhe.ECDH(peerKey)
   493  	if err != nil {
   494  		c.sendAlert(alertIllegalParameter)
   495  		return errors.New("tls: invalid server key share")
   496  	}
   497  	if hs.serverHello.serverShare.group == X25519MLKEM768 {
   498  		if hs.keyShareKeys.mlkem == nil {
   499  			return c.sendAlert(alertInternalError)
   500  		}
   501  		ciphertext := hs.serverHello.serverShare.data[:mlkem.CiphertextSize768]
   502  		mlkemShared, err := hs.keyShareKeys.mlkem.Decapsulate(ciphertext)
   503  		if err != nil {
   504  			c.sendAlert(alertIllegalParameter)
   505  			return errors.New("tls: invalid X25519MLKEM768 server key share")
   506  		}
   507  		sharedKey = append(mlkemShared, sharedKey...)
   508  	}
   509  	c.curveID = hs.serverHello.serverShare.group
   510  
   511  	earlySecret := hs.earlySecret
   512  	if !hs.usingPSK {
   513  		earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
   514  	}
   515  
   516  	handshakeSecret := earlySecret.HandshakeSecret(sharedKey)
   517  
   518  	clientSecret := handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
   519  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
   520  	serverSecret := handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
   521  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
   522  
   523  	if c.quic != nil {
   524  		if c.hand.Len() != 0 {
   525  			c.sendAlert(alertUnexpectedMessage)
   526  		}
   527  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
   528  		c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
   529  	}
   530  
   531  	err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
   532  	if err != nil {
   533  		c.sendAlert(alertInternalError)
   534  		return err
   535  	}
   536  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
   537  	if err != nil {
   538  		c.sendAlert(alertInternalError)
   539  		return err
   540  	}
   541  
   542  	hs.masterSecret = handshakeSecret.MasterSecret()
   543  
   544  	return nil
   545  }
   546  
   547  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
   548  	c := hs.c
   549  
   550  	msg, err := c.readHandshake(hs.transcript)
   551  	if err != nil {
   552  		return err
   553  	}
   554  
   555  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
   556  	if !ok {
   557  		c.sendAlert(alertUnexpectedMessage)
   558  		return unexpectedMessageError(encryptedExtensions, msg)
   559  	}
   560  
   561  	if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
   562  		// RFC 8446 specifies that no_application_protocol is sent by servers, but
   563  		// does not specify how clients handle the selection of an incompatible protocol.
   564  		// RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
   565  		// in this case. Always sending no_application_protocol seems reasonable.
   566  		c.sendAlert(alertNoApplicationProtocol)
   567  		return err
   568  	}
   569  	c.clientProtocol = encryptedExtensions.alpnProtocol
   570  
   571  	if c.quic != nil {
   572  		if encryptedExtensions.quicTransportParameters == nil {
   573  			// RFC 9001 Section 8.2.
   574  			c.sendAlert(alertMissingExtension)
   575  			return errors.New("tls: server did not send a quic_transport_parameters extension")
   576  		}
   577  		c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
   578  	} else {
   579  		if encryptedExtensions.quicTransportParameters != nil {
   580  			c.sendAlert(alertUnsupportedExtension)
   581  			return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
   582  		}
   583  	}
   584  
   585  	if !hs.hello.earlyData && encryptedExtensions.earlyData {
   586  		c.sendAlert(alertUnsupportedExtension)
   587  		return errors.New("tls: server sent an unexpected early_data extension")
   588  	}
   589  	if hs.hello.earlyData && !encryptedExtensions.earlyData {
   590  		c.quicRejectedEarlyData()
   591  	}
   592  	if encryptedExtensions.earlyData {
   593  		if hs.session.cipherSuite != c.cipherSuite {
   594  			c.sendAlert(alertHandshakeFailure)
   595  			return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
   596  		}
   597  		if hs.session.alpnProtocol != c.clientProtocol {
   598  			c.sendAlert(alertHandshakeFailure)
   599  			return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
   600  		}
   601  	}
   602  	if hs.echContext != nil {
   603  		if hs.echContext.echRejected {
   604  			hs.echContext.retryConfigs = encryptedExtensions.echRetryConfigs
   605  		} else if encryptedExtensions.echRetryConfigs != nil {
   606  			c.sendAlert(alertUnsupportedExtension)
   607  			return errors.New("tls: server sent encrypted client hello retry configs after accepting encrypted client hello")
   608  		}
   609  	}
   610  
   611  	return nil
   612  }
   613  
   614  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
   615  	c := hs.c
   616  
   617  	// Either a PSK or a certificate is always used, but not both.
   618  	// See RFC 8446, Section 4.1.1.
   619  	if hs.usingPSK {
   620  		// Make sure the connection is still being verified whether or not this
   621  		// is a resumption. Resumptions currently don't reverify certificates so
   622  		// they don't call verifyServerCertificate. See Issue 31641.
   623  		if c.config.VerifyConnection != nil {
   624  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   625  				c.sendAlert(alertBadCertificate)
   626  				return err
   627  			}
   628  		}
   629  		return nil
   630  	}
   631  
   632  	msg, err := c.readHandshake(hs.transcript)
   633  	if err != nil {
   634  		return err
   635  	}
   636  
   637  	certReq, ok := msg.(*certificateRequestMsgTLS13)
   638  	if ok {
   639  		hs.certReq = certReq
   640  
   641  		msg, err = c.readHandshake(hs.transcript)
   642  		if err != nil {
   643  			return err
   644  		}
   645  	}
   646  
   647  	certMsg, ok := msg.(*certificateMsgTLS13)
   648  	if !ok {
   649  		c.sendAlert(alertUnexpectedMessage)
   650  		return unexpectedMessageError(certMsg, msg)
   651  	}
   652  	if len(certMsg.certificate.Certificate) == 0 {
   653  		c.sendAlert(alertDecodeError)
   654  		return errors.New("tls: received empty certificates message")
   655  	}
   656  
   657  	c.scts = certMsg.certificate.SignedCertificateTimestamps
   658  	c.ocspResponse = certMsg.certificate.OCSPStaple
   659  
   660  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
   661  		return err
   662  	}
   663  
   664  	// certificateVerifyMsg is included in the transcript, but not until
   665  	// after we verify the handshake signature, since the state before
   666  	// this message was sent is used.
   667  	msg, err = c.readHandshake(nil)
   668  	if err != nil {
   669  		return err
   670  	}
   671  
   672  	certVerify, ok := msg.(*certificateVerifyMsg)
   673  	if !ok {
   674  		c.sendAlert(alertUnexpectedMessage)
   675  		return unexpectedMessageError(certVerify, msg)
   676  	}
   677  
   678  	// See RFC 8446, Section 4.4.3.
   679  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
   680  		c.sendAlert(alertIllegalParameter)
   681  		return errors.New("tls: certificate used with invalid signature algorithm")
   682  	}
   683  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   684  	if err != nil {
   685  		return c.sendAlert(alertInternalError)
   686  	}
   687  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   688  		c.sendAlert(alertIllegalParameter)
   689  		return errors.New("tls: certificate used with invalid signature algorithm")
   690  	}
   691  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   692  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   693  		sigHash, signed, certVerify.signature); err != nil {
   694  		c.sendAlert(alertDecryptError)
   695  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
   696  	}
   697  
   698  	if err := transcriptMsg(certVerify, hs.transcript); err != nil {
   699  		return err
   700  	}
   701  
   702  	return nil
   703  }
   704  
   705  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
   706  	c := hs.c
   707  
   708  	// finishedMsg is included in the transcript, but not until after we
   709  	// check the client version, since the state before this message was
   710  	// sent is used during verification.
   711  	msg, err := c.readHandshake(nil)
   712  	if err != nil {
   713  		return err
   714  	}
   715  
   716  	finished, ok := msg.(*finishedMsg)
   717  	if !ok {
   718  		c.sendAlert(alertUnexpectedMessage)
   719  		return unexpectedMessageError(finished, msg)
   720  	}
   721  
   722  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   723  	if !hmac.Equal(expectedMAC, finished.verifyData) {
   724  		c.sendAlert(alertDecryptError)
   725  		return errors.New("tls: invalid server finished hash")
   726  	}
   727  
   728  	if err := transcriptMsg(finished, hs.transcript); err != nil {
   729  		return err
   730  	}
   731  
   732  	// Derive secrets that take context through the server Finished.
   733  
   734  	hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
   735  	serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
   736  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
   737  
   738  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
   739  	if err != nil {
   740  		c.sendAlert(alertInternalError)
   741  		return err
   742  	}
   743  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
   744  	if err != nil {
   745  		c.sendAlert(alertInternalError)
   746  		return err
   747  	}
   748  
   749  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   750  
   751  	return nil
   752  }
   753  
   754  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
   755  	c := hs.c
   756  
   757  	if hs.certReq == nil {
   758  		return nil
   759  	}
   760  
   761  	if hs.echContext != nil && hs.echContext.echRejected {
   762  		if _, err := hs.c.writeHandshakeRecord(&certificateMsgTLS13{}, hs.transcript); err != nil {
   763  			return err
   764  		}
   765  		return nil
   766  	}
   767  
   768  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
   769  		AcceptableCAs:    hs.certReq.certificateAuthorities,
   770  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
   771  		Version:          c.vers,
   772  		ctx:              hs.ctx,
   773  	})
   774  	if err != nil {
   775  		return err
   776  	}
   777  
   778  	certMsg := new(certificateMsgTLS13)
   779  
   780  	certMsg.certificate = *cert
   781  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   782  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   783  
   784  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
   785  		return err
   786  	}
   787  
   788  	// If we sent an empty certificate message, skip the CertificateVerify.
   789  	if len(cert.Certificate) == 0 {
   790  		return nil
   791  	}
   792  
   793  	certVerifyMsg := new(certificateVerifyMsg)
   794  	certVerifyMsg.hasSignatureAlgorithm = true
   795  
   796  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
   797  	if err != nil {
   798  		// getClientCertificate returned a certificate incompatible with the
   799  		// CertificateRequestInfo supported signature algorithms.
   800  		c.sendAlert(alertHandshakeFailure)
   801  		return err
   802  	}
   803  
   804  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   805  	if err != nil {
   806  		return c.sendAlert(alertInternalError)
   807  	}
   808  
   809  	signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   810  	signOpts := crypto.SignerOpts(sigHash)
   811  	if sigType == signatureRSAPSS {
   812  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   813  	}
   814  	sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   815  	if err != nil {
   816  		c.sendAlert(alertInternalError)
   817  		return errors.New("tls: failed to sign handshake: " + err.Error())
   818  	}
   819  	certVerifyMsg.signature = sig
   820  
   821  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
   822  		return err
   823  	}
   824  
   825  	return nil
   826  }
   827  
   828  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   829  	c := hs.c
   830  
   831  	finished := &finishedMsg{
   832  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   833  	}
   834  
   835  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
   836  		return err
   837  	}
   838  
   839  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
   840  
   841  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   842  		c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
   843  	}
   844  
   845  	if c.quic != nil {
   846  		if c.hand.Len() != 0 {
   847  			c.sendAlert(alertUnexpectedMessage)
   848  		}
   849  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
   850  	}
   851  
   852  	return nil
   853  }
   854  
   855  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   856  	if !c.isClient {
   857  		c.sendAlert(alertUnexpectedMessage)
   858  		return errors.New("tls: received new session ticket from a client")
   859  	}
   860  
   861  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   862  		return nil
   863  	}
   864  
   865  	// See RFC 8446, Section 4.6.1.
   866  	if msg.lifetime == 0 {
   867  		return nil
   868  	}
   869  	lifetime := time.Duration(msg.lifetime) * time.Second
   870  	if lifetime > maxSessionTicketLifetime {
   871  		c.sendAlert(alertIllegalParameter)
   872  		return errors.New("tls: received a session ticket with invalid lifetime")
   873  	}
   874  
   875  	if len(msg.label) == 0 {
   876  		c.sendAlert(alertDecodeError)
   877  		return errors.New("tls: received a session ticket with empty opaque ticket label")
   878  	}
   879  
   880  	// RFC 9001, Section 4.6.1
   881  	if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
   882  		c.sendAlert(alertIllegalParameter)
   883  		return errors.New("tls: invalid early data for QUIC connection")
   884  	}
   885  
   886  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   887  	if cipherSuite == nil || c.resumptionSecret == nil {
   888  		return c.sendAlert(alertInternalError)
   889  	}
   890  
   891  	psk := tls13.ExpandLabel(cipherSuite.hash.New, c.resumptionSecret, "resumption",
   892  		msg.nonce, cipherSuite.hash.Size())
   893  
   894  	session := c.sessionState()
   895  	session.secret = psk
   896  	session.useBy = uint64(c.config.time().Add(lifetime).Unix())
   897  	session.ageAdd = msg.ageAdd
   898  	session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1
   899  	session.ticket = msg.label
   900  	if c.quic != nil && c.quic.enableSessionEvents {
   901  		c.quicStoreSession(session)
   902  		return nil
   903  	}
   904  	cs := &ClientSessionState{session: session}
   905  	if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
   906  		c.config.ClientSessionCache.Put(cacheKey, cs)
   907  	}
   908  
   909  	return nil
   910  }
   911  

View as plain text