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