Source file src/crypto/tls/handshake_server_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/hmac"
    12  	"crypto/rsa"
    13  	"encoding/binary"
    14  	"errors"
    15  	"hash"
    16  	"io"
    17  	"time"
    18  )
    19  
    20  // maxClientPSKIdentities is the number of client PSK identities the server will
    21  // attempt to validate. It will ignore the rest not to let cheap ClientHello
    22  // messages cause too much work in session ticket decryption attempts.
    23  const maxClientPSKIdentities = 5
    24  
    25  type serverHandshakeStateTLS13 struct {
    26  	c               *Conn
    27  	ctx             context.Context
    28  	clientHello     *clientHelloMsg
    29  	hello           *serverHelloMsg
    30  	sentDummyCCS    bool
    31  	usingPSK        bool
    32  	earlyData       bool
    33  	suite           *cipherSuiteTLS13
    34  	cert            *Certificate
    35  	sigAlg          SignatureScheme
    36  	earlySecret     []byte
    37  	sharedKey       []byte
    38  	handshakeSecret []byte
    39  	masterSecret    []byte
    40  	trafficSecret   []byte // client_application_traffic_secret_0
    41  	transcript      hash.Hash
    42  	clientFinished  []byte
    43  }
    44  
    45  func (hs *serverHandshakeStateTLS13) handshake() error {
    46  	c := hs.c
    47  
    48  	if needFIPS() {
    49  		return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode")
    50  	}
    51  
    52  	// For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
    53  	if err := hs.processClientHello(); err != nil {
    54  		return err
    55  	}
    56  	if err := hs.checkForResumption(); err != nil {
    57  		return err
    58  	}
    59  	if err := hs.pickCertificate(); err != nil {
    60  		return err
    61  	}
    62  	c.buffering = true
    63  	if err := hs.sendServerParameters(); err != nil {
    64  		return err
    65  	}
    66  	if err := hs.sendServerCertificate(); err != nil {
    67  		return err
    68  	}
    69  	if err := hs.sendServerFinished(); err != nil {
    70  		return err
    71  	}
    72  	// Note that at this point we could start sending application data without
    73  	// waiting for the client's second flight, but the application might not
    74  	// expect the lack of replay protection of the ClientHello parameters.
    75  	if _, err := c.flush(); err != nil {
    76  		return err
    77  	}
    78  	if err := hs.readClientCertificate(); err != nil {
    79  		return err
    80  	}
    81  	if err := hs.readClientFinished(); err != nil {
    82  		return err
    83  	}
    84  
    85  	c.isHandshakeComplete.Store(true)
    86  
    87  	return nil
    88  }
    89  
    90  func (hs *serverHandshakeStateTLS13) processClientHello() error {
    91  	c := hs.c
    92  
    93  	hs.hello = new(serverHelloMsg)
    94  
    95  	// TLS 1.3 froze the ServerHello.legacy_version field, and uses
    96  	// supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
    97  	hs.hello.vers = VersionTLS12
    98  	hs.hello.supportedVersion = c.vers
    99  
   100  	if len(hs.clientHello.supportedVersions) == 0 {
   101  		c.sendAlert(alertIllegalParameter)
   102  		return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
   103  	}
   104  
   105  	// Abort if the client is doing a fallback and landing lower than what we
   106  	// support. See RFC 7507, which however does not specify the interaction
   107  	// with supported_versions. The only difference is that with
   108  	// supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
   109  	// handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
   110  	// it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
   111  	// TLS 1.2, because a TLS 1.3 server would abort here. The situation before
   112  	// supported_versions was not better because there was just no way to do a
   113  	// TLS 1.4 handshake without risking the server selecting TLS 1.3.
   114  	for _, id := range hs.clientHello.cipherSuites {
   115  		if id == TLS_FALLBACK_SCSV {
   116  			// Use c.vers instead of max(supported_versions) because an attacker
   117  			// could defeat this by adding an arbitrary high version otherwise.
   118  			if c.vers < c.config.maxSupportedVersion(roleServer) {
   119  				c.sendAlert(alertInappropriateFallback)
   120  				return errors.New("tls: client using inappropriate protocol fallback")
   121  			}
   122  			break
   123  		}
   124  	}
   125  
   126  	if len(hs.clientHello.compressionMethods) != 1 ||
   127  		hs.clientHello.compressionMethods[0] != compressionNone {
   128  		c.sendAlert(alertIllegalParameter)
   129  		return errors.New("tls: TLS 1.3 client supports illegal compression methods")
   130  	}
   131  
   132  	hs.hello.random = make([]byte, 32)
   133  	if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
   134  		c.sendAlert(alertInternalError)
   135  		return err
   136  	}
   137  
   138  	if len(hs.clientHello.secureRenegotiation) != 0 {
   139  		c.sendAlert(alertHandshakeFailure)
   140  		return errors.New("tls: initial handshake had non-empty renegotiation extension")
   141  	}
   142  
   143  	if hs.clientHello.earlyData && c.quic != nil {
   144  		if len(hs.clientHello.pskIdentities) == 0 {
   145  			c.sendAlert(alertIllegalParameter)
   146  			return errors.New("tls: early_data without pre_shared_key")
   147  		}
   148  	} else if hs.clientHello.earlyData {
   149  		// See RFC 8446, Section 4.2.10 for the complicated behavior required
   150  		// here. The scenario is that a different server at our address offered
   151  		// to accept early data in the past, which we can't handle. For now, all
   152  		// 0-RTT enabled session tickets need to expire before a Go server can
   153  		// replace a server or join a pool. That's the same requirement that
   154  		// applies to mixing or replacing with any TLS 1.2 server.
   155  		c.sendAlert(alertUnsupportedExtension)
   156  		return errors.New("tls: client sent unexpected early data")
   157  	}
   158  
   159  	hs.hello.sessionId = hs.clientHello.sessionId
   160  	hs.hello.compressionMethod = compressionNone
   161  
   162  	preferenceList := defaultCipherSuitesTLS13
   163  	if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
   164  		preferenceList = defaultCipherSuitesTLS13NoAES
   165  	}
   166  	for _, suiteID := range preferenceList {
   167  		hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
   168  		if hs.suite != nil {
   169  			break
   170  		}
   171  	}
   172  	if hs.suite == nil {
   173  		c.sendAlert(alertHandshakeFailure)
   174  		return errors.New("tls: no cipher suite supported by both client and server")
   175  	}
   176  	c.cipherSuite = hs.suite.id
   177  	hs.hello.cipherSuite = hs.suite.id
   178  	hs.transcript = hs.suite.hash.New()
   179  
   180  	// Pick the ECDHE group in server preference order, but give priority to
   181  	// groups with a key share, to avoid a HelloRetryRequest round-trip.
   182  	var selectedGroup CurveID
   183  	var clientKeyShare *keyShare
   184  GroupSelection:
   185  	for _, preferredGroup := range c.config.curvePreferences() {
   186  		for _, ks := range hs.clientHello.keyShares {
   187  			if ks.group == preferredGroup {
   188  				selectedGroup = ks.group
   189  				clientKeyShare = &ks
   190  				break GroupSelection
   191  			}
   192  		}
   193  		if selectedGroup != 0 {
   194  			continue
   195  		}
   196  		for _, group := range hs.clientHello.supportedCurves {
   197  			if group == preferredGroup {
   198  				selectedGroup = group
   199  				break
   200  			}
   201  		}
   202  	}
   203  	if selectedGroup == 0 {
   204  		c.sendAlert(alertHandshakeFailure)
   205  		return errors.New("tls: no ECDHE curve supported by both client and server")
   206  	}
   207  	if clientKeyShare == nil {
   208  		if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
   209  			return err
   210  		}
   211  		clientKeyShare = &hs.clientHello.keyShares[0]
   212  	}
   213  
   214  	if _, ok := curveForCurveID(selectedGroup); !ok {
   215  		c.sendAlert(alertInternalError)
   216  		return errors.New("tls: CurvePreferences includes unsupported curve")
   217  	}
   218  	key, err := generateECDHEKey(c.config.rand(), selectedGroup)
   219  	if err != nil {
   220  		c.sendAlert(alertInternalError)
   221  		return err
   222  	}
   223  	hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()}
   224  	peerKey, err := key.Curve().NewPublicKey(clientKeyShare.data)
   225  	if err != nil {
   226  		c.sendAlert(alertIllegalParameter)
   227  		return errors.New("tls: invalid client key share")
   228  	}
   229  	hs.sharedKey, err = key.ECDH(peerKey)
   230  	if err != nil {
   231  		c.sendAlert(alertIllegalParameter)
   232  		return errors.New("tls: invalid client key share")
   233  	}
   234  
   235  	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil)
   236  	if err != nil {
   237  		c.sendAlert(alertNoApplicationProtocol)
   238  		return err
   239  	}
   240  	c.clientProtocol = selectedProto
   241  
   242  	if c.quic != nil {
   243  		if hs.clientHello.quicTransportParameters == nil {
   244  			// RFC 9001 Section 8.2.
   245  			c.sendAlert(alertMissingExtension)
   246  			return errors.New("tls: client did not send a quic_transport_parameters extension")
   247  		}
   248  		c.quicSetTransportParameters(hs.clientHello.quicTransportParameters)
   249  	} else {
   250  		if hs.clientHello.quicTransportParameters != nil {
   251  			c.sendAlert(alertUnsupportedExtension)
   252  			return errors.New("tls: client sent an unexpected quic_transport_parameters extension")
   253  		}
   254  	}
   255  
   256  	c.serverName = hs.clientHello.serverName
   257  	return nil
   258  }
   259  
   260  func (hs *serverHandshakeStateTLS13) checkForResumption() error {
   261  	c := hs.c
   262  
   263  	if c.config.SessionTicketsDisabled {
   264  		return nil
   265  	}
   266  
   267  	modeOK := false
   268  	for _, mode := range hs.clientHello.pskModes {
   269  		if mode == pskModeDHE {
   270  			modeOK = true
   271  			break
   272  		}
   273  	}
   274  	if !modeOK {
   275  		return nil
   276  	}
   277  
   278  	if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
   279  		c.sendAlert(alertIllegalParameter)
   280  		return errors.New("tls: invalid or missing PSK binders")
   281  	}
   282  	if len(hs.clientHello.pskIdentities) == 0 {
   283  		return nil
   284  	}
   285  
   286  	for i, identity := range hs.clientHello.pskIdentities {
   287  		if i >= maxClientPSKIdentities {
   288  			break
   289  		}
   290  
   291  		var sessionState *SessionState
   292  		if c.config.UnwrapSession != nil {
   293  			var err error
   294  			sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked())
   295  			if err != nil {
   296  				return err
   297  			}
   298  			if sessionState == nil {
   299  				continue
   300  			}
   301  		} else {
   302  			plaintext := c.config.decryptTicket(identity.label, c.ticketKeys)
   303  			if plaintext == nil {
   304  				continue
   305  			}
   306  			var err error
   307  			sessionState, err = ParseSessionState(plaintext)
   308  			if err != nil {
   309  				continue
   310  			}
   311  		}
   312  
   313  		if sessionState.version != VersionTLS13 {
   314  			continue
   315  		}
   316  
   317  		createdAt := time.Unix(int64(sessionState.createdAt), 0)
   318  		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   319  			continue
   320  		}
   321  
   322  		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
   323  		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
   324  			continue
   325  		}
   326  
   327  		// PSK connections don't re-establish client certificates, but carry
   328  		// them over in the session ticket. Ensure the presence of client certs
   329  		// in the ticket is consistent with the configured requirements.
   330  		sessionHasClientCerts := len(sessionState.peerCertificates) != 0
   331  		needClientCerts := requiresClientCert(c.config.ClientAuth)
   332  		if needClientCerts && !sessionHasClientCerts {
   333  			continue
   334  		}
   335  		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   336  			continue
   337  		}
   338  		if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
   339  			continue
   340  		}
   341  		if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
   342  			len(sessionState.verifiedChains) == 0 {
   343  			continue
   344  		}
   345  
   346  		hs.earlySecret = hs.suite.extract(sessionState.secret, nil)
   347  		binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
   348  		// Clone the transcript in case a HelloRetryRequest was recorded.
   349  		transcript := cloneHash(hs.transcript, hs.suite.hash)
   350  		if transcript == nil {
   351  			c.sendAlert(alertInternalError)
   352  			return errors.New("tls: internal error: failed to clone hash")
   353  		}
   354  		clientHelloBytes, err := hs.clientHello.marshalWithoutBinders()
   355  		if err != nil {
   356  			c.sendAlert(alertInternalError)
   357  			return err
   358  		}
   359  		transcript.Write(clientHelloBytes)
   360  		pskBinder := hs.suite.finishedHash(binderKey, transcript)
   361  		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
   362  			c.sendAlert(alertDecryptError)
   363  			return errors.New("tls: invalid PSK binder")
   364  		}
   365  
   366  		if c.quic != nil && hs.clientHello.earlyData && i == 0 &&
   367  			sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id &&
   368  			sessionState.alpnProtocol == c.clientProtocol {
   369  			hs.earlyData = true
   370  
   371  			transcript := hs.suite.hash.New()
   372  			if err := transcriptMsg(hs.clientHello, transcript); err != nil {
   373  				return err
   374  			}
   375  			earlyTrafficSecret := hs.suite.deriveSecret(hs.earlySecret, clientEarlyTrafficLabel, transcript)
   376  			c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret)
   377  		}
   378  
   379  		c.didResume = true
   380  		c.peerCertificates = sessionState.peerCertificates
   381  		c.ocspResponse = sessionState.ocspResponse
   382  		c.scts = sessionState.scts
   383  		c.verifiedChains = sessionState.verifiedChains
   384  
   385  		hs.hello.selectedIdentityPresent = true
   386  		hs.hello.selectedIdentity = uint16(i)
   387  		hs.usingPSK = true
   388  		return nil
   389  	}
   390  
   391  	return nil
   392  }
   393  
   394  // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
   395  // interfaces implemented by standard library hashes to clone the state of in
   396  // to a new instance of h. It returns nil if the operation fails.
   397  func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
   398  	// Recreate the interface to avoid importing encoding.
   399  	type binaryMarshaler interface {
   400  		MarshalBinary() (data []byte, err error)
   401  		UnmarshalBinary(data []byte) error
   402  	}
   403  	marshaler, ok := in.(binaryMarshaler)
   404  	if !ok {
   405  		return nil
   406  	}
   407  	state, err := marshaler.MarshalBinary()
   408  	if err != nil {
   409  		return nil
   410  	}
   411  	out := h.New()
   412  	unmarshaler, ok := out.(binaryMarshaler)
   413  	if !ok {
   414  		return nil
   415  	}
   416  	if err := unmarshaler.UnmarshalBinary(state); err != nil {
   417  		return nil
   418  	}
   419  	return out
   420  }
   421  
   422  func (hs *serverHandshakeStateTLS13) pickCertificate() error {
   423  	c := hs.c
   424  
   425  	// Only one of PSK and certificates are used at a time.
   426  	if hs.usingPSK {
   427  		return nil
   428  	}
   429  
   430  	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
   431  	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
   432  		return c.sendAlert(alertMissingExtension)
   433  	}
   434  
   435  	certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
   436  	if err != nil {
   437  		if err == errNoCertificates {
   438  			c.sendAlert(alertUnrecognizedName)
   439  		} else {
   440  			c.sendAlert(alertInternalError)
   441  		}
   442  		return err
   443  	}
   444  	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
   445  	if err != nil {
   446  		// getCertificate returned a certificate that is unsupported or
   447  		// incompatible with the client's signature algorithms.
   448  		c.sendAlert(alertHandshakeFailure)
   449  		return err
   450  	}
   451  	hs.cert = certificate
   452  
   453  	return nil
   454  }
   455  
   456  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   457  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   458  func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   459  	if hs.c.quic != nil {
   460  		return nil
   461  	}
   462  	if hs.sentDummyCCS {
   463  		return nil
   464  	}
   465  	hs.sentDummyCCS = true
   466  
   467  	return hs.c.writeChangeCipherRecord()
   468  }
   469  
   470  func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
   471  	c := hs.c
   472  
   473  	// The first ClientHello gets double-hashed into the transcript upon a
   474  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   475  	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
   476  		return err
   477  	}
   478  	chHash := hs.transcript.Sum(nil)
   479  	hs.transcript.Reset()
   480  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   481  	hs.transcript.Write(chHash)
   482  
   483  	helloRetryRequest := &serverHelloMsg{
   484  		vers:              hs.hello.vers,
   485  		random:            helloRetryRequestRandom,
   486  		sessionId:         hs.hello.sessionId,
   487  		cipherSuite:       hs.hello.cipherSuite,
   488  		compressionMethod: hs.hello.compressionMethod,
   489  		supportedVersion:  hs.hello.supportedVersion,
   490  		selectedGroup:     selectedGroup,
   491  	}
   492  
   493  	if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil {
   494  		return err
   495  	}
   496  
   497  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   498  		return err
   499  	}
   500  
   501  	// clientHelloMsg is not included in the transcript.
   502  	msg, err := c.readHandshake(nil)
   503  	if err != nil {
   504  		return err
   505  	}
   506  
   507  	clientHello, ok := msg.(*clientHelloMsg)
   508  	if !ok {
   509  		c.sendAlert(alertUnexpectedMessage)
   510  		return unexpectedMessageError(clientHello, msg)
   511  	}
   512  
   513  	if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
   514  		c.sendAlert(alertIllegalParameter)
   515  		return errors.New("tls: client sent invalid key share in second ClientHello")
   516  	}
   517  
   518  	if clientHello.earlyData {
   519  		c.sendAlert(alertIllegalParameter)
   520  		return errors.New("tls: client indicated early data in second ClientHello")
   521  	}
   522  
   523  	if illegalClientHelloChange(clientHello, hs.clientHello) {
   524  		c.sendAlert(alertIllegalParameter)
   525  		return errors.New("tls: client illegally modified second ClientHello")
   526  	}
   527  
   528  	hs.clientHello = clientHello
   529  	return nil
   530  }
   531  
   532  // illegalClientHelloChange reports whether the two ClientHello messages are
   533  // different, with the exception of the changes allowed before and after a
   534  // HelloRetryRequest. See RFC 8446, Section 4.1.2.
   535  func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
   536  	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
   537  		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
   538  		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
   539  		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
   540  		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
   541  		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
   542  		return true
   543  	}
   544  	for i := range ch.supportedVersions {
   545  		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
   546  			return true
   547  		}
   548  	}
   549  	for i := range ch.cipherSuites {
   550  		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
   551  			return true
   552  		}
   553  	}
   554  	for i := range ch.supportedCurves {
   555  		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
   556  			return true
   557  		}
   558  	}
   559  	for i := range ch.supportedSignatureAlgorithms {
   560  		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
   561  			return true
   562  		}
   563  	}
   564  	for i := range ch.supportedSignatureAlgorithmsCert {
   565  		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
   566  			return true
   567  		}
   568  	}
   569  	for i := range ch.alpnProtocols {
   570  		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
   571  			return true
   572  		}
   573  	}
   574  	return ch.vers != ch1.vers ||
   575  		!bytes.Equal(ch.random, ch1.random) ||
   576  		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
   577  		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
   578  		ch.serverName != ch1.serverName ||
   579  		ch.ocspStapling != ch1.ocspStapling ||
   580  		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
   581  		ch.ticketSupported != ch1.ticketSupported ||
   582  		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
   583  		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
   584  		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
   585  		ch.scts != ch1.scts ||
   586  		!bytes.Equal(ch.cookie, ch1.cookie) ||
   587  		!bytes.Equal(ch.pskModes, ch1.pskModes)
   588  }
   589  
   590  func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
   591  	c := hs.c
   592  
   593  	if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
   594  		return err
   595  	}
   596  	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
   597  		return err
   598  	}
   599  
   600  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   601  		return err
   602  	}
   603  
   604  	earlySecret := hs.earlySecret
   605  	if earlySecret == nil {
   606  		earlySecret = hs.suite.extract(nil, nil)
   607  	}
   608  	hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
   609  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   610  
   611  	clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   612  		clientHandshakeTrafficLabel, hs.transcript)
   613  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
   614  	serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   615  		serverHandshakeTrafficLabel, hs.transcript)
   616  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret)
   617  
   618  	if c.quic != nil {
   619  		if c.hand.Len() != 0 {
   620  			c.sendAlert(alertUnexpectedMessage)
   621  		}
   622  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret)
   623  		c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
   624  	}
   625  
   626  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
   627  	if err != nil {
   628  		c.sendAlert(alertInternalError)
   629  		return err
   630  	}
   631  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
   632  	if err != nil {
   633  		c.sendAlert(alertInternalError)
   634  		return err
   635  	}
   636  
   637  	encryptedExtensions := new(encryptedExtensionsMsg)
   638  	encryptedExtensions.alpnProtocol = c.clientProtocol
   639  
   640  	if c.quic != nil {
   641  		p, err := c.quicGetTransportParameters()
   642  		if err != nil {
   643  			return err
   644  		}
   645  		encryptedExtensions.quicTransportParameters = p
   646  		encryptedExtensions.earlyData = hs.earlyData
   647  	}
   648  
   649  	if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil {
   650  		return err
   651  	}
   652  
   653  	return nil
   654  }
   655  
   656  func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
   657  	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
   658  }
   659  
   660  func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
   661  	c := hs.c
   662  
   663  	// Only one of PSK and certificates are used at a time.
   664  	if hs.usingPSK {
   665  		return nil
   666  	}
   667  
   668  	if hs.requestClientCert() {
   669  		// Request a client certificate
   670  		certReq := new(certificateRequestMsgTLS13)
   671  		certReq.ocspStapling = true
   672  		certReq.scts = true
   673  		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
   674  		if c.config.ClientCAs != nil {
   675  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   676  		}
   677  
   678  		if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil {
   679  			return err
   680  		}
   681  	}
   682  
   683  	certMsg := new(certificateMsgTLS13)
   684  
   685  	certMsg.certificate = *hs.cert
   686  	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
   687  	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
   688  
   689  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
   690  		return err
   691  	}
   692  
   693  	certVerifyMsg := new(certificateVerifyMsg)
   694  	certVerifyMsg.hasSignatureAlgorithm = true
   695  	certVerifyMsg.signatureAlgorithm = hs.sigAlg
   696  
   697  	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
   698  	if err != nil {
   699  		return c.sendAlert(alertInternalError)
   700  	}
   701  
   702  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   703  	signOpts := crypto.SignerOpts(sigHash)
   704  	if sigType == signatureRSAPSS {
   705  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   706  	}
   707  	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   708  	if err != nil {
   709  		public := hs.cert.PrivateKey.(crypto.Signer).Public()
   710  		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
   711  			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
   712  			c.sendAlert(alertHandshakeFailure)
   713  		} else {
   714  			c.sendAlert(alertInternalError)
   715  		}
   716  		return errors.New("tls: failed to sign handshake: " + err.Error())
   717  	}
   718  	certVerifyMsg.signature = sig
   719  
   720  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
   721  		return err
   722  	}
   723  
   724  	return nil
   725  }
   726  
   727  func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
   728  	c := hs.c
   729  
   730  	finished := &finishedMsg{
   731  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   732  	}
   733  
   734  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
   735  		return err
   736  	}
   737  
   738  	// Derive secrets that take context through the server Finished.
   739  
   740  	hs.masterSecret = hs.suite.extract(nil,
   741  		hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
   742  
   743  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   744  		clientApplicationTrafficLabel, hs.transcript)
   745  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   746  		serverApplicationTrafficLabel, hs.transcript)
   747  	c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret)
   748  
   749  	if c.quic != nil {
   750  		if c.hand.Len() != 0 {
   751  			// TODO: Handle this in setTrafficSecret?
   752  			c.sendAlert(alertUnexpectedMessage)
   753  		}
   754  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret)
   755  	}
   756  
   757  	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
   758  	if err != nil {
   759  		c.sendAlert(alertInternalError)
   760  		return err
   761  	}
   762  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
   763  	if err != nil {
   764  		c.sendAlert(alertInternalError)
   765  		return err
   766  	}
   767  
   768  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   769  
   770  	// If we did not request client certificates, at this point we can
   771  	// precompute the client finished and roll the transcript forward to send
   772  	// session tickets in our first flight.
   773  	if !hs.requestClientCert() {
   774  		if err := hs.sendSessionTickets(); err != nil {
   775  			return err
   776  		}
   777  	}
   778  
   779  	return nil
   780  }
   781  
   782  func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
   783  	if hs.c.config.SessionTicketsDisabled {
   784  		return false
   785  	}
   786  
   787  	// QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically.
   788  	if hs.c.quic != nil {
   789  		return false
   790  	}
   791  
   792  	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
   793  	for _, pskMode := range hs.clientHello.pskModes {
   794  		if pskMode == pskModeDHE {
   795  			return true
   796  		}
   797  	}
   798  	return false
   799  }
   800  
   801  func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
   802  	c := hs.c
   803  
   804  	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   805  	finishedMsg := &finishedMsg{
   806  		verifyData: hs.clientFinished,
   807  	}
   808  	if err := transcriptMsg(finishedMsg, hs.transcript); err != nil {
   809  		return err
   810  	}
   811  
   812  	c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
   813  		resumptionLabel, hs.transcript)
   814  
   815  	if !hs.shouldSendSessionTickets() {
   816  		return nil
   817  	}
   818  	return c.sendSessionTicket(false)
   819  }
   820  
   821  func (c *Conn) sendSessionTicket(earlyData bool) error {
   822  	suite := cipherSuiteTLS13ByID(c.cipherSuite)
   823  	if suite == nil {
   824  		return errors.New("tls: internal error: unknown cipher suite")
   825  	}
   826  	// ticket_nonce, which must be unique per connection, is always left at
   827  	// zero because we only ever send one ticket per connection.
   828  	psk := suite.expandLabel(c.resumptionSecret, "resumption",
   829  		nil, suite.hash.Size())
   830  
   831  	m := new(newSessionTicketMsgTLS13)
   832  
   833  	state, err := c.sessionState()
   834  	if err != nil {
   835  		return err
   836  	}
   837  	state.secret = psk
   838  	state.EarlyData = earlyData
   839  	if c.config.WrapSession != nil {
   840  		m.label, err = c.config.WrapSession(c.connectionStateLocked(), state)
   841  		if err != nil {
   842  			return err
   843  		}
   844  	} else {
   845  		stateBytes, err := state.Bytes()
   846  		if err != nil {
   847  			c.sendAlert(alertInternalError)
   848  			return err
   849  		}
   850  		m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
   851  		if err != nil {
   852  			return err
   853  		}
   854  	}
   855  	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
   856  
   857  	// ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1
   858  	// The value is not stored anywhere; we never need to check the ticket age
   859  	// because 0-RTT is not supported.
   860  	ageAdd := make([]byte, 4)
   861  	_, err = c.config.rand().Read(ageAdd)
   862  	if err != nil {
   863  		return err
   864  	}
   865  	m.ageAdd = binary.LittleEndian.Uint32(ageAdd)
   866  
   867  	if earlyData {
   868  		// RFC 9001, Section 4.6.1
   869  		m.maxEarlyData = 0xffffffff
   870  	}
   871  
   872  	if _, err := c.writeHandshakeRecord(m, nil); err != nil {
   873  		return err
   874  	}
   875  
   876  	return nil
   877  }
   878  
   879  func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
   880  	c := hs.c
   881  
   882  	if !hs.requestClientCert() {
   883  		// Make sure the connection is still being verified whether or not
   884  		// the server requested a client certificate.
   885  		if c.config.VerifyConnection != nil {
   886  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   887  				c.sendAlert(alertBadCertificate)
   888  				return err
   889  			}
   890  		}
   891  		return nil
   892  	}
   893  
   894  	// If we requested a client certificate, then the client must send a
   895  	// certificate message. If it's empty, no CertificateVerify is sent.
   896  
   897  	msg, err := c.readHandshake(hs.transcript)
   898  	if err != nil {
   899  		return err
   900  	}
   901  
   902  	certMsg, ok := msg.(*certificateMsgTLS13)
   903  	if !ok {
   904  		c.sendAlert(alertUnexpectedMessage)
   905  		return unexpectedMessageError(certMsg, msg)
   906  	}
   907  
   908  	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
   909  		return err
   910  	}
   911  
   912  	if c.config.VerifyConnection != nil {
   913  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   914  			c.sendAlert(alertBadCertificate)
   915  			return err
   916  		}
   917  	}
   918  
   919  	if len(certMsg.certificate.Certificate) != 0 {
   920  		// certificateVerifyMsg is included in the transcript, but not until
   921  		// after we verify the handshake signature, since the state before
   922  		// this message was sent is used.
   923  		msg, err = c.readHandshake(nil)
   924  		if err != nil {
   925  			return err
   926  		}
   927  
   928  		certVerify, ok := msg.(*certificateVerifyMsg)
   929  		if !ok {
   930  			c.sendAlert(alertUnexpectedMessage)
   931  			return unexpectedMessageError(certVerify, msg)
   932  		}
   933  
   934  		// See RFC 8446, Section 4.4.3.
   935  		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) {
   936  			c.sendAlert(alertIllegalParameter)
   937  			return errors.New("tls: client certificate used with invalid signature algorithm")
   938  		}
   939  		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   940  		if err != nil {
   941  			return c.sendAlert(alertInternalError)
   942  		}
   943  		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   944  			c.sendAlert(alertIllegalParameter)
   945  			return errors.New("tls: client certificate used with invalid signature algorithm")
   946  		}
   947  		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   948  		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   949  			sigHash, signed, certVerify.signature); err != nil {
   950  			c.sendAlert(alertDecryptError)
   951  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   952  		}
   953  
   954  		if err := transcriptMsg(certVerify, hs.transcript); err != nil {
   955  			return err
   956  		}
   957  	}
   958  
   959  	// If we waited until the client certificates to send session tickets, we
   960  	// are ready to do it now.
   961  	if err := hs.sendSessionTickets(); err != nil {
   962  		return err
   963  	}
   964  
   965  	return nil
   966  }
   967  
   968  func (hs *serverHandshakeStateTLS13) readClientFinished() error {
   969  	c := hs.c
   970  
   971  	// finishedMsg is not included in the transcript.
   972  	msg, err := c.readHandshake(nil)
   973  	if err != nil {
   974  		return err
   975  	}
   976  
   977  	finished, ok := msg.(*finishedMsg)
   978  	if !ok {
   979  		c.sendAlert(alertUnexpectedMessage)
   980  		return unexpectedMessageError(finished, msg)
   981  	}
   982  
   983  	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
   984  		c.sendAlert(alertDecryptError)
   985  		return errors.New("tls: invalid client finished hash")
   986  	}
   987  
   988  	c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
   989  
   990  	return nil
   991  }
   992  

View as plain text