Source file src/crypto/tls/handshake_client_tls13.go

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"crypto"
    11  	"crypto/hkdf"
    12  	"crypto/hmac"
    13  	"crypto/internal/fips140/tls13"
    14  	"crypto/rsa"
    15  	"crypto/subtle"
    16  	"errors"
    17  	"hash"
    18  	"slices"
    19  	"time"
    20  )
    21  
    22  type clientHandshakeStateTLS13 struct {
    23  	c            *Conn
    24  	ctx          context.Context
    25  	serverHello  *serverHelloMsg
    26  	hello        *clientHelloMsg
    27  	keyShareKeys *keySharePrivateKeys
    28  
    29  	session     *SessionState
    30  	earlySecret *tls13.EarlySecret
    31  	binderKey   []byte
    32  
    33  	certReq       *certificateRequestMsgTLS13
    34  	usingPSK      bool
    35  	sentDummyCCS  bool
    36  	suite         *cipherSuiteTLS13
    37  	transcript    hash.Hash
    38  	masterSecret  *tls13.MasterSecret
    39  	trafficSecret []byte // client_application_traffic_secret_0
    40  
    41  	echContext *echClientContext
    42  }
    43  
    44  // handshake requires hs.c, hs.hello, hs.serverHello, hs.keyShareKeys, and,
    45  // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
    46  func (hs *clientHandshakeStateTLS13) handshake() error {
    47  	c := hs.c
    48  
    49  	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
    50  	// sections 4.1.2 and 4.1.3.
    51  	if c.handshakes > 0 {
    52  		c.sendAlert(alertProtocolVersion)
    53  		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
    54  	}
    55  
    56  	// Consistency check on the presence of a keyShare and its parameters.
    57  	if hs.keyShareKeys == nil || (hs.keyShareKeys.ecdhe == nil && hs.keyShareKeys.mlkem == nil) ||
    58  		len(hs.hello.keyShares) == 0 {
    59  		return c.sendAlert(alertInternalError)
    60  	}
    61  
    62  	if err := hs.checkServerHelloOrHRR(); err != nil {
    63  		return err
    64  	}
    65  
    66  	hs.transcript = hs.suite.hash.New()
    67  
    68  	if err := transcriptMsg(hs.hello, hs.transcript); err != nil {
    69  		return err
    70  	}
    71  
    72  	if hs.echContext != nil {
    73  		hs.echContext.innerTranscript = hs.suite.hash.New()
    74  		if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
    75  			return err
    76  		}
    77  	}
    78  
    79  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
    80  		if err := hs.sendDummyChangeCipherSpec(); err != nil {
    81  			return err
    82  		}
    83  		if err := hs.processHelloRetryRequest(); err != nil {
    84  			return err
    85  		}
    86  	}
    87  
    88  	if hs.echContext != nil {
    89  		confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
    90  		confTranscript.Write(hs.serverHello.original[:30])
    91  		confTranscript.Write(make([]byte, 8))
    92  		confTranscript.Write(hs.serverHello.original[38:])
    93  		h := hs.suite.hash.New
    94  		prk, err := hkdf.Extract(h, hs.echContext.innerHello.random, nil)
    95  		if err != nil {
    96  			c.sendAlert(alertInternalError)
    97  			return err
    98  		}
    99  		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  		ke, err := keyExchangeForCurveID(curveID)
   324  		if err != nil {
   325  			c.sendAlert(alertInternalError)
   326  			return errors.New("tls: internal error: supportsCurve accepted unimplemented curve")
   327  		}
   328  		hs.keyShareKeys, hello.keyShares, err = ke.keyShares(c.config.rand())
   329  		if err != nil {
   330  			c.sendAlert(alertInternalError)
   331  			return err
   332  		}
   333  		// Do not send the fallback ECDH key share in a HRR response.
   334  		hello.keyShares = hello.keyShares[:1]
   335  	}
   336  
   337  	if len(hello.pskIdentities) > 0 {
   338  		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   339  		if pskSuite == nil {
   340  			return c.sendAlert(alertInternalError)
   341  		}
   342  		if pskSuite.hash == hs.suite.hash {
   343  			// Update binders and obfuscated_ticket_age.
   344  			ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0))
   345  			hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd
   346  
   347  			transcript := hs.suite.hash.New()
   348  			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   349  			transcript.Write(chHash)
   350  			if err := transcriptMsg(hs.serverHello, transcript); err != nil {
   351  				return err
   352  			}
   353  
   354  			if err := computeAndUpdatePSK(hello, hs.binderKey, transcript, hs.suite.finishedHash); err != nil {
   355  				return err
   356  			}
   357  		} else {
   358  			// Server selected a cipher suite incompatible with the PSK.
   359  			hello.pskIdentities = nil
   360  			hello.pskBinders = nil
   361  		}
   362  	}
   363  
   364  	if hello.earlyData {
   365  		hello.earlyData = false
   366  		c.quicRejectedEarlyData()
   367  	}
   368  
   369  	if isInnerHello {
   370  		// Any extensions which have changed in hello, but are mirrored in the
   371  		// outer hello and compressed, need to be copied to the outer hello, so
   372  		// they can be properly decompressed by the server. For now, the only
   373  		// extension which may have changed is keyShares.
   374  		hs.hello.keyShares = hello.keyShares
   375  		hs.echContext.innerHello = hello
   376  		if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
   377  			return err
   378  		}
   379  
   380  		if err := computeAndUpdateOuterECHExtension(hs.hello, hs.echContext.innerHello, hs.echContext, false); err != nil {
   381  			return err
   382  		}
   383  	} else {
   384  		hs.hello = hello
   385  	}
   386  
   387  	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
   388  		return err
   389  	}
   390  
   391  	// serverHelloMsg is not included in the transcript
   392  	msg, err := c.readHandshake(nil)
   393  	if err != nil {
   394  		return err
   395  	}
   396  
   397  	serverHello, ok := msg.(*serverHelloMsg)
   398  	if !ok {
   399  		c.sendAlert(alertUnexpectedMessage)
   400  		return unexpectedMessageError(serverHello, msg)
   401  	}
   402  	hs.serverHello = serverHello
   403  
   404  	if err := hs.checkServerHelloOrHRR(); err != nil {
   405  		return err
   406  	}
   407  
   408  	c.didHRR = true
   409  	return nil
   410  }
   411  
   412  func (hs *clientHandshakeStateTLS13) processServerHello() error {
   413  	c := hs.c
   414  
   415  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
   416  		c.sendAlert(alertUnexpectedMessage)
   417  		return errors.New("tls: server sent two HelloRetryRequest messages")
   418  	}
   419  
   420  	if len(hs.serverHello.cookie) != 0 {
   421  		c.sendAlert(alertUnsupportedExtension)
   422  		return errors.New("tls: server sent a cookie in a normal ServerHello")
   423  	}
   424  
   425  	if hs.serverHello.selectedGroup != 0 {
   426  		c.sendAlert(alertDecodeError)
   427  		return errors.New("tls: malformed key_share extension")
   428  	}
   429  
   430  	if hs.serverHello.serverShare.group == 0 {
   431  		c.sendAlert(alertIllegalParameter)
   432  		return errors.New("tls: server did not send a key share")
   433  	}
   434  	if !slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
   435  		return ks.group == hs.serverHello.serverShare.group
   436  	}) {
   437  		c.sendAlert(alertIllegalParameter)
   438  		return errors.New("tls: server selected unsupported group")
   439  	}
   440  
   441  	if !hs.serverHello.selectedIdentityPresent {
   442  		return nil
   443  	}
   444  
   445  	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
   446  		c.sendAlert(alertIllegalParameter)
   447  		return errors.New("tls: server selected an invalid PSK")
   448  	}
   449  
   450  	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
   451  		return c.sendAlert(alertInternalError)
   452  	}
   453  	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
   454  	if pskSuite == nil {
   455  		return c.sendAlert(alertInternalError)
   456  	}
   457  	if pskSuite.hash != hs.suite.hash {
   458  		c.sendAlert(alertIllegalParameter)
   459  		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
   460  	}
   461  
   462  	hs.usingPSK = true
   463  	c.didResume = true
   464  	c.peerCertificates = hs.session.peerCertificates
   465  	c.verifiedChains = hs.session.verifiedChains
   466  	c.ocspResponse = hs.session.ocspResponse
   467  	c.scts = hs.session.scts
   468  	return nil
   469  }
   470  
   471  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
   472  	c := hs.c
   473  
   474  	ke, err := keyExchangeForCurveID(hs.serverHello.serverShare.group)
   475  	if err != nil {
   476  		c.sendAlert(alertInternalError)
   477  		return err
   478  	}
   479  	sharedKey, err := ke.clientSharedSecret(hs.keyShareKeys, hs.serverHello.serverShare.data)
   480  	if err != nil {
   481  		c.sendAlert(alertIllegalParameter)
   482  		return errors.New("tls: invalid server key share")
   483  	}
   484  	c.curveID = hs.serverHello.serverShare.group
   485  
   486  	earlySecret := hs.earlySecret
   487  	if !hs.usingPSK {
   488  		earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
   489  	}
   490  
   491  	handshakeSecret := earlySecret.HandshakeSecret(sharedKey)
   492  
   493  	clientSecret := handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
   494  	c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
   495  	serverSecret := handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
   496  	if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret, false); err != nil {
   497  		return err
   498  	}
   499  
   500  	if c.quic != nil {
   501  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
   502  		if err := c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret); err != nil {
   503  			return err
   504  		}
   505  	}
   506  
   507  	err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
   508  	if err != nil {
   509  		c.sendAlert(alertInternalError)
   510  		return err
   511  	}
   512  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
   513  	if err != nil {
   514  		c.sendAlert(alertInternalError)
   515  		return err
   516  	}
   517  
   518  	hs.masterSecret = handshakeSecret.MasterSecret()
   519  
   520  	return nil
   521  }
   522  
   523  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
   524  	c := hs.c
   525  
   526  	msg, err := c.readHandshake(hs.transcript)
   527  	if err != nil {
   528  		return err
   529  	}
   530  
   531  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
   532  	if !ok {
   533  		c.sendAlert(alertUnexpectedMessage)
   534  		return unexpectedMessageError(encryptedExtensions, msg)
   535  	}
   536  
   537  	if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
   538  		// RFC 8446 specifies that no_application_protocol is sent by servers, but
   539  		// does not specify how clients handle the selection of an incompatible protocol.
   540  		// RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
   541  		// in this case. Always sending no_application_protocol seems reasonable.
   542  		c.sendAlert(alertNoApplicationProtocol)
   543  		return err
   544  	}
   545  	c.clientProtocol = encryptedExtensions.alpnProtocol
   546  
   547  	if c.quic != nil {
   548  		if encryptedExtensions.quicTransportParameters == nil {
   549  			// RFC 9001 Section 8.2.
   550  			c.sendAlert(alertMissingExtension)
   551  			return errors.New("tls: server did not send a quic_transport_parameters extension")
   552  		}
   553  		c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
   554  	} else {
   555  		if encryptedExtensions.quicTransportParameters != nil {
   556  			c.sendAlert(alertUnsupportedExtension)
   557  			return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
   558  		}
   559  	}
   560  
   561  	if !hs.hello.earlyData && encryptedExtensions.earlyData {
   562  		c.sendAlert(alertUnsupportedExtension)
   563  		return errors.New("tls: server sent an unexpected early_data extension")
   564  	}
   565  	if hs.hello.earlyData && !encryptedExtensions.earlyData {
   566  		c.quicRejectedEarlyData()
   567  	}
   568  	if encryptedExtensions.earlyData {
   569  		if hs.session.cipherSuite != c.cipherSuite {
   570  			c.sendAlert(alertHandshakeFailure)
   571  			return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
   572  		}
   573  		if hs.session.alpnProtocol != c.clientProtocol {
   574  			c.sendAlert(alertHandshakeFailure)
   575  			return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
   576  		}
   577  	}
   578  	if hs.echContext != nil {
   579  		if hs.echContext.echRejected {
   580  			hs.echContext.retryConfigs = encryptedExtensions.echRetryConfigs
   581  		} else if encryptedExtensions.echRetryConfigs != nil {
   582  			c.sendAlert(alertUnsupportedExtension)
   583  			return errors.New("tls: server sent encrypted client hello retry configs after accepting encrypted client hello")
   584  		}
   585  	}
   586  
   587  	return nil
   588  }
   589  
   590  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
   591  	c := hs.c
   592  
   593  	// Either a PSK or a certificate is always used, but not both.
   594  	// See RFC 8446, Section 4.1.1.
   595  	if hs.usingPSK {
   596  		// Make sure the connection is still being verified whether or not this
   597  		// is a resumption. Resumptions currently don't reverify certificates so
   598  		// they don't call verifyServerCertificate. See Issue 31641.
   599  		if c.config.VerifyConnection != nil {
   600  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   601  				c.sendAlert(alertBadCertificate)
   602  				return err
   603  			}
   604  		}
   605  		return nil
   606  	}
   607  
   608  	msg, err := c.readHandshake(hs.transcript)
   609  	if err != nil {
   610  		return err
   611  	}
   612  
   613  	certReq, ok := msg.(*certificateRequestMsgTLS13)
   614  	if ok {
   615  		hs.certReq = certReq
   616  
   617  		msg, err = c.readHandshake(hs.transcript)
   618  		if err != nil {
   619  			return err
   620  		}
   621  	}
   622  
   623  	certMsg, ok := msg.(*certificateMsgTLS13)
   624  	if !ok {
   625  		c.sendAlert(alertUnexpectedMessage)
   626  		return unexpectedMessageError(certMsg, msg)
   627  	}
   628  	if len(certMsg.certificate.Certificate) == 0 {
   629  		c.sendAlert(alertDecodeError)
   630  		return errors.New("tls: received empty certificates message")
   631  	}
   632  
   633  	c.scts = certMsg.certificate.SignedCertificateTimestamps
   634  	c.ocspResponse = certMsg.certificate.OCSPStaple
   635  
   636  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
   637  		return err
   638  	}
   639  
   640  	// certificateVerifyMsg is included in the transcript, but not until
   641  	// after we verify the handshake signature, since the state before
   642  	// this message was sent is used.
   643  	msg, err = c.readHandshake(nil)
   644  	if err != nil {
   645  		return err
   646  	}
   647  
   648  	certVerify, ok := msg.(*certificateVerifyMsg)
   649  	if !ok {
   650  		c.sendAlert(alertUnexpectedMessage)
   651  		return unexpectedMessageError(certVerify, msg)
   652  	}
   653  
   654  	// See RFC 8446, Section 4.4.3.
   655  	// We don't use hs.hello.supportedSignatureAlgorithms because it might
   656  	// include PKCS#1 v1.5 and SHA-1 if the ClientHello also supported TLS 1.2.
   657  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers, c.vers)) ||
   658  		!isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, signatureSchemesForPublicKey(c.vers, c.peerCertificates[0].PublicKey)) {
   659  		c.sendAlert(alertIllegalParameter)
   660  		return errors.New("tls: certificate used with invalid signature algorithm")
   661  	}
   662  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   663  	if err != nil {
   664  		return c.sendAlert(alertInternalError)
   665  	}
   666  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   667  		return c.sendAlert(alertInternalError)
   668  	}
   669  	signed := signedMessage(serverSignatureContext, hs.transcript)
   670  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   671  		sigHash, signed, certVerify.signature); err != nil {
   672  		c.sendAlert(alertDecryptError)
   673  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
   674  	}
   675  	c.peerSigAlg = certVerify.signatureAlgorithm
   676  
   677  	if err := transcriptMsg(certVerify, hs.transcript); err != nil {
   678  		return err
   679  	}
   680  
   681  	return nil
   682  }
   683  
   684  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
   685  	c := hs.c
   686  
   687  	// finishedMsg is included in the transcript, but not until after we
   688  	// check the client version, since the state before this message was
   689  	// sent is used during verification.
   690  	msg, err := c.readHandshake(nil)
   691  	if err != nil {
   692  		return err
   693  	}
   694  
   695  	finished, ok := msg.(*finishedMsg)
   696  	if !ok {
   697  		c.sendAlert(alertUnexpectedMessage)
   698  		return unexpectedMessageError(finished, msg)
   699  	}
   700  
   701  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   702  	if !hmac.Equal(expectedMAC, finished.verifyData) {
   703  		c.sendAlert(alertDecryptError)
   704  		return errors.New("tls: invalid server finished hash")
   705  	}
   706  
   707  	if err := transcriptMsg(finished, hs.transcript); err != nil {
   708  		return err
   709  	}
   710  
   711  	// Derive secrets that take context through the server Finished.
   712  
   713  	hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
   714  	serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
   715  	if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret, false); err != nil {
   716  		return err
   717  	}
   718  
   719  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
   720  	if err != nil {
   721  		c.sendAlert(alertInternalError)
   722  		return err
   723  	}
   724  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
   725  	if err != nil {
   726  		c.sendAlert(alertInternalError)
   727  		return err
   728  	}
   729  
   730  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   731  
   732  	return nil
   733  }
   734  
   735  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
   736  	c := hs.c
   737  
   738  	if hs.certReq == nil {
   739  		return nil
   740  	}
   741  
   742  	if hs.echContext != nil && hs.echContext.echRejected {
   743  		if _, err := hs.c.writeHandshakeRecord(&certificateMsgTLS13{}, hs.transcript); err != nil {
   744  			return err
   745  		}
   746  		return nil
   747  	}
   748  
   749  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
   750  		AcceptableCAs:    hs.certReq.certificateAuthorities,
   751  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
   752  		Version:          c.vers,
   753  		ctx:              hs.ctx,
   754  	})
   755  	if err != nil {
   756  		return err
   757  	}
   758  
   759  	certMsg := new(certificateMsgTLS13)
   760  
   761  	certMsg.certificate = *cert
   762  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
   763  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
   764  
   765  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
   766  		return err
   767  	}
   768  
   769  	// If we sent an empty certificate message, skip the CertificateVerify.
   770  	if len(cert.Certificate) == 0 {
   771  		return nil
   772  	}
   773  
   774  	certVerifyMsg := new(certificateVerifyMsg)
   775  	certVerifyMsg.hasSignatureAlgorithm = true
   776  
   777  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
   778  	if err != nil {
   779  		// getClientCertificate returned a certificate incompatible with the
   780  		// CertificateRequestInfo supported signature algorithms.
   781  		c.sendAlert(alertHandshakeFailure)
   782  		return err
   783  	}
   784  
   785  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
   786  	if err != nil {
   787  		return c.sendAlert(alertInternalError)
   788  	}
   789  
   790  	signed := signedMessage(clientSignatureContext, hs.transcript)
   791  	signOpts := crypto.SignerOpts(sigHash)
   792  	if sigType == signatureRSAPSS {
   793  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   794  	}
   795  	sig, err := crypto.SignMessage(cert.PrivateKey.(crypto.Signer), c.config.rand(), signed, signOpts)
   796  	if err != nil {
   797  		c.sendAlert(alertInternalError)
   798  		return errors.New("tls: failed to sign handshake: " + err.Error())
   799  	}
   800  	certVerifyMsg.signature = sig
   801  
   802  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
   803  		return err
   804  	}
   805  
   806  	return nil
   807  }
   808  
   809  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
   810  	c := hs.c
   811  
   812  	finished := &finishedMsg{
   813  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   814  	}
   815  
   816  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
   817  		return err
   818  	}
   819  
   820  	c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
   821  
   822  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
   823  		c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
   824  	}
   825  
   826  	if c.quic != nil {
   827  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
   828  	}
   829  
   830  	return nil
   831  }
   832  
   833  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
   834  	if !c.isClient {
   835  		c.sendAlert(alertUnexpectedMessage)
   836  		return errors.New("tls: received new session ticket from a client")
   837  	}
   838  
   839  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   840  		return nil
   841  	}
   842  
   843  	// See RFC 8446, Section 4.6.1.
   844  	if msg.lifetime == 0 {
   845  		return nil
   846  	}
   847  	lifetime := time.Duration(msg.lifetime) * time.Second
   848  	if lifetime > maxSessionTicketLifetime {
   849  		c.sendAlert(alertIllegalParameter)
   850  		return errors.New("tls: received a session ticket with invalid lifetime")
   851  	}
   852  
   853  	if len(msg.label) == 0 {
   854  		c.sendAlert(alertDecodeError)
   855  		return errors.New("tls: received a session ticket with empty opaque ticket label")
   856  	}
   857  
   858  	// RFC 9001, Section 4.6.1
   859  	if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
   860  		c.sendAlert(alertIllegalParameter)
   861  		return errors.New("tls: invalid early data for QUIC connection")
   862  	}
   863  
   864  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
   865  	if cipherSuite == nil || c.resumptionSecret == nil {
   866  		return c.sendAlert(alertInternalError)
   867  	}
   868  
   869  	psk := tls13.ExpandLabel(cipherSuite.hash.New, c.resumptionSecret, "resumption",
   870  		msg.nonce, cipherSuite.hash.Size())
   871  
   872  	session := c.sessionState()
   873  	session.secret = psk
   874  	session.useBy = uint64(c.config.time().Add(lifetime).Unix())
   875  	session.ageAdd = msg.ageAdd
   876  	session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1
   877  	session.ticket = msg.label
   878  	if c.quic != nil && c.quic.enableSessionEvents {
   879  		c.quicStoreSession(session)
   880  		return nil
   881  	}
   882  	cs := &ClientSessionState{session: session}
   883  	if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
   884  		c.config.ClientSessionCache.Put(cacheKey, cs)
   885  	}
   886  
   887  	return nil
   888  }
   889  

View as plain text