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