github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/tls/handshake_server_tls13.go (about)

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