Source file src/crypto/tls/handshake_server_tls13.go

Documentation: crypto/tls

     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() {
   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  	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
   360  	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
   361  		return c.sendAlert(alertMissingExtension)
   362  	}
   363  
   364  	certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
   365  	if err != nil {
   366  		if err == errNoCertificates {
   367  			c.sendAlert(alertUnrecognizedName)
   368  		} else {
   369  			c.sendAlert(alertInternalError)
   370  		}
   371  		return err
   372  	}
   373  	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
   374  	if err != nil {
   375  		// getCertificate returned a certificate that is unsupported or
   376  		// incompatible with the client's signature algorithms.
   377  		c.sendAlert(alertHandshakeFailure)
   378  		return err
   379  	}
   380  	hs.cert = certificate
   381  
   382  	return nil
   383  }
   384  
   385  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   386  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   387  func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   388  	if hs.sentDummyCCS {
   389  		return nil
   390  	}
   391  	hs.sentDummyCCS = true
   392  
   393  	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
   394  	return err
   395  }
   396  
   397  func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
   398  	c := hs.c
   399  
   400  	// The first ClientHello gets double-hashed into the transcript upon a
   401  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   402  	hs.transcript.Write(hs.clientHello.marshal())
   403  	chHash := hs.transcript.Sum(nil)
   404  	hs.transcript.Reset()
   405  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   406  	hs.transcript.Write(chHash)
   407  
   408  	helloRetryRequest := &serverHelloMsg{
   409  		vers:              hs.hello.vers,
   410  		random:            helloRetryRequestRandom,
   411  		sessionId:         hs.hello.sessionId,
   412  		cipherSuite:       hs.hello.cipherSuite,
   413  		compressionMethod: hs.hello.compressionMethod,
   414  		supportedVersion:  hs.hello.supportedVersion,
   415  		selectedGroup:     selectedGroup,
   416  	}
   417  
   418  	hs.transcript.Write(helloRetryRequest.marshal())
   419  	if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
   420  		return err
   421  	}
   422  
   423  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   424  		return err
   425  	}
   426  
   427  	msg, err := c.readHandshake()
   428  	if err != nil {
   429  		return err
   430  	}
   431  
   432  	clientHello, ok := msg.(*clientHelloMsg)
   433  	if !ok {
   434  		c.sendAlert(alertUnexpectedMessage)
   435  		return unexpectedMessageError(clientHello, msg)
   436  	}
   437  
   438  	if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
   439  		c.sendAlert(alertIllegalParameter)
   440  		return errors.New("tls: client sent invalid key share in second ClientHello")
   441  	}
   442  
   443  	if clientHello.earlyData {
   444  		c.sendAlert(alertIllegalParameter)
   445  		return errors.New("tls: client indicated early data in second ClientHello")
   446  	}
   447  
   448  	if illegalClientHelloChange(clientHello, hs.clientHello) {
   449  		c.sendAlert(alertIllegalParameter)
   450  		return errors.New("tls: client illegally modified second ClientHello")
   451  	}
   452  
   453  	hs.clientHello = clientHello
   454  	return nil
   455  }
   456  
   457  // illegalClientHelloChange reports whether the two ClientHello messages are
   458  // different, with the exception of the changes allowed before and after a
   459  // HelloRetryRequest. See RFC 8446, Section 4.1.2.
   460  func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
   461  	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
   462  		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
   463  		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
   464  		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
   465  		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
   466  		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
   467  		return true
   468  	}
   469  	for i := range ch.supportedVersions {
   470  		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
   471  			return true
   472  		}
   473  	}
   474  	for i := range ch.cipherSuites {
   475  		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
   476  			return true
   477  		}
   478  	}
   479  	for i := range ch.supportedCurves {
   480  		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
   481  			return true
   482  		}
   483  	}
   484  	for i := range ch.supportedSignatureAlgorithms {
   485  		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
   486  			return true
   487  		}
   488  	}
   489  	for i := range ch.supportedSignatureAlgorithmsCert {
   490  		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
   491  			return true
   492  		}
   493  	}
   494  	for i := range ch.alpnProtocols {
   495  		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
   496  			return true
   497  		}
   498  	}
   499  	return ch.vers != ch1.vers ||
   500  		!bytes.Equal(ch.random, ch1.random) ||
   501  		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
   502  		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
   503  		ch.serverName != ch1.serverName ||
   504  		ch.ocspStapling != ch1.ocspStapling ||
   505  		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
   506  		ch.ticketSupported != ch1.ticketSupported ||
   507  		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
   508  		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
   509  		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
   510  		ch.scts != ch1.scts ||
   511  		!bytes.Equal(ch.cookie, ch1.cookie) ||
   512  		!bytes.Equal(ch.pskModes, ch1.pskModes)
   513  }
   514  
   515  func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
   516  	c := hs.c
   517  
   518  	hs.transcript.Write(hs.clientHello.marshal())
   519  	hs.transcript.Write(hs.hello.marshal())
   520  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   521  		return err
   522  	}
   523  
   524  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   525  		return err
   526  	}
   527  
   528  	earlySecret := hs.earlySecret
   529  	if earlySecret == nil {
   530  		earlySecret = hs.suite.extract(nil, nil)
   531  	}
   532  	hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
   533  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   534  
   535  	clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   536  		clientHandshakeTrafficLabel, hs.transcript)
   537  	c.in.setTrafficSecret(hs.suite, clientSecret)
   538  	serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   539  		serverHandshakeTrafficLabel, hs.transcript)
   540  	c.out.setTrafficSecret(hs.suite, serverSecret)
   541  
   542  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
   543  	if err != nil {
   544  		c.sendAlert(alertInternalError)
   545  		return err
   546  	}
   547  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
   548  	if err != nil {
   549  		c.sendAlert(alertInternalError)
   550  		return err
   551  	}
   552  
   553  	encryptedExtensions := new(encryptedExtensionsMsg)
   554  
   555  	if len(hs.clientHello.alpnProtocols) > 0 {
   556  		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
   557  			encryptedExtensions.alpnProtocol = selectedProto
   558  			c.clientProtocol = selectedProto
   559  		}
   560  	}
   561  
   562  	hs.transcript.Write(encryptedExtensions.marshal())
   563  	if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
   564  		return err
   565  	}
   566  
   567  	return nil
   568  }
   569  
   570  func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
   571  	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
   572  }
   573  
   574  func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
   575  	c := hs.c
   576  
   577  	// Only one of PSK and certificates are used at a time.
   578  	if hs.usingPSK {
   579  		return nil
   580  	}
   581  
   582  	if hs.requestClientCert() {
   583  		// Request a client certificate
   584  		certReq := new(certificateRequestMsgTLS13)
   585  		certReq.ocspStapling = true
   586  		certReq.scts = true
   587  		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   588  		if c.config.ClientCAs != nil {
   589  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   590  		}
   591  
   592  		hs.transcript.Write(certReq.marshal())
   593  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   594  			return err
   595  		}
   596  	}
   597  
   598  	certMsg := new(certificateMsgTLS13)
   599  
   600  	certMsg.certificate = *hs.cert
   601  	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
   602  	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
   603  
   604  	hs.transcript.Write(certMsg.marshal())
   605  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   606  		return err
   607  	}
   608  
   609  	certVerifyMsg := new(certificateVerifyMsg)
   610  	certVerifyMsg.hasSignatureAlgorithm = true
   611  	certVerifyMsg.signatureAlgorithm = hs.sigAlg
   612  
   613  	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
   614  	if err != nil {
   615  		return c.sendAlert(alertInternalError)
   616  	}
   617  
   618  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   619  	signOpts := crypto.SignerOpts(sigHash)
   620  	if sigType == signatureRSAPSS {
   621  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   622  	}
   623  	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   624  	if err != nil {
   625  		public := hs.cert.PrivateKey.(crypto.Signer).Public()
   626  		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
   627  			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
   628  			c.sendAlert(alertHandshakeFailure)
   629  		} else {
   630  			c.sendAlert(alertInternalError)
   631  		}
   632  		return errors.New("tls: failed to sign handshake: " + err.Error())
   633  	}
   634  	certVerifyMsg.signature = sig
   635  
   636  	hs.transcript.Write(certVerifyMsg.marshal())
   637  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   638  		return err
   639  	}
   640  
   641  	return nil
   642  }
   643  
   644  func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
   645  	c := hs.c
   646  
   647  	finished := &finishedMsg{
   648  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   649  	}
   650  
   651  	hs.transcript.Write(finished.marshal())
   652  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   653  		return err
   654  	}
   655  
   656  	// Derive secrets that take context through the server Finished.
   657  
   658  	hs.masterSecret = hs.suite.extract(nil,
   659  		hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
   660  
   661  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   662  		clientApplicationTrafficLabel, hs.transcript)
   663  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   664  		serverApplicationTrafficLabel, hs.transcript)
   665  	c.out.setTrafficSecret(hs.suite, serverSecret)
   666  
   667  	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
   668  	if err != nil {
   669  		c.sendAlert(alertInternalError)
   670  		return err
   671  	}
   672  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
   673  	if err != nil {
   674  		c.sendAlert(alertInternalError)
   675  		return err
   676  	}
   677  
   678  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   679  
   680  	// If we did not request client certificates, at this point we can
   681  	// precompute the client finished and roll the transcript forward to send
   682  	// session tickets in our first flight.
   683  	if !hs.requestClientCert() {
   684  		if err := hs.sendSessionTickets(); err != nil {
   685  			return err
   686  		}
   687  	}
   688  
   689  	return nil
   690  }
   691  
   692  func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
   693  	if hs.c.config.SessionTicketsDisabled {
   694  		return false
   695  	}
   696  
   697  	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
   698  	for _, pskMode := range hs.clientHello.pskModes {
   699  		if pskMode == pskModeDHE {
   700  			return true
   701  		}
   702  	}
   703  	return false
   704  }
   705  
   706  func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
   707  	c := hs.c
   708  
   709  	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   710  	finishedMsg := &finishedMsg{
   711  		verifyData: hs.clientFinished,
   712  	}
   713  	hs.transcript.Write(finishedMsg.marshal())
   714  
   715  	if !hs.shouldSendSessionTickets() {
   716  		return nil
   717  	}
   718  
   719  	resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
   720  		resumptionLabel, hs.transcript)
   721  
   722  	m := new(newSessionTicketMsgTLS13)
   723  
   724  	var certsFromClient [][]byte
   725  	for _, cert := range c.peerCertificates {
   726  		certsFromClient = append(certsFromClient, cert.Raw)
   727  	}
   728  	state := sessionStateTLS13{
   729  		cipherSuite:      hs.suite.id,
   730  		createdAt:        uint64(c.config.time().Unix()),
   731  		resumptionSecret: resumptionSecret,
   732  		certificate: Certificate{
   733  			Certificate:                 certsFromClient,
   734  			OCSPStaple:                  c.ocspResponse,
   735  			SignedCertificateTimestamps: c.scts,
   736  		},
   737  	}
   738  	var err error
   739  	m.label, err = c.encryptTicket(state.marshal())
   740  	if err != nil {
   741  		return err
   742  	}
   743  	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
   744  
   745  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   746  		return err
   747  	}
   748  
   749  	return nil
   750  }
   751  
   752  func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
   753  	c := hs.c
   754  
   755  	if !hs.requestClientCert() {
   756  		return nil
   757  	}
   758  
   759  	// If we requested a client certificate, then the client must send a
   760  	// certificate message. If it's empty, no CertificateVerify is sent.
   761  
   762  	msg, err := c.readHandshake()
   763  	if err != nil {
   764  		return err
   765  	}
   766  
   767  	certMsg, ok := msg.(*certificateMsgTLS13)
   768  	if !ok {
   769  		c.sendAlert(alertUnexpectedMessage)
   770  		return unexpectedMessageError(certMsg, msg)
   771  	}
   772  	hs.transcript.Write(certMsg.marshal())
   773  
   774  	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
   775  		return err
   776  	}
   777  
   778  	if len(certMsg.certificate.Certificate) != 0 {
   779  		msg, err = c.readHandshake()
   780  		if err != nil {
   781  			return err
   782  		}
   783  
   784  		certVerify, ok := msg.(*certificateVerifyMsg)
   785  		if !ok {
   786  			c.sendAlert(alertUnexpectedMessage)
   787  			return unexpectedMessageError(certVerify, msg)
   788  		}
   789  
   790  		// See RFC 8446, Section 4.4.3.
   791  		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
   792  			c.sendAlert(alertIllegalParameter)
   793  			return errors.New("tls: client certificate used with invalid signature algorithm")
   794  		}
   795  		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   796  		if err != nil {
   797  			return c.sendAlert(alertInternalError)
   798  		}
   799  		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   800  			c.sendAlert(alertIllegalParameter)
   801  			return errors.New("tls: client certificate used with invalid signature algorithm")
   802  		}
   803  		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   804  		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   805  			sigHash, signed, certVerify.signature); err != nil {
   806  			c.sendAlert(alertDecryptError)
   807  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   808  		}
   809  
   810  		hs.transcript.Write(certVerify.marshal())
   811  	}
   812  
   813  	// If we waited until the client certificates to send session tickets, we
   814  	// are ready to do it now.
   815  	if err := hs.sendSessionTickets(); err != nil {
   816  		return err
   817  	}
   818  
   819  	return nil
   820  }
   821  
   822  func (hs *serverHandshakeStateTLS13) readClientFinished() error {
   823  	c := hs.c
   824  
   825  	msg, err := c.readHandshake()
   826  	if err != nil {
   827  		return err
   828  	}
   829  
   830  	finished, ok := msg.(*finishedMsg)
   831  	if !ok {
   832  		c.sendAlert(alertUnexpectedMessage)
   833  		return unexpectedMessageError(finished, msg)
   834  	}
   835  
   836  	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
   837  		c.sendAlert(alertDecryptError)
   838  		return errors.New("tls: invalid client finished hash")
   839  	}
   840  
   841  	c.in.setTrafficSecret(hs.suite, hs.trafficSecret)
   842  
   843  	return nil
   844  }
   845  

View as plain text