gitee.com/lh-her-team/common@v1.5.1/crypto/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  	"crypto"
    10  	"crypto/hmac"
    11  	"crypto/rsa"
    12  	"errors"
    13  	"hash"
    14  	"io"
    15  	"sync/atomic"
    16  	"time"
    17  )
    18  
    19  // maxClientPSKIdentities is the number of client PSK identities the server will
    20  // attempt to validate. It will ignore the rest not to let cheap ClientHello
    21  // messages cause too much work in session ticket decryption attempts.
    22  const maxClientPSKIdentities = 5
    23  
    24  type serverHandshakeStateTLS13 struct {
    25  	c               *Conn
    26  	clientHello     *clientHelloMsg
    27  	hello           *serverHelloMsg
    28  	sentDummyCCS    bool
    29  	usingPSK        bool
    30  	suite           *cipherSuiteTLS13
    31  	cert            *Certificate
    32  	sigAlg          SignatureScheme
    33  	earlySecret     []byte
    34  	sharedKey       []byte
    35  	handshakeSecret []byte
    36  	masterSecret    []byte
    37  	trafficSecret   []byte // client_application_traffic_secret_0
    38  	transcript      hash.Hash
    39  	clientFinished  []byte
    40  }
    41  
    42  func (hs *serverHandshakeStateTLS13) handshake() error {
    43  	c := hs.c
    44  	// For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2.
    45  	if err := hs.processClientHello(); err != nil {
    46  		return err
    47  	}
    48  	if err := hs.checkForResumption(); err != nil {
    49  		return err
    50  	}
    51  	if err := hs.pickCertificate(); err != nil {
    52  		return err
    53  	}
    54  	c.buffering = true
    55  	if err := hs.sendServerParameters(); err != nil {
    56  		return err
    57  	}
    58  	if err := hs.sendServerCertificate(); err != nil {
    59  		return err
    60  	}
    61  	if err := hs.sendServerFinished(); err != nil {
    62  		return err
    63  	}
    64  	// Note that at this point we could start sending application data without
    65  	// waiting for the client's second flight, but the application might not
    66  	// expect the lack of replay protection of the ClientHello parameters.
    67  	if _, err := c.flush(); err != nil {
    68  		return err
    69  	}
    70  	if err := hs.readClientCertificate(); err != nil {
    71  		return err
    72  	}
    73  	if err := hs.readClientFinished(); err != nil {
    74  		return err
    75  	}
    76  	atomic.StoreUint32(&c.handshakeStatus, 1)
    77  	return nil
    78  }
    79  
    80  func (hs *serverHandshakeStateTLS13) processClientHello() error {
    81  	c := hs.c
    82  	hs.hello = new(serverHelloMsg)
    83  	// TLS 1.3 froze the ServerHello.legacy_version field, and uses
    84  	// supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1.
    85  	hs.hello.vers = VersionTLS12
    86  	hs.hello.supportedVersion = c.vers
    87  	if len(hs.clientHello.supportedVersions) == 0 {
    88  		c.sendAlert(alertIllegalParameter)
    89  		return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
    90  	}
    91  	// Abort if the client is doing a fallback and landing lower than what we
    92  	// support. See RFC 7507, which however does not specify the interaction
    93  	// with supported_versions. The only difference is that with
    94  	// supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4]
    95  	// handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case,
    96  	// it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to
    97  	// TLS 1.2, because a TLS 1.3 server would abort here. The situation before
    98  	// supported_versions was not better because there was just no way to do a
    99  	// TLS 1.4 handshake without risking the server selecting TLS 1.3.
   100  	for _, id := range hs.clientHello.cipherSuites {
   101  		if id == TLS_FALLBACK_SCSV {
   102  			// Use c.vers instead of max(supported_versions) because an attacker
   103  			// could defeat this by adding an arbitrary high version otherwise.
   104  			if c.vers < c.config.maxSupportedVersion() {
   105  				c.sendAlert(alertInappropriateFallback)
   106  				return errors.New("tls: client using inappropriate protocol fallback")
   107  			}
   108  			break
   109  		}
   110  	}
   111  	if len(hs.clientHello.compressionMethods) != 1 ||
   112  		hs.clientHello.compressionMethods[0] != compressionNone {
   113  		c.sendAlert(alertIllegalParameter)
   114  		return errors.New("tls: TLS 1.3 client supports illegal compression methods")
   115  	}
   116  	hs.hello.random = make([]byte, 32)
   117  	if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
   118  		c.sendAlert(alertInternalError)
   119  		return err
   120  	}
   121  	if len(hs.clientHello.secureRenegotiation) != 0 {
   122  		c.sendAlert(alertHandshakeFailure)
   123  		return errors.New("tls: initial handshake had non-empty renegotiation extension")
   124  	}
   125  	if hs.clientHello.earlyData {
   126  		// See RFC 8446, Section 4.2.10 for the complicated behavior required
   127  		// here. The scenario is that a different server at our address offered
   128  		// to accept early data in the past, which we can't handle. For now, all
   129  		// 0-RTT enabled session tickets need to expire before a Go server can
   130  		// replace a server or join a pool. That's the same requirement that
   131  		// applies to mixing or replacing with any TLS 1.2 server.
   132  		c.sendAlert(alertUnsupportedExtension)
   133  		return errors.New("tls: client sent unexpected early data")
   134  	}
   135  	hs.hello.sessionId = hs.clientHello.sessionId
   136  	hs.hello.compressionMethod = compressionNone
   137  	var preferenceList, supportedList []uint16
   138  	if c.config.PreferServerCipherSuites {
   139  		preferenceList = defaultCipherSuitesTLS13()
   140  		supportedList = hs.clientHello.cipherSuites
   141  	} else {
   142  		preferenceList = hs.clientHello.cipherSuites
   143  		supportedList = defaultCipherSuitesTLS13()
   144  	}
   145  	for _, suiteID := range preferenceList {
   146  		hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID)
   147  		if hs.suite != nil {
   148  			break
   149  		}
   150  	}
   151  	if hs.suite == nil {
   152  		c.sendAlert(alertHandshakeFailure)
   153  		return errors.New("tls: no cipher suite supported by both client and server")
   154  	}
   155  	c.cipherSuite = hs.suite.id
   156  	hs.hello.cipherSuite = hs.suite.id
   157  	hs.transcript = hs.suite.hash.New()
   158  	// Pick the ECDHE group in server preference order, but give priority to
   159  	// groups with a key share, to avoid a HelloRetryRequest round-trip.
   160  	var selectedGroup CurveID
   161  	var clientKeyShare *keyShare
   162  GroupSelection:
   163  	for _, preferredGroup := range c.config.curvePreferences() {
   164  		for _, ks := range hs.clientHello.keyShares {
   165  			if ks.group == preferredGroup {
   166  				selectedGroup = ks.group
   167  				clientKeyShare = &ks
   168  				break GroupSelection
   169  			}
   170  		}
   171  		if selectedGroup != 0 {
   172  			continue
   173  		}
   174  		for _, group := range hs.clientHello.supportedCurves {
   175  			if group == preferredGroup {
   176  				selectedGroup = group
   177  				break
   178  			}
   179  		}
   180  	}
   181  	if selectedGroup == 0 {
   182  		c.sendAlert(alertHandshakeFailure)
   183  		return errors.New("tls: no ECDHE curve supported by both client and server")
   184  	}
   185  	if clientKeyShare == nil {
   186  		if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
   187  			return err
   188  		}
   189  		clientKeyShare = &hs.clientHello.keyShares[0]
   190  	}
   191  
   192  	if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
   193  		c.sendAlert(alertInternalError)
   194  		return errors.New("tls: CurvePreferences includes unsupported curve")
   195  	}
   196  	params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
   197  	if err != nil {
   198  		c.sendAlert(alertInternalError)
   199  		return err
   200  	}
   201  	hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
   202  	hs.sharedKey = params.SharedKey(clientKeyShare.data)
   203  	if hs.sharedKey == nil {
   204  		c.sendAlert(alertIllegalParameter)
   205  		return errors.New("tls: invalid client key share")
   206  	}
   207  	c.serverName = hs.clientHello.serverName
   208  	return nil
   209  }
   210  
   211  func (hs *serverHandshakeStateTLS13) checkForResumption() error {
   212  	c := hs.c
   213  	if c.config.SessionTicketsDisabled {
   214  		return nil
   215  	}
   216  	modeOK := false
   217  	for _, mode := range hs.clientHello.pskModes {
   218  		if mode == pskModeDHE {
   219  			modeOK = true
   220  			break
   221  		}
   222  	}
   223  	if !modeOK {
   224  		return nil
   225  	}
   226  	if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
   227  		c.sendAlert(alertIllegalParameter)
   228  		return errors.New("tls: invalid or missing PSK binders")
   229  	}
   230  	if len(hs.clientHello.pskIdentities) == 0 {
   231  		return nil
   232  	}
   233  	for i, identity := range hs.clientHello.pskIdentities {
   234  		if i >= maxClientPSKIdentities {
   235  			break
   236  		}
   237  		plaintext, _ := c.decryptTicket(identity.label)
   238  		if plaintext == nil {
   239  			continue
   240  		}
   241  		sessionState := new(sessionStateTLS13)
   242  		if ok := sessionState.unmarshal(plaintext); !ok {
   243  			continue
   244  		}
   245  		createdAt := time.Unix(int64(sessionState.createdAt), 0)
   246  		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   247  			continue
   248  		}
   249  		// We don't check the obfuscated ticket age because it's affected by
   250  		// clock skew and it's only a freshness signal useful for shrinking the
   251  		// window for replay attacks, which don't affect us as we don't do 0-RTT.
   252  		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
   253  		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
   254  			continue
   255  		}
   256  		// PSK connections don't re-establish client certificates, but carry
   257  		// them over in the session ticket. Ensure the presence of client certs
   258  		// in the ticket is consistent with the configured requirements.
   259  		sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
   260  		needClientCerts := requiresClientCert(c.config.ClientAuth)
   261  		if needClientCerts && !sessionHasClientCerts {
   262  			continue
   263  		}
   264  		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   265  			continue
   266  		}
   267  		psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
   268  			nil, hs.suite.hash.Size())
   269  		hs.earlySecret = hs.suite.extract(psk, nil)
   270  		binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
   271  		// Clone the transcript in case a HelloRetryRequest was recorded.
   272  		transcript := cloneHash(hs.transcript, hs.suite.hash)
   273  		if transcript == nil {
   274  			c.sendAlert(alertInternalError)
   275  			return errors.New("tls: internal error: failed to clone hash")
   276  		}
   277  		transcript.Write(hs.clientHello.marshalWithoutBinders())
   278  		pskBinder := hs.suite.finishedHash(binderKey, transcript)
   279  		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
   280  			c.sendAlert(alertDecryptError)
   281  			return errors.New("tls: invalid PSK binder")
   282  		}
   283  		if err := c.processCertsFromClient(sessionState.certificate); err != nil {
   284  			return err
   285  		}
   286  		hs.hello.selectedIdentityPresent = true
   287  		hs.hello.selectedIdentity = uint16(i)
   288  		hs.usingPSK = true
   289  		c.didResume = true
   290  		return nil
   291  	}
   292  	return nil
   293  }
   294  
   295  // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
   296  // interfaces implemented by standard library hashes to clone the state of in
   297  // to a new instance of h. It returns nil if the operation fails.
   298  func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
   299  	// Recreate the interface to avoid importing encoding.
   300  	type binaryMarshaler interface {
   301  		MarshalBinary() (data []byte, err error)
   302  		UnmarshalBinary(data []byte) error
   303  	}
   304  	marshaler, ok := in.(binaryMarshaler)
   305  	if !ok {
   306  		return nil
   307  	}
   308  	state, err := marshaler.MarshalBinary()
   309  	if err != nil {
   310  		return nil
   311  	}
   312  	out := h.New()
   313  	unmarshaler, ok := out.(binaryMarshaler)
   314  	if !ok {
   315  		return nil
   316  	}
   317  	if err := unmarshaler.UnmarshalBinary(state); err != nil {
   318  		return nil
   319  	}
   320  	return out
   321  }
   322  
   323  func (hs *serverHandshakeStateTLS13) pickCertificate() error {
   324  	c := hs.c
   325  	// Only one of PSK and certificates are used at a time.
   326  	if hs.usingPSK {
   327  		return nil
   328  	}
   329  	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
   330  	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
   331  		return c.sendAlert(alertMissingExtension)
   332  	}
   333  	certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
   334  	if err != nil {
   335  		if err == errNoCertificates {
   336  			c.sendAlert(alertUnrecognizedName)
   337  		} else {
   338  			c.sendAlert(alertInternalError)
   339  		}
   340  		return err
   341  	}
   342  	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
   343  	if err != nil {
   344  		// getCertificate returned a certificate that is unsupported or
   345  		// incompatible with the client's signature algorithms.
   346  		c.sendAlert(alertHandshakeFailure)
   347  		return err
   348  	}
   349  	hs.cert = certificate
   350  	return nil
   351  }
   352  
   353  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   354  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   355  func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   356  	if hs.sentDummyCCS {
   357  		return nil
   358  	}
   359  	hs.sentDummyCCS = true
   360  	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
   361  	return err
   362  }
   363  
   364  func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
   365  	c := hs.c
   366  	// The first ClientHello gets double-hashed into the transcript upon a
   367  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   368  	hs.transcript.Write(hs.clientHello.marshal())
   369  	chHash := hs.transcript.Sum(nil)
   370  	hs.transcript.Reset()
   371  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   372  	hs.transcript.Write(chHash)
   373  	helloRetryRequest := &serverHelloMsg{
   374  		vers:              hs.hello.vers,
   375  		random:            helloRetryRequestRandom,
   376  		sessionId:         hs.hello.sessionId,
   377  		cipherSuite:       hs.hello.cipherSuite,
   378  		compressionMethod: hs.hello.compressionMethod,
   379  		supportedVersion:  hs.hello.supportedVersion,
   380  		selectedGroup:     selectedGroup,
   381  	}
   382  	hs.transcript.Write(helloRetryRequest.marshal())
   383  	if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
   384  		return err
   385  	}
   386  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   387  		return err
   388  	}
   389  	msg, err := c.readHandshake()
   390  	if err != nil {
   391  		return err
   392  	}
   393  	clientHello, ok := msg.(*clientHelloMsg)
   394  	if !ok {
   395  		c.sendAlert(alertUnexpectedMessage)
   396  		return unexpectedMessageError(clientHello, msg)
   397  	}
   398  	if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
   399  		c.sendAlert(alertIllegalParameter)
   400  		return errors.New("tls: client sent invalid key share in second ClientHello")
   401  	}
   402  	if clientHello.earlyData {
   403  		c.sendAlert(alertIllegalParameter)
   404  		return errors.New("tls: client indicated early data in second ClientHello")
   405  	}
   406  	if illegalClientHelloChange(clientHello, hs.clientHello) {
   407  		c.sendAlert(alertIllegalParameter)
   408  		return errors.New("tls: client illegally modified second ClientHello")
   409  	}
   410  	hs.clientHello = clientHello
   411  	return nil
   412  }
   413  
   414  // illegalClientHelloChange reports whether the two ClientHello messages are
   415  // different, with the exception of the changes allowed before and after a
   416  // HelloRetryRequest. See RFC 8446, Section 4.1.2.
   417  func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
   418  	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
   419  		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
   420  		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
   421  		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
   422  		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
   423  		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
   424  		return true
   425  	}
   426  	for i := range ch.supportedVersions {
   427  		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
   428  			return true
   429  		}
   430  	}
   431  	for i := range ch.cipherSuites {
   432  		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
   433  			return true
   434  		}
   435  	}
   436  	for i := range ch.supportedCurves {
   437  		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
   438  			return true
   439  		}
   440  	}
   441  	for i := range ch.supportedSignatureAlgorithms {
   442  		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
   443  			return true
   444  		}
   445  	}
   446  	for i := range ch.supportedSignatureAlgorithmsCert {
   447  		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
   448  			return true
   449  		}
   450  	}
   451  	for i := range ch.alpnProtocols {
   452  		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
   453  			return true
   454  		}
   455  	}
   456  	return ch.vers != ch1.vers ||
   457  		!bytes.Equal(ch.random, ch1.random) ||
   458  		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
   459  		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
   460  		ch.serverName != ch1.serverName ||
   461  		ch.ocspStapling != ch1.ocspStapling ||
   462  		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
   463  		ch.ticketSupported != ch1.ticketSupported ||
   464  		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
   465  		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
   466  		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
   467  		ch.scts != ch1.scts ||
   468  		!bytes.Equal(ch.cookie, ch1.cookie) ||
   469  		!bytes.Equal(ch.pskModes, ch1.pskModes)
   470  }
   471  
   472  func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
   473  	c := hs.c
   474  	hs.transcript.Write(hs.clientHello.marshal())
   475  	hs.transcript.Write(hs.hello.marshal())
   476  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   477  		return err
   478  	}
   479  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   480  		return err
   481  	}
   482  	earlySecret := hs.earlySecret
   483  	if earlySecret == nil {
   484  		earlySecret = hs.suite.extract(nil, nil)
   485  	}
   486  	hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
   487  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   488  	clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   489  		clientHandshakeTrafficLabel, hs.transcript)
   490  	c.in.setTrafficSecret(hs.suite, clientSecret)
   491  	serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   492  		serverHandshakeTrafficLabel, hs.transcript)
   493  	c.out.setTrafficSecret(hs.suite, serverSecret)
   494  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
   495  	if err != nil {
   496  		c.sendAlert(alertInternalError)
   497  		return err
   498  	}
   499  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
   500  	if err != nil {
   501  		c.sendAlert(alertInternalError)
   502  		return err
   503  	}
   504  	encryptedExtensions := new(encryptedExtensionsMsg)
   505  	if len(hs.clientHello.alpnProtocols) > 0 {
   506  		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
   507  			encryptedExtensions.alpnProtocol = selectedProto
   508  			c.clientProtocol = selectedProto
   509  		}
   510  	}
   511  	hs.transcript.Write(encryptedExtensions.marshal())
   512  	if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
   513  		return err
   514  	}
   515  	return nil
   516  }
   517  
   518  func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
   519  	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
   520  }
   521  
   522  func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
   523  	c := hs.c
   524  	// Only one of PSK and certificates are used at a time.
   525  	if hs.usingPSK {
   526  		return nil
   527  	}
   528  	if hs.requestClientCert() {
   529  		// Request a client certificate
   530  		certReq := new(certificateRequestMsgTLS13)
   531  		certReq.ocspStapling = true
   532  		certReq.scts = true
   533  		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   534  		if c.config.ClientCAs != nil {
   535  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   536  		}
   537  		hs.transcript.Write(certReq.marshal())
   538  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   539  			return err
   540  		}
   541  	}
   542  	certMsg := new(certificateMsgTLS13)
   543  	certMsg.certificate = *hs.cert
   544  	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
   545  	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
   546  	hs.transcript.Write(certMsg.marshal())
   547  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   548  		return err
   549  	}
   550  	certVerifyMsg := new(certificateVerifyMsg)
   551  	certVerifyMsg.hasSignatureAlgorithm = true
   552  	certVerifyMsg.signatureAlgorithm = hs.sigAlg
   553  	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
   554  	if err != nil {
   555  		return c.sendAlert(alertInternalError)
   556  	}
   557  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   558  	signOpts := crypto.SignerOpts(sigHash)
   559  	if sigType == signatureRSAPSS {
   560  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   561  	}
   562  	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   563  	if err != nil {
   564  		public := hs.cert.PrivateKey.(crypto.Signer).Public()
   565  		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
   566  			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
   567  			c.sendAlert(alertHandshakeFailure)
   568  		} else {
   569  			c.sendAlert(alertInternalError)
   570  		}
   571  		return errors.New("tls: failed to sign handshake: " + err.Error())
   572  	}
   573  	certVerifyMsg.signature = sig
   574  	hs.transcript.Write(certVerifyMsg.marshal())
   575  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   576  		return err
   577  	}
   578  	return nil
   579  }
   580  
   581  func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
   582  	c := hs.c
   583  	finished := &finishedMsg{
   584  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   585  	}
   586  	hs.transcript.Write(finished.marshal())
   587  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   588  		return err
   589  	}
   590  	// Derive secrets that take context through the server Finished.
   591  
   592  	hs.masterSecret = hs.suite.extract(nil,
   593  		hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
   594  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   595  		clientApplicationTrafficLabel, hs.transcript)
   596  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   597  		serverApplicationTrafficLabel, hs.transcript)
   598  	c.out.setTrafficSecret(hs.suite, serverSecret)
   599  	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
   600  	if err != nil {
   601  		c.sendAlert(alertInternalError)
   602  		return err
   603  	}
   604  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
   605  	if err != nil {
   606  		c.sendAlert(alertInternalError)
   607  		return err
   608  	}
   609  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   610  	// If we did not request client certificates, at this point we can
   611  	// precompute the client finished and roll the transcript forward to send
   612  	// session tickets in our first flight.
   613  	if !hs.requestClientCert() {
   614  		if err := hs.sendSessionTickets(); err != nil {
   615  			return err
   616  		}
   617  	}
   618  	return nil
   619  }
   620  
   621  func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
   622  	if hs.c.config.SessionTicketsDisabled {
   623  		return false
   624  	}
   625  	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
   626  	for _, pskMode := range hs.clientHello.pskModes {
   627  		if pskMode == pskModeDHE {
   628  			return true
   629  		}
   630  	}
   631  	return false
   632  }
   633  
   634  func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
   635  	c := hs.c
   636  	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   637  	finishedMsg := &finishedMsg{
   638  		verifyData: hs.clientFinished,
   639  	}
   640  	hs.transcript.Write(finishedMsg.marshal())
   641  	if !hs.shouldSendSessionTickets() {
   642  		return nil
   643  	}
   644  	resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
   645  		resumptionLabel, hs.transcript)
   646  	m := new(newSessionTicketMsgTLS13)
   647  	var certsFromClient [][]byte
   648  	for _, cert := range c.peerCertificates {
   649  		certsFromClient = append(certsFromClient, cert.Raw)
   650  	}
   651  	state := sessionStateTLS13{
   652  		cipherSuite:      hs.suite.id,
   653  		createdAt:        uint64(c.config.time().Unix()),
   654  		resumptionSecret: resumptionSecret,
   655  		certificate: Certificate{
   656  			Certificate:                 certsFromClient,
   657  			OCSPStaple:                  c.ocspResponse,
   658  			SignedCertificateTimestamps: c.scts,
   659  		},
   660  	}
   661  	var err error
   662  	m.label, err = c.encryptTicket(state.marshal())
   663  	if err != nil {
   664  		return err
   665  	}
   666  	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
   667  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   668  		return err
   669  	}
   670  	return nil
   671  }
   672  
   673  func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
   674  	c := hs.c
   675  	if !hs.requestClientCert() {
   676  		return nil
   677  	}
   678  	// If we requested a client certificate, then the client must send a
   679  	// certificate message. If it's empty, no CertificateVerify is sent.
   680  	msg, err := c.readHandshake()
   681  	if err != nil {
   682  		return err
   683  	}
   684  	certMsg, ok := msg.(*certificateMsgTLS13)
   685  	if !ok {
   686  		c.sendAlert(alertUnexpectedMessage)
   687  		return unexpectedMessageError(certMsg, msg)
   688  	}
   689  	hs.transcript.Write(certMsg.marshal())
   690  	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
   691  		return err
   692  	}
   693  	if len(certMsg.certificate.Certificate) != 0 {
   694  		msg, err = c.readHandshake()
   695  		if err != nil {
   696  			return err
   697  		}
   698  		certVerify, ok := msg.(*certificateVerifyMsg)
   699  		if !ok {
   700  			c.sendAlert(alertUnexpectedMessage)
   701  			return unexpectedMessageError(certVerify, msg)
   702  		}
   703  		// See RFC 8446, Section 4.4.3.
   704  		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
   705  			c.sendAlert(alertIllegalParameter)
   706  			return errors.New("tls: client certificate used with invalid signature algorithm")
   707  		}
   708  		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   709  		if err != nil {
   710  			return c.sendAlert(alertInternalError)
   711  		}
   712  		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   713  			c.sendAlert(alertIllegalParameter)
   714  			return errors.New("tls: client certificate used with invalid signature algorithm")
   715  		}
   716  		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   717  		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   718  			sigHash, signed, certVerify.signature); err != nil {
   719  			c.sendAlert(alertDecryptError)
   720  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   721  		}
   722  		hs.transcript.Write(certVerify.marshal())
   723  	}
   724  	// If we waited until the client certificates to send session tickets, we
   725  	// are ready to do it now.
   726  	if err := hs.sendSessionTickets(); err != nil {
   727  		return err
   728  	}
   729  	return nil
   730  }
   731  
   732  func (hs *serverHandshakeStateTLS13) readClientFinished() error {
   733  	c := hs.c
   734  	msg, err := c.readHandshake()
   735  	if err != nil {
   736  		return err
   737  	}
   738  	finished, ok := msg.(*finishedMsg)
   739  	if !ok {
   740  		c.sendAlert(alertUnexpectedMessage)
   741  		return unexpectedMessageError(finished, msg)
   742  	}
   743  	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
   744  		c.sendAlert(alertDecryptError)
   745  		return errors.New("tls: invalid client finished hash")
   746  	}
   747  	c.in.setTrafficSecret(hs.suite, hs.trafficSecret)
   748  	return nil
   749  }