Black Lives Matter. Support the Equal Justice Initiative.

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  
   155  		// If the client does not seem to have hardware support for AES-GCM,
   156  		// prefer other AEAD ciphers even if we prioritized AES-GCM ciphers
   157  		// by default.
   158  		if !aesgcmPreferred(hs.clientHello.cipherSuites) {
   159  			preferenceList = deprioritizeAES(preferenceList)
   160  		}
   161  	} else {
   162  		preferenceList = hs.clientHello.cipherSuites
   163  		supportedList = defaultCipherSuitesTLS13()
   164  
   165  		// If we don't have hardware support for AES-GCM, prefer other AEAD
   166  		// ciphers even if the client prioritized AES-GCM.
   167  		if !hasAESGCMHardwareSupport {
   168  			preferenceList = deprioritizeAES(preferenceList)
   169  		}
   170  	}
   171  	for _, suiteID := range preferenceList {
   172  		hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID)
   173  		if hs.suite != nil {
   174  			break
   175  		}
   176  	}
   177  	if hs.suite == nil {
   178  		c.sendAlert(alertHandshakeFailure)
   179  		return errors.New("tls: no cipher suite supported by both client and server")
   180  	}
   181  	c.cipherSuite = hs.suite.id
   182  	hs.hello.cipherSuite = hs.suite.id
   183  	hs.transcript = hs.suite.hash.New()
   184  
   185  	// Pick the ECDHE group in server preference order, but give priority to
   186  	// groups with a key share, to avoid a HelloRetryRequest round-trip.
   187  	var selectedGroup CurveID
   188  	var clientKeyShare *keyShare
   189  GroupSelection:
   190  	for _, preferredGroup := range c.config.curvePreferences() {
   191  		for _, ks := range hs.clientHello.keyShares {
   192  			if ks.group == preferredGroup {
   193  				selectedGroup = ks.group
   194  				clientKeyShare = &ks
   195  				break GroupSelection
   196  			}
   197  		}
   198  		if selectedGroup != 0 {
   199  			continue
   200  		}
   201  		for _, group := range hs.clientHello.supportedCurves {
   202  			if group == preferredGroup {
   203  				selectedGroup = group
   204  				break
   205  			}
   206  		}
   207  	}
   208  	if selectedGroup == 0 {
   209  		c.sendAlert(alertHandshakeFailure)
   210  		return errors.New("tls: no ECDHE curve supported by both client and server")
   211  	}
   212  	if clientKeyShare == nil {
   213  		if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
   214  			return err
   215  		}
   216  		clientKeyShare = &hs.clientHello.keyShares[0]
   217  	}
   218  
   219  	if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
   220  		c.sendAlert(alertInternalError)
   221  		return errors.New("tls: CurvePreferences includes unsupported curve")
   222  	}
   223  	params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
   224  	if err != nil {
   225  		c.sendAlert(alertInternalError)
   226  		return err
   227  	}
   228  	hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
   229  	hs.sharedKey = params.SharedKey(clientKeyShare.data)
   230  	if hs.sharedKey == nil {
   231  		c.sendAlert(alertIllegalParameter)
   232  		return errors.New("tls: invalid client key share")
   233  	}
   234  
   235  	c.serverName = hs.clientHello.serverName
   236  	return nil
   237  }
   238  
   239  func (hs *serverHandshakeStateTLS13) checkForResumption() error {
   240  	c := hs.c
   241  
   242  	if c.config.SessionTicketsDisabled {
   243  		return nil
   244  	}
   245  
   246  	modeOK := false
   247  	for _, mode := range hs.clientHello.pskModes {
   248  		if mode == pskModeDHE {
   249  			modeOK = true
   250  			break
   251  		}
   252  	}
   253  	if !modeOK {
   254  		return nil
   255  	}
   256  
   257  	if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
   258  		c.sendAlert(alertIllegalParameter)
   259  		return errors.New("tls: invalid or missing PSK binders")
   260  	}
   261  	if len(hs.clientHello.pskIdentities) == 0 {
   262  		return nil
   263  	}
   264  
   265  	for i, identity := range hs.clientHello.pskIdentities {
   266  		if i >= maxClientPSKIdentities {
   267  			break
   268  		}
   269  
   270  		plaintext, _ := c.decryptTicket(identity.label)
   271  		if plaintext == nil {
   272  			continue
   273  		}
   274  		sessionState := new(sessionStateTLS13)
   275  		if ok := sessionState.unmarshal(plaintext); !ok {
   276  			continue
   277  		}
   278  
   279  		createdAt := time.Unix(int64(sessionState.createdAt), 0)
   280  		if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   281  			continue
   282  		}
   283  
   284  		// We don't check the obfuscated ticket age because it's affected by
   285  		// clock skew and it's only a freshness signal useful for shrinking the
   286  		// window for replay attacks, which don't affect us as we don't do 0-RTT.
   287  
   288  		pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
   289  		if pskSuite == nil || pskSuite.hash != hs.suite.hash {
   290  			continue
   291  		}
   292  
   293  		// PSK connections don't re-establish client certificates, but carry
   294  		// them over in the session ticket. Ensure the presence of client certs
   295  		// in the ticket is consistent with the configured requirements.
   296  		sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
   297  		needClientCerts := requiresClientCert(c.config.ClientAuth)
   298  		if needClientCerts && !sessionHasClientCerts {
   299  			continue
   300  		}
   301  		if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   302  			continue
   303  		}
   304  
   305  		psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
   306  			nil, hs.suite.hash.Size())
   307  		hs.earlySecret = hs.suite.extract(psk, nil)
   308  		binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
   309  		// Clone the transcript in case a HelloRetryRequest was recorded.
   310  		transcript := cloneHash(hs.transcript, hs.suite.hash)
   311  		if transcript == nil {
   312  			c.sendAlert(alertInternalError)
   313  			return errors.New("tls: internal error: failed to clone hash")
   314  		}
   315  		transcript.Write(hs.clientHello.marshalWithoutBinders())
   316  		pskBinder := hs.suite.finishedHash(binderKey, transcript)
   317  		if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
   318  			c.sendAlert(alertDecryptError)
   319  			return errors.New("tls: invalid PSK binder")
   320  		}
   321  
   322  		c.didResume = true
   323  		if err := c.processCertsFromClient(sessionState.certificate); err != nil {
   324  			return err
   325  		}
   326  
   327  		hs.hello.selectedIdentityPresent = true
   328  		hs.hello.selectedIdentity = uint16(i)
   329  		hs.usingPSK = true
   330  		return nil
   331  	}
   332  
   333  	return nil
   334  }
   335  
   336  // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
   337  // interfaces implemented by standard library hashes to clone the state of in
   338  // to a new instance of h. It returns nil if the operation fails.
   339  func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
   340  	// Recreate the interface to avoid importing encoding.
   341  	type binaryMarshaler interface {
   342  		MarshalBinary() (data []byte, err error)
   343  		UnmarshalBinary(data []byte) error
   344  	}
   345  	marshaler, ok := in.(binaryMarshaler)
   346  	if !ok {
   347  		return nil
   348  	}
   349  	state, err := marshaler.MarshalBinary()
   350  	if err != nil {
   351  		return nil
   352  	}
   353  	out := h.New()
   354  	unmarshaler, ok := out.(binaryMarshaler)
   355  	if !ok {
   356  		return nil
   357  	}
   358  	if err := unmarshaler.UnmarshalBinary(state); err != nil {
   359  		return nil
   360  	}
   361  	return out
   362  }
   363  
   364  func (hs *serverHandshakeStateTLS13) pickCertificate() error {
   365  	c := hs.c
   366  
   367  	// Only one of PSK and certificates are used at a time.
   368  	if hs.usingPSK {
   369  		return nil
   370  	}
   371  
   372  	// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3.
   373  	if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
   374  		return c.sendAlert(alertMissingExtension)
   375  	}
   376  
   377  	certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
   378  	if err != nil {
   379  		if err == errNoCertificates {
   380  			c.sendAlert(alertUnrecognizedName)
   381  		} else {
   382  			c.sendAlert(alertInternalError)
   383  		}
   384  		return err
   385  	}
   386  	hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
   387  	if err != nil {
   388  		// getCertificate returned a certificate that is unsupported or
   389  		// incompatible with the client's signature algorithms.
   390  		c.sendAlert(alertHandshakeFailure)
   391  		return err
   392  	}
   393  	hs.cert = certificate
   394  
   395  	return nil
   396  }
   397  
   398  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
   399  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
   400  func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
   401  	if hs.sentDummyCCS {
   402  		return nil
   403  	}
   404  	hs.sentDummyCCS = true
   405  
   406  	_, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
   407  	return err
   408  }
   409  
   410  func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
   411  	c := hs.c
   412  
   413  	// The first ClientHello gets double-hashed into the transcript upon a
   414  	// HelloRetryRequest. See RFC 8446, Section 4.4.1.
   415  	hs.transcript.Write(hs.clientHello.marshal())
   416  	chHash := hs.transcript.Sum(nil)
   417  	hs.transcript.Reset()
   418  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
   419  	hs.transcript.Write(chHash)
   420  
   421  	helloRetryRequest := &serverHelloMsg{
   422  		vers:              hs.hello.vers,
   423  		random:            helloRetryRequestRandom,
   424  		sessionId:         hs.hello.sessionId,
   425  		cipherSuite:       hs.hello.cipherSuite,
   426  		compressionMethod: hs.hello.compressionMethod,
   427  		supportedVersion:  hs.hello.supportedVersion,
   428  		selectedGroup:     selectedGroup,
   429  	}
   430  
   431  	hs.transcript.Write(helloRetryRequest.marshal())
   432  	if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
   433  		return err
   434  	}
   435  
   436  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   437  		return err
   438  	}
   439  
   440  	msg, err := c.readHandshake()
   441  	if err != nil {
   442  		return err
   443  	}
   444  
   445  	clientHello, ok := msg.(*clientHelloMsg)
   446  	if !ok {
   447  		c.sendAlert(alertUnexpectedMessage)
   448  		return unexpectedMessageError(clientHello, msg)
   449  	}
   450  
   451  	if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
   452  		c.sendAlert(alertIllegalParameter)
   453  		return errors.New("tls: client sent invalid key share in second ClientHello")
   454  	}
   455  
   456  	if clientHello.earlyData {
   457  		c.sendAlert(alertIllegalParameter)
   458  		return errors.New("tls: client indicated early data in second ClientHello")
   459  	}
   460  
   461  	if illegalClientHelloChange(clientHello, hs.clientHello) {
   462  		c.sendAlert(alertIllegalParameter)
   463  		return errors.New("tls: client illegally modified second ClientHello")
   464  	}
   465  
   466  	hs.clientHello = clientHello
   467  	return nil
   468  }
   469  
   470  // illegalClientHelloChange reports whether the two ClientHello messages are
   471  // different, with the exception of the changes allowed before and after a
   472  // HelloRetryRequest. See RFC 8446, Section 4.1.2.
   473  func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
   474  	if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
   475  		len(ch.cipherSuites) != len(ch1.cipherSuites) ||
   476  		len(ch.supportedCurves) != len(ch1.supportedCurves) ||
   477  		len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
   478  		len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
   479  		len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
   480  		return true
   481  	}
   482  	for i := range ch.supportedVersions {
   483  		if ch.supportedVersions[i] != ch1.supportedVersions[i] {
   484  			return true
   485  		}
   486  	}
   487  	for i := range ch.cipherSuites {
   488  		if ch.cipherSuites[i] != ch1.cipherSuites[i] {
   489  			return true
   490  		}
   491  	}
   492  	for i := range ch.supportedCurves {
   493  		if ch.supportedCurves[i] != ch1.supportedCurves[i] {
   494  			return true
   495  		}
   496  	}
   497  	for i := range ch.supportedSignatureAlgorithms {
   498  		if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
   499  			return true
   500  		}
   501  	}
   502  	for i := range ch.supportedSignatureAlgorithmsCert {
   503  		if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
   504  			return true
   505  		}
   506  	}
   507  	for i := range ch.alpnProtocols {
   508  		if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
   509  			return true
   510  		}
   511  	}
   512  	return ch.vers != ch1.vers ||
   513  		!bytes.Equal(ch.random, ch1.random) ||
   514  		!bytes.Equal(ch.sessionId, ch1.sessionId) ||
   515  		!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
   516  		ch.serverName != ch1.serverName ||
   517  		ch.ocspStapling != ch1.ocspStapling ||
   518  		!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
   519  		ch.ticketSupported != ch1.ticketSupported ||
   520  		!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
   521  		ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
   522  		!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
   523  		ch.scts != ch1.scts ||
   524  		!bytes.Equal(ch.cookie, ch1.cookie) ||
   525  		!bytes.Equal(ch.pskModes, ch1.pskModes)
   526  }
   527  
   528  func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
   529  	c := hs.c
   530  
   531  	hs.transcript.Write(hs.clientHello.marshal())
   532  	hs.transcript.Write(hs.hello.marshal())
   533  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   534  		return err
   535  	}
   536  
   537  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
   538  		return err
   539  	}
   540  
   541  	earlySecret := hs.earlySecret
   542  	if earlySecret == nil {
   543  		earlySecret = hs.suite.extract(nil, nil)
   544  	}
   545  	hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
   546  		hs.suite.deriveSecret(earlySecret, "derived", nil))
   547  
   548  	clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   549  		clientHandshakeTrafficLabel, hs.transcript)
   550  	c.in.setTrafficSecret(hs.suite, clientSecret)
   551  	serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
   552  		serverHandshakeTrafficLabel, hs.transcript)
   553  	c.out.setTrafficSecret(hs.suite, serverSecret)
   554  
   555  	err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
   556  	if err != nil {
   557  		c.sendAlert(alertInternalError)
   558  		return err
   559  	}
   560  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
   561  	if err != nil {
   562  		c.sendAlert(alertInternalError)
   563  		return err
   564  	}
   565  
   566  	encryptedExtensions := new(encryptedExtensionsMsg)
   567  
   568  	if len(hs.clientHello.alpnProtocols) > 0 {
   569  		if selectedProto := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); selectedProto != "" {
   570  			encryptedExtensions.alpnProtocol = selectedProto
   571  			c.clientProtocol = selectedProto
   572  		}
   573  	}
   574  
   575  	hs.transcript.Write(encryptedExtensions.marshal())
   576  	if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
   577  		return err
   578  	}
   579  
   580  	return nil
   581  }
   582  
   583  func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
   584  	return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
   585  }
   586  
   587  func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
   588  	c := hs.c
   589  
   590  	// Only one of PSK and certificates are used at a time.
   591  	if hs.usingPSK {
   592  		return nil
   593  	}
   594  
   595  	if hs.requestClientCert() {
   596  		// Request a client certificate
   597  		certReq := new(certificateRequestMsgTLS13)
   598  		certReq.ocspStapling = true
   599  		certReq.scts = true
   600  		certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   601  		if c.config.ClientCAs != nil {
   602  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   603  		}
   604  
   605  		hs.transcript.Write(certReq.marshal())
   606  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   607  			return err
   608  		}
   609  	}
   610  
   611  	certMsg := new(certificateMsgTLS13)
   612  
   613  	certMsg.certificate = *hs.cert
   614  	certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
   615  	certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
   616  
   617  	hs.transcript.Write(certMsg.marshal())
   618  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   619  		return err
   620  	}
   621  
   622  	certVerifyMsg := new(certificateVerifyMsg)
   623  	certVerifyMsg.hasSignatureAlgorithm = true
   624  	certVerifyMsg.signatureAlgorithm = hs.sigAlg
   625  
   626  	sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
   627  	if err != nil {
   628  		return c.sendAlert(alertInternalError)
   629  	}
   630  
   631  	signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
   632  	signOpts := crypto.SignerOpts(sigHash)
   633  	if sigType == signatureRSAPSS {
   634  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   635  	}
   636  	sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
   637  	if err != nil {
   638  		public := hs.cert.PrivateKey.(crypto.Signer).Public()
   639  		if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
   640  			rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS
   641  			c.sendAlert(alertHandshakeFailure)
   642  		} else {
   643  			c.sendAlert(alertInternalError)
   644  		}
   645  		return errors.New("tls: failed to sign handshake: " + err.Error())
   646  	}
   647  	certVerifyMsg.signature = sig
   648  
   649  	hs.transcript.Write(certVerifyMsg.marshal())
   650  	if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
   651  		return err
   652  	}
   653  
   654  	return nil
   655  }
   656  
   657  func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
   658  	c := hs.c
   659  
   660  	finished := &finishedMsg{
   661  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
   662  	}
   663  
   664  	hs.transcript.Write(finished.marshal())
   665  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   666  		return err
   667  	}
   668  
   669  	// Derive secrets that take context through the server Finished.
   670  
   671  	hs.masterSecret = hs.suite.extract(nil,
   672  		hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
   673  
   674  	hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
   675  		clientApplicationTrafficLabel, hs.transcript)
   676  	serverSecret := hs.suite.deriveSecret(hs.masterSecret,
   677  		serverApplicationTrafficLabel, hs.transcript)
   678  	c.out.setTrafficSecret(hs.suite, serverSecret)
   679  
   680  	err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
   681  	if err != nil {
   682  		c.sendAlert(alertInternalError)
   683  		return err
   684  	}
   685  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
   686  	if err != nil {
   687  		c.sendAlert(alertInternalError)
   688  		return err
   689  	}
   690  
   691  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
   692  
   693  	// If we did not request client certificates, at this point we can
   694  	// precompute the client finished and roll the transcript forward to send
   695  	// session tickets in our first flight.
   696  	if !hs.requestClientCert() {
   697  		if err := hs.sendSessionTickets(); err != nil {
   698  			return err
   699  		}
   700  	}
   701  
   702  	return nil
   703  }
   704  
   705  func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
   706  	if hs.c.config.SessionTicketsDisabled {
   707  		return false
   708  	}
   709  
   710  	// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9.
   711  	for _, pskMode := range hs.clientHello.pskModes {
   712  		if pskMode == pskModeDHE {
   713  			return true
   714  		}
   715  	}
   716  	return false
   717  }
   718  
   719  func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
   720  	c := hs.c
   721  
   722  	hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
   723  	finishedMsg := &finishedMsg{
   724  		verifyData: hs.clientFinished,
   725  	}
   726  	hs.transcript.Write(finishedMsg.marshal())
   727  
   728  	if !hs.shouldSendSessionTickets() {
   729  		return nil
   730  	}
   731  
   732  	resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
   733  		resumptionLabel, hs.transcript)
   734  
   735  	m := new(newSessionTicketMsgTLS13)
   736  
   737  	var certsFromClient [][]byte
   738  	for _, cert := range c.peerCertificates {
   739  		certsFromClient = append(certsFromClient, cert.Raw)
   740  	}
   741  	state := sessionStateTLS13{
   742  		cipherSuite:      hs.suite.id,
   743  		createdAt:        uint64(c.config.time().Unix()),
   744  		resumptionSecret: resumptionSecret,
   745  		certificate: Certificate{
   746  			Certificate:                 certsFromClient,
   747  			OCSPStaple:                  c.ocspResponse,
   748  			SignedCertificateTimestamps: c.scts,
   749  		},
   750  	}
   751  	var err error
   752  	m.label, err = c.encryptTicket(state.marshal())
   753  	if err != nil {
   754  		return err
   755  	}
   756  	m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
   757  
   758  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   759  		return err
   760  	}
   761  
   762  	return nil
   763  }
   764  
   765  func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
   766  	c := hs.c
   767  
   768  	if !hs.requestClientCert() {
   769  		// Make sure the connection is still being verified whether or not
   770  		// the server requested a client certificate.
   771  		if c.config.VerifyConnection != nil {
   772  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   773  				c.sendAlert(alertBadCertificate)
   774  				return err
   775  			}
   776  		}
   777  		return nil
   778  	}
   779  
   780  	// If we requested a client certificate, then the client must send a
   781  	// certificate message. If it's empty, no CertificateVerify is sent.
   782  
   783  	msg, err := c.readHandshake()
   784  	if err != nil {
   785  		return err
   786  	}
   787  
   788  	certMsg, ok := msg.(*certificateMsgTLS13)
   789  	if !ok {
   790  		c.sendAlert(alertUnexpectedMessage)
   791  		return unexpectedMessageError(certMsg, msg)
   792  	}
   793  	hs.transcript.Write(certMsg.marshal())
   794  
   795  	if err := c.processCertsFromClient(certMsg.certificate); err != nil {
   796  		return err
   797  	}
   798  
   799  	if c.config.VerifyConnection != nil {
   800  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   801  			c.sendAlert(alertBadCertificate)
   802  			return err
   803  		}
   804  	}
   805  
   806  	if len(certMsg.certificate.Certificate) != 0 {
   807  		msg, err = c.readHandshake()
   808  		if err != nil {
   809  			return err
   810  		}
   811  
   812  		certVerify, ok := msg.(*certificateVerifyMsg)
   813  		if !ok {
   814  			c.sendAlert(alertUnexpectedMessage)
   815  			return unexpectedMessageError(certVerify, msg)
   816  		}
   817  
   818  		// See RFC 8446, Section 4.4.3.
   819  		if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
   820  			c.sendAlert(alertIllegalParameter)
   821  			return errors.New("tls: client certificate used with invalid signature algorithm")
   822  		}
   823  		sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   824  		if err != nil {
   825  			return c.sendAlert(alertInternalError)
   826  		}
   827  		if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
   828  			c.sendAlert(alertIllegalParameter)
   829  			return errors.New("tls: client certificate used with invalid signature algorithm")
   830  		}
   831  		signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
   832  		if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
   833  			sigHash, signed, certVerify.signature); err != nil {
   834  			c.sendAlert(alertDecryptError)
   835  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   836  		}
   837  
   838  		hs.transcript.Write(certVerify.marshal())
   839  	}
   840  
   841  	// If we waited until the client certificates to send session tickets, we
   842  	// are ready to do it now.
   843  	if err := hs.sendSessionTickets(); err != nil {
   844  		return err
   845  	}
   846  
   847  	return nil
   848  }
   849  
   850  func (hs *serverHandshakeStateTLS13) readClientFinished() error {
   851  	c := hs.c
   852  
   853  	msg, err := c.readHandshake()
   854  	if err != nil {
   855  		return err
   856  	}
   857  
   858  	finished, ok := msg.(*finishedMsg)
   859  	if !ok {
   860  		c.sendAlert(alertUnexpectedMessage)
   861  		return unexpectedMessageError(finished, msg)
   862  	}
   863  
   864  	if !hmac.Equal(hs.clientFinished, finished.verifyData) {
   865  		c.sendAlert(alertDecryptError)
   866  		return errors.New("tls: invalid client finished hash")
   867  	}
   868  
   869  	c.in.setTrafficSecret(hs.suite, hs.trafficSecret)
   870  
   871  	return nil
   872  }
   873  

View as plain text