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