...

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

View as plain text