github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/qtls-go1-15/handshake_server_tls13.go (about)

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