Source file src/crypto/tls/handshake_server_tls13.go

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

View as plain text