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

View as plain text