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

     1  // Copyright 2009 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/ecdsa"
    12  	"crypto/ed25519"
    13  	"crypto/rsa"
    14  	"crypto/subtle"
    15  	"crypto/x509"
    16  	"errors"
    17  	"fmt"
    18  	"hash"
    19  	"io"
    20  	"net"
    21  	"strings"
    22  	"sync/atomic"
    23  	"time"
    24  
    25  	"golang.org/x/crypto/cryptobyte"
    26  )
    27  
    28  const clientSessionStateVersion = 1
    29  
    30  type clientHandshakeState struct {
    31  	c            *Conn
    32  	ctx          context.Context
    33  	serverHello  *serverHelloMsg
    34  	hello        *clientHelloMsg
    35  	suite        *cipherSuite
    36  	finishedHash finishedHash
    37  	masterSecret []byte
    38  	session      *clientSessionState
    39  }
    40  
    41  func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
    42  	config := c.config
    43  	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
    44  		return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
    45  	}
    46  
    47  	nextProtosLength := 0
    48  	for _, proto := range config.NextProtos {
    49  		if l := len(proto); l == 0 || l > 255 {
    50  			return nil, nil, errors.New("tls: invalid NextProtos value")
    51  		} else {
    52  			nextProtosLength += 1 + l
    53  		}
    54  	}
    55  	if nextProtosLength > 0xffff {
    56  		return nil, nil, errors.New("tls: NextProtos values too large")
    57  	}
    58  
    59  	var supportedVersions []uint16
    60  	var clientHelloVersion uint16
    61  	if c.extraConfig.usesAlternativeRecordLayer() {
    62  		if config.maxSupportedVersion() < VersionTLS13 {
    63  			return nil, nil, errors.New("tls: MaxVersion prevents QUIC from using TLS 1.3")
    64  		}
    65  		// Only offer TLS 1.3 when QUIC is used.
    66  		supportedVersions = []uint16{VersionTLS13}
    67  		clientHelloVersion = VersionTLS13
    68  	} else {
    69  		supportedVersions = config.supportedVersions()
    70  		if len(supportedVersions) == 0 {
    71  			return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
    72  		}
    73  		clientHelloVersion = config.maxSupportedVersion()
    74  	}
    75  
    76  	// The version at the beginning of the ClientHello was capped at TLS 1.2
    77  	// for compatibility reasons. The supported_versions extension is used
    78  	// to negotiate versions now. See RFC 8446, Section 4.2.1.
    79  	if clientHelloVersion > VersionTLS12 {
    80  		clientHelloVersion = VersionTLS12
    81  	}
    82  
    83  	hello := &clientHelloMsg{
    84  		vers:                         clientHelloVersion,
    85  		compressionMethods:           []uint8{compressionNone},
    86  		random:                       make([]byte, 32),
    87  		ocspStapling:                 true,
    88  		scts:                         true,
    89  		serverName:                   hostnameInSNI(config.ServerName),
    90  		supportedCurves:              config.curvePreferences(),
    91  		supportedPoints:              []uint8{pointFormatUncompressed},
    92  		secureRenegotiationSupported: true,
    93  		alpnProtocols:                config.NextProtos,
    94  		supportedVersions:            supportedVersions,
    95  	}
    96  
    97  	// [Psiphon]
    98  	if c.extraConfig != nil {
    99  		hello.PRNG = c.extraConfig.ClientHelloPRNG
   100  		if c.extraConfig.GetClientHelloRandom != nil {
   101  			helloRandom, err := c.extraConfig.GetClientHelloRandom()
   102  			if err == nil && len(helloRandom) != 32 {
   103  				err = errors.New("invalid length")
   104  			}
   105  			if err != nil {
   106  				return nil, nil, errors.New("tls: GetClientHelloRandom failed: " + err.Error())
   107  			}
   108  			copy(hello.random, helloRandom)
   109  		}
   110  	}
   111  
   112  	if c.handshakes > 0 {
   113  		hello.secureRenegotiation = c.clientFinished[:]
   114  	}
   115  
   116  	preferenceOrder := cipherSuitesPreferenceOrder
   117  	if !hasAESGCMHardwareSupport {
   118  		preferenceOrder = cipherSuitesPreferenceOrderNoAES
   119  	}
   120  	configCipherSuites := config.cipherSuites()
   121  	hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
   122  
   123  	for _, suiteId := range preferenceOrder {
   124  		suite := mutualCipherSuite(configCipherSuites, suiteId)
   125  		if suite == nil {
   126  			continue
   127  		}
   128  		// Don't advertise TLS 1.2-only cipher suites unless
   129  		// we're attempting TLS 1.2.
   130  		if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
   131  			continue
   132  		}
   133  		hello.cipherSuites = append(hello.cipherSuites, suiteId)
   134  	}
   135  
   136  	// [Psiphon]
   137  	var err error
   138  	if c.extraConfig == nil || c.extraConfig.GetClientHelloRandom == nil {
   139  
   140  		_, err = io.ReadFull(config.rand(), hello.random)
   141  		if err != nil {
   142  			return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
   143  		}
   144  	}
   145  
   146  	// A random session ID is used to detect when the server accepted a ticket
   147  	// and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
   148  	// a compatibility measure (see RFC 8446, Section 4.1.2).
   149  	if c.extraConfig == nil || c.extraConfig.AlternativeRecordLayer == nil {
   150  		hello.sessionId = make([]byte, 32)
   151  		if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
   152  			return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
   153  		}
   154  	}
   155  
   156  	if hello.vers >= VersionTLS12 {
   157  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   158  	}
   159  
   160  	var params ecdheParameters
   161  	if hello.supportedVersions[0] == VersionTLS13 {
   162  		var suites []uint16
   163  		for _, suiteID := range configCipherSuites {
   164  			for _, suite := range cipherSuitesTLS13 {
   165  				if suite.id == suiteID {
   166  					suites = append(suites, suiteID)
   167  				}
   168  			}
   169  		}
   170  		if len(suites) > 0 {
   171  			hello.cipherSuites = suites
   172  		} else {
   173  			if hasAESGCMHardwareSupport {
   174  				hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
   175  			} else {
   176  				hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
   177  			}
   178  		}
   179  
   180  		curveID := config.curvePreferences()[0]
   181  		if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
   182  			return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
   183  		}
   184  		params, err = generateECDHEParameters(config.rand(), curveID)
   185  		if err != nil {
   186  			return nil, nil, err
   187  		}
   188  		hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
   189  	}
   190  
   191  	if hello.supportedVersions[0] == VersionTLS13 && c.extraConfig != nil && c.extraConfig.GetExtensions != nil {
   192  		hello.additionalExtensions = c.extraConfig.GetExtensions(typeClientHello)
   193  	}
   194  
   195  	return hello, params, nil
   196  }
   197  
   198  func (c *Conn) clientHandshake(ctx context.Context) (err error) {
   199  	if c.config == nil {
   200  		c.config = fromConfig(defaultConfig())
   201  	}
   202  	c.setAlternativeRecordLayer()
   203  
   204  	// This may be a renegotiation handshake, in which case some fields
   205  	// need to be reset.
   206  	c.didResume = false
   207  
   208  	hello, ecdheParams, err := c.makeClientHello()
   209  	if err != nil {
   210  		return err
   211  	}
   212  	c.serverName = hello.serverName
   213  
   214  	cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
   215  	if cacheKey != "" && session != nil {
   216  		var deletedTicket bool
   217  		if session.vers == VersionTLS13 && hello.earlyData && c.extraConfig != nil && c.extraConfig.Enable0RTT {
   218  			// don't reuse a session ticket that enabled 0-RTT
   219  			c.config.ClientSessionCache.Put(cacheKey, nil)
   220  			deletedTicket = true
   221  
   222  			if suite := cipherSuiteTLS13ByID(session.cipherSuite); suite != nil {
   223  				h := suite.hash.New()
   224  				h.Write(hello.marshal())
   225  				clientEarlySecret := suite.deriveSecret(earlySecret, "c e traffic", h)
   226  				c.out.exportKey(Encryption0RTT, suite, clientEarlySecret)
   227  				if err := c.config.writeKeyLog(keyLogLabelEarlyTraffic, hello.random, clientEarlySecret); err != nil {
   228  					c.sendAlert(alertInternalError)
   229  					return err
   230  				}
   231  			}
   232  		}
   233  		if !deletedTicket {
   234  			defer func() {
   235  				// If we got a handshake failure when resuming a session, throw away
   236  				// the session ticket. See RFC 5077, Section 3.2.
   237  				//
   238  				// RFC 8446 makes no mention of dropping tickets on failure, but it
   239  				// does require servers to abort on invalid binders, so we need to
   240  				// delete tickets to recover from a corrupted PSK.
   241  				if err != nil {
   242  					c.config.ClientSessionCache.Put(cacheKey, nil)
   243  				}
   244  			}()
   245  		}
   246  	}
   247  
   248  	if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
   249  		return err
   250  	}
   251  
   252  	msg, err := c.readHandshake()
   253  	if err != nil {
   254  		return err
   255  	}
   256  
   257  	serverHello, ok := msg.(*serverHelloMsg)
   258  	if !ok {
   259  		c.sendAlert(alertUnexpectedMessage)
   260  		return unexpectedMessageError(serverHello, msg)
   261  	}
   262  
   263  	if err := c.pickTLSVersion(serverHello); err != nil {
   264  		return err
   265  	}
   266  
   267  	// If we are negotiating a protocol version that's lower than what we
   268  	// support, check for the server downgrade canaries.
   269  	// See RFC 8446, Section 4.1.3.
   270  	maxVers := c.config.maxSupportedVersion()
   271  	tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
   272  	tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
   273  	if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
   274  		maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
   275  		c.sendAlert(alertIllegalParameter)
   276  		return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
   277  	}
   278  
   279  	if c.vers == VersionTLS13 {
   280  		hs := &clientHandshakeStateTLS13{
   281  			c:           c,
   282  			ctx:         ctx,
   283  			serverHello: serverHello,
   284  			hello:       hello,
   285  			ecdheParams: ecdheParams,
   286  			session:     session,
   287  			earlySecret: earlySecret,
   288  			binderKey:   binderKey,
   289  		}
   290  
   291  		// In TLS 1.3, session tickets are delivered after the handshake.
   292  		return hs.handshake()
   293  	}
   294  
   295  	hs := &clientHandshakeState{
   296  		c:           c,
   297  		ctx:         ctx,
   298  		serverHello: serverHello,
   299  		hello:       hello,
   300  		session:     session,
   301  	}
   302  
   303  	if err := hs.handshake(); err != nil {
   304  		return err
   305  	}
   306  
   307  	// If we had a successful handshake and hs.session is different from
   308  	// the one already cached - cache a new one.
   309  	if cacheKey != "" && hs.session != nil && session != hs.session {
   310  		c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(hs.session))
   311  	}
   312  
   313  	return nil
   314  }
   315  
   316  // extract the app data saved in the session.nonce,
   317  // and set the session.nonce to the actual nonce value
   318  func (c *Conn) decodeSessionState(session *clientSessionState) (uint32 /* max early data */, []byte /* app data */, bool /* ok */) {
   319  	s := cryptobyte.String(session.nonce)
   320  	var version uint16
   321  	if !s.ReadUint16(&version) {
   322  		return 0, nil, false
   323  	}
   324  	if version != clientSessionStateVersion {
   325  		return 0, nil, false
   326  	}
   327  	var maxEarlyData uint32
   328  	if !s.ReadUint32(&maxEarlyData) {
   329  		return 0, nil, false
   330  	}
   331  	var appData []byte
   332  	if !readUint16LengthPrefixed(&s, &appData) {
   333  		return 0, nil, false
   334  	}
   335  	var nonce []byte
   336  	if !readUint16LengthPrefixed(&s, &nonce) {
   337  		return 0, nil, false
   338  	}
   339  	session.nonce = nonce
   340  	return maxEarlyData, appData, true
   341  }
   342  
   343  func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
   344  	session *clientSessionState, earlySecret, binderKey []byte) {
   345  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
   346  		return "", nil, nil, nil
   347  	}
   348  
   349  	hello.ticketSupported = true
   350  
   351  	if hello.supportedVersions[0] == VersionTLS13 {
   352  		// Require DHE on resumption as it guarantees forward secrecy against
   353  		// compromise of the session ticket key. See RFC 8446, Section 4.2.9.
   354  		hello.pskModes = []uint8{pskModeDHE}
   355  	}
   356  
   357  	// Session resumption is not allowed if renegotiating because
   358  	// renegotiation is primarily used to allow a client to send a client
   359  	// certificate, which would be skipped if session resumption occurred.
   360  	if c.handshakes != 0 {
   361  		return "", nil, nil, nil
   362  	}
   363  
   364  	// Try to resume a previously negotiated TLS session, if available.
   365  	cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   366  	sess, ok := c.config.ClientSessionCache.Get(cacheKey)
   367  	if !ok || sess == nil {
   368  		return cacheKey, nil, nil, nil
   369  	}
   370  	session = fromClientSessionState(sess)
   371  
   372  	var appData []byte
   373  	var maxEarlyData uint32
   374  	if session.vers == VersionTLS13 {
   375  		var ok bool
   376  		maxEarlyData, appData, ok = c.decodeSessionState(session)
   377  		if !ok { // delete it, if parsing failed
   378  			c.config.ClientSessionCache.Put(cacheKey, nil)
   379  			return cacheKey, nil, nil, nil
   380  		}
   381  	}
   382  
   383  	// Check that version used for the previous session is still valid.
   384  	versOk := false
   385  	for _, v := range hello.supportedVersions {
   386  		if v == session.vers {
   387  			versOk = true
   388  			break
   389  		}
   390  	}
   391  	if !versOk {
   392  		return cacheKey, nil, nil, nil
   393  	}
   394  
   395  	// Check that the cached server certificate is not expired, and that it's
   396  	// valid for the ServerName. This should be ensured by the cache key, but
   397  	// protect the application from a faulty ClientSessionCache implementation.
   398  	if !c.config.InsecureSkipVerify {
   399  		if len(session.verifiedChains) == 0 {
   400  			// The original connection had InsecureSkipVerify, while this doesn't.
   401  			return cacheKey, nil, nil, nil
   402  		}
   403  		serverCert := session.serverCertificates[0]
   404  		if c.config.time().After(serverCert.NotAfter) {
   405  			// Expired certificate, delete the entry.
   406  			c.config.ClientSessionCache.Put(cacheKey, nil)
   407  			return cacheKey, nil, nil, nil
   408  		}
   409  		if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
   410  			return cacheKey, nil, nil, nil
   411  		}
   412  	}
   413  
   414  	if session.vers != VersionTLS13 {
   415  		// In TLS 1.2 the cipher suite must match the resumed session. Ensure we
   416  		// are still offering it.
   417  		if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
   418  			return cacheKey, nil, nil, nil
   419  		}
   420  
   421  		hello.sessionTicket = session.sessionTicket
   422  		return
   423  	}
   424  
   425  	// Check that the session ticket is not expired.
   426  	if c.config.time().After(session.useBy) {
   427  		c.config.ClientSessionCache.Put(cacheKey, nil)
   428  		return cacheKey, nil, nil, nil
   429  	}
   430  
   431  	// In TLS 1.3 the KDF hash must match the resumed session. Ensure we
   432  	// offer at least one cipher suite with that hash.
   433  	cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
   434  	if cipherSuite == nil {
   435  		return cacheKey, nil, nil, nil
   436  	}
   437  	cipherSuiteOk := false
   438  	for _, offeredID := range hello.cipherSuites {
   439  		offeredSuite := cipherSuiteTLS13ByID(offeredID)
   440  		if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
   441  			cipherSuiteOk = true
   442  			break
   443  		}
   444  	}
   445  	if !cipherSuiteOk {
   446  		return cacheKey, nil, nil, nil
   447  	}
   448  
   449  	// Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
   450  	ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
   451  	identity := pskIdentity{
   452  		label:               session.sessionTicket,
   453  		obfuscatedTicketAge: ticketAge + session.ageAdd,
   454  	}
   455  	hello.pskIdentities = []pskIdentity{identity}
   456  	hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
   457  
   458  	// Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
   459  	psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
   460  		session.nonce, cipherSuite.hash.Size())
   461  	earlySecret = cipherSuite.extract(psk, nil)
   462  	binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
   463  	if c.extraConfig != nil {
   464  		hello.earlyData = c.extraConfig.Enable0RTT && maxEarlyData > 0
   465  	}
   466  	transcript := cipherSuite.hash.New()
   467  	transcript.Write(hello.marshalWithoutBinders())
   468  	pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
   469  	hello.updateBinders(pskBinders)
   470  
   471  	if session.vers == VersionTLS13 && c.extraConfig != nil && c.extraConfig.SetAppDataFromSessionState != nil {
   472  		c.extraConfig.SetAppDataFromSessionState(appData)
   473  	}
   474  	return
   475  }
   476  
   477  func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
   478  	peerVersion := serverHello.vers
   479  	if serverHello.supportedVersion != 0 {
   480  		peerVersion = serverHello.supportedVersion
   481  	}
   482  
   483  	vers, ok := c.config.mutualVersion([]uint16{peerVersion})
   484  	if !ok {
   485  		c.sendAlert(alertProtocolVersion)
   486  		return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
   487  	}
   488  
   489  	c.vers = vers
   490  	c.haveVers = true
   491  	c.in.version = vers
   492  	c.out.version = vers
   493  
   494  	return nil
   495  }
   496  
   497  // Does the handshake, either a full one or resumes old session. Requires hs.c,
   498  // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
   499  func (hs *clientHandshakeState) handshake() error {
   500  	c := hs.c
   501  
   502  	isResume, err := hs.processServerHello()
   503  	if err != nil {
   504  		return err
   505  	}
   506  
   507  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   508  
   509  	// No signatures of the handshake are needed in a resumption.
   510  	// Otherwise, in a full handshake, if we don't have any certificates
   511  	// configured then we will never send a CertificateVerify message and
   512  	// thus no signatures are needed in that case either.
   513  	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
   514  		hs.finishedHash.discardHandshakeBuffer()
   515  	}
   516  
   517  	hs.finishedHash.Write(hs.hello.marshal())
   518  	hs.finishedHash.Write(hs.serverHello.marshal())
   519  
   520  	c.buffering = true
   521  	c.didResume = isResume
   522  	if isResume {
   523  		if err := hs.establishKeys(); err != nil {
   524  			return err
   525  		}
   526  		if err := hs.readSessionTicket(); err != nil {
   527  			return err
   528  		}
   529  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   530  			return err
   531  		}
   532  		c.clientFinishedIsFirst = false
   533  		// Make sure the connection is still being verified whether or not this
   534  		// is a resumption. Resumptions currently don't reverify certificates so
   535  		// they don't call verifyServerCertificate. See Issue 31641.
   536  		if c.config.VerifyConnection != nil {
   537  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   538  				c.sendAlert(alertBadCertificate)
   539  				return err
   540  			}
   541  		}
   542  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   543  			return err
   544  		}
   545  		if _, err := c.flush(); err != nil {
   546  			return err
   547  		}
   548  	} else {
   549  		if err := hs.doFullHandshake(); err != nil {
   550  			return err
   551  		}
   552  		if err := hs.establishKeys(); err != nil {
   553  			return err
   554  		}
   555  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   556  			return err
   557  		}
   558  		if _, err := c.flush(); err != nil {
   559  			return err
   560  		}
   561  		c.clientFinishedIsFirst = true
   562  		if err := hs.readSessionTicket(); err != nil {
   563  			return err
   564  		}
   565  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   566  			return err
   567  		}
   568  	}
   569  
   570  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
   571  	atomic.StoreUint32(&c.handshakeStatus, 1)
   572  
   573  	return nil
   574  }
   575  
   576  func (hs *clientHandshakeState) pickCipherSuite() error {
   577  	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
   578  		hs.c.sendAlert(alertHandshakeFailure)
   579  		return errors.New("tls: server chose an unconfigured cipher suite")
   580  	}
   581  
   582  	hs.c.cipherSuite = hs.suite.id
   583  	return nil
   584  }
   585  
   586  func (hs *clientHandshakeState) doFullHandshake() error {
   587  	c := hs.c
   588  
   589  	msg, err := c.readHandshake()
   590  	if err != nil {
   591  		return err
   592  	}
   593  	certMsg, ok := msg.(*certificateMsg)
   594  	if !ok || len(certMsg.certificates) == 0 {
   595  		c.sendAlert(alertUnexpectedMessage)
   596  		return unexpectedMessageError(certMsg, msg)
   597  	}
   598  	hs.finishedHash.Write(certMsg.marshal())
   599  
   600  	msg, err = c.readHandshake()
   601  	if err != nil {
   602  		return err
   603  	}
   604  
   605  	cs, ok := msg.(*certificateStatusMsg)
   606  	if ok {
   607  		// RFC4366 on Certificate Status Request:
   608  		// The server MAY return a "certificate_status" message.
   609  
   610  		if !hs.serverHello.ocspStapling {
   611  			// If a server returns a "CertificateStatus" message, then the
   612  			// server MUST have included an extension of type "status_request"
   613  			// with empty "extension_data" in the extended server hello.
   614  
   615  			c.sendAlert(alertUnexpectedMessage)
   616  			return errors.New("tls: received unexpected CertificateStatus message")
   617  		}
   618  		hs.finishedHash.Write(cs.marshal())
   619  
   620  		c.ocspResponse = cs.response
   621  
   622  		msg, err = c.readHandshake()
   623  		if err != nil {
   624  			return err
   625  		}
   626  	}
   627  
   628  	if c.handshakes == 0 {
   629  		// If this is the first handshake on a connection, process and
   630  		// (optionally) verify the server's certificates.
   631  		if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
   632  			return err
   633  		}
   634  	} else {
   635  		// This is a renegotiation handshake. We require that the
   636  		// server's identity (i.e. leaf certificate) is unchanged and
   637  		// thus any previous trust decision is still valid.
   638  		//
   639  		// See https://mitls.org/pages/attacks/3SHAKE for the
   640  		// motivation behind this requirement.
   641  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
   642  			c.sendAlert(alertBadCertificate)
   643  			return errors.New("tls: server's identity changed during renegotiation")
   644  		}
   645  	}
   646  
   647  	keyAgreement := hs.suite.ka(c.vers)
   648  
   649  	skx, ok := msg.(*serverKeyExchangeMsg)
   650  	if ok {
   651  		hs.finishedHash.Write(skx.marshal())
   652  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
   653  		if err != nil {
   654  			c.sendAlert(alertUnexpectedMessage)
   655  			return err
   656  		}
   657  
   658  		msg, err = c.readHandshake()
   659  		if err != nil {
   660  			return err
   661  		}
   662  	}
   663  
   664  	var chainToSend *Certificate
   665  	var certRequested bool
   666  	certReq, ok := msg.(*certificateRequestMsg)
   667  	if ok {
   668  		certRequested = true
   669  		hs.finishedHash.Write(certReq.marshal())
   670  
   671  		cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
   672  		if chainToSend, err = c.getClientCertificate(cri); err != nil {
   673  			c.sendAlert(alertInternalError)
   674  			return err
   675  		}
   676  
   677  		msg, err = c.readHandshake()
   678  		if err != nil {
   679  			return err
   680  		}
   681  	}
   682  
   683  	shd, ok := msg.(*serverHelloDoneMsg)
   684  	if !ok {
   685  		c.sendAlert(alertUnexpectedMessage)
   686  		return unexpectedMessageError(shd, msg)
   687  	}
   688  	hs.finishedHash.Write(shd.marshal())
   689  
   690  	// If the server requested a certificate then we have to send a
   691  	// Certificate message, even if it's empty because we don't have a
   692  	// certificate to send.
   693  	if certRequested {
   694  		certMsg = new(certificateMsg)
   695  		certMsg.certificates = chainToSend.Certificate
   696  		hs.finishedHash.Write(certMsg.marshal())
   697  		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   698  			return err
   699  		}
   700  	}
   701  
   702  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
   703  	if err != nil {
   704  		c.sendAlert(alertInternalError)
   705  		return err
   706  	}
   707  	if ckx != nil {
   708  		hs.finishedHash.Write(ckx.marshal())
   709  		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
   710  			return err
   711  		}
   712  	}
   713  
   714  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   715  		certVerify := &certificateVerifyMsg{}
   716  
   717  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   718  		if !ok {
   719  			c.sendAlert(alertInternalError)
   720  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   721  		}
   722  
   723  		var sigType uint8
   724  		var sigHash crypto.Hash
   725  		if c.vers >= VersionTLS12 {
   726  			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
   727  			if err != nil {
   728  				c.sendAlert(alertIllegalParameter)
   729  				return err
   730  			}
   731  			sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
   732  			if err != nil {
   733  				return c.sendAlert(alertInternalError)
   734  			}
   735  			certVerify.hasSignatureAlgorithm = true
   736  			certVerify.signatureAlgorithm = signatureAlgorithm
   737  		} else {
   738  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
   739  			if err != nil {
   740  				c.sendAlert(alertIllegalParameter)
   741  				return err
   742  			}
   743  		}
   744  
   745  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
   746  		signOpts := crypto.SignerOpts(sigHash)
   747  		if sigType == signatureRSAPSS {
   748  			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
   749  		}
   750  		certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
   751  		if err != nil {
   752  			c.sendAlert(alertInternalError)
   753  			return err
   754  		}
   755  
   756  		hs.finishedHash.Write(certVerify.marshal())
   757  		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
   758  			return err
   759  		}
   760  	}
   761  
   762  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
   763  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
   764  		c.sendAlert(alertInternalError)
   765  		return errors.New("tls: failed to write to key log: " + err.Error())
   766  	}
   767  
   768  	hs.finishedHash.discardHandshakeBuffer()
   769  
   770  	return nil
   771  }
   772  
   773  func (hs *clientHandshakeState) establishKeys() error {
   774  	c := hs.c
   775  
   776  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   777  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   778  	var clientCipher, serverCipher interface{}
   779  	var clientHash, serverHash hash.Hash
   780  	if hs.suite.cipher != nil {
   781  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   782  		clientHash = hs.suite.mac(clientMAC)
   783  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   784  		serverHash = hs.suite.mac(serverMAC)
   785  	} else {
   786  		clientCipher = hs.suite.aead(clientKey, clientIV)
   787  		serverCipher = hs.suite.aead(serverKey, serverIV)
   788  	}
   789  
   790  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   791  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   792  	return nil
   793  }
   794  
   795  func (hs *clientHandshakeState) serverResumedSession() bool {
   796  	// If the server responded with the same sessionId then it means the
   797  	// sessionTicket is being used to resume a TLS session.
   798  	return hs.session != nil && hs.hello.sessionId != nil &&
   799  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   800  }
   801  
   802  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   803  	c := hs.c
   804  
   805  	if err := hs.pickCipherSuite(); err != nil {
   806  		return false, err
   807  	}
   808  
   809  	if hs.serverHello.compressionMethod != compressionNone {
   810  		c.sendAlert(alertUnexpectedMessage)
   811  		return false, errors.New("tls: server selected unsupported compression format")
   812  	}
   813  
   814  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   815  		c.secureRenegotiation = true
   816  		if len(hs.serverHello.secureRenegotiation) != 0 {
   817  			c.sendAlert(alertHandshakeFailure)
   818  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   819  		}
   820  	}
   821  
   822  	if c.handshakes > 0 && c.secureRenegotiation {
   823  		var expectedSecureRenegotiation [24]byte
   824  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   825  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   826  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   827  			c.sendAlert(alertHandshakeFailure)
   828  			return false, errors.New("tls: incorrect renegotiation extension contents")
   829  		}
   830  	}
   831  
   832  	if hs.serverHello.alpnProtocol != "" {
   833  		if len(hs.hello.alpnProtocols) == 0 {
   834  			c.sendAlert(alertUnsupportedExtension)
   835  			return false, errors.New("tls: server advertised unrequested ALPN extension")
   836  		}
   837  		if mutualProtocol([]string{hs.serverHello.alpnProtocol}, hs.hello.alpnProtocols) == "" {
   838  			c.sendAlert(alertUnsupportedExtension)
   839  			return false, errors.New("tls: server selected unadvertised ALPN protocol")
   840  		}
   841  		c.clientProtocol = hs.serverHello.alpnProtocol
   842  	}
   843  
   844  	c.scts = hs.serverHello.scts
   845  
   846  	if !hs.serverResumedSession() {
   847  		return false, nil
   848  	}
   849  
   850  	if hs.session.vers != c.vers {
   851  		c.sendAlert(alertHandshakeFailure)
   852  		return false, errors.New("tls: server resumed a session with a different version")
   853  	}
   854  
   855  	if hs.session.cipherSuite != hs.suite.id {
   856  		c.sendAlert(alertHandshakeFailure)
   857  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   858  	}
   859  
   860  	// Restore masterSecret, peerCerts, and ocspResponse from previous state
   861  	hs.masterSecret = hs.session.masterSecret
   862  	c.peerCertificates = hs.session.serverCertificates
   863  	c.verifiedChains = hs.session.verifiedChains
   864  	c.ocspResponse = hs.session.ocspResponse
   865  	// Let the ServerHello SCTs override the session SCTs from the original
   866  	// connection, if any are provided
   867  	if len(c.scts) == 0 && len(hs.session.scts) != 0 {
   868  		c.scts = hs.session.scts
   869  	}
   870  
   871  	return true, nil
   872  }
   873  
   874  func (hs *clientHandshakeState) readFinished(out []byte) error {
   875  	c := hs.c
   876  
   877  	if err := c.readChangeCipherSpec(); err != nil {
   878  		return err
   879  	}
   880  
   881  	msg, err := c.readHandshake()
   882  	if err != nil {
   883  		return err
   884  	}
   885  	serverFinished, ok := msg.(*finishedMsg)
   886  	if !ok {
   887  		c.sendAlert(alertUnexpectedMessage)
   888  		return unexpectedMessageError(serverFinished, msg)
   889  	}
   890  
   891  	verify := hs.finishedHash.serverSum(hs.masterSecret)
   892  	if len(verify) != len(serverFinished.verifyData) ||
   893  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
   894  		c.sendAlert(alertHandshakeFailure)
   895  		return errors.New("tls: server's Finished message was incorrect")
   896  	}
   897  	hs.finishedHash.Write(serverFinished.marshal())
   898  	copy(out, verify)
   899  	return nil
   900  }
   901  
   902  func (hs *clientHandshakeState) readSessionTicket() error {
   903  	if !hs.serverHello.ticketSupported {
   904  		return nil
   905  	}
   906  
   907  	c := hs.c
   908  	msg, err := c.readHandshake()
   909  	if err != nil {
   910  		return err
   911  	}
   912  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
   913  	if !ok {
   914  		c.sendAlert(alertUnexpectedMessage)
   915  		return unexpectedMessageError(sessionTicketMsg, msg)
   916  	}
   917  	hs.finishedHash.Write(sessionTicketMsg.marshal())
   918  
   919  	hs.session = &clientSessionState{
   920  		sessionTicket:      sessionTicketMsg.ticket,
   921  		vers:               c.vers,
   922  		cipherSuite:        hs.suite.id,
   923  		masterSecret:       hs.masterSecret,
   924  		serverCertificates: c.peerCertificates,
   925  		verifiedChains:     c.verifiedChains,
   926  		receivedAt:         c.config.time(),
   927  		ocspResponse:       c.ocspResponse,
   928  		scts:               c.scts,
   929  	}
   930  
   931  	return nil
   932  }
   933  
   934  func (hs *clientHandshakeState) sendFinished(out []byte) error {
   935  	c := hs.c
   936  
   937  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   938  		return err
   939  	}
   940  
   941  	finished := new(finishedMsg)
   942  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
   943  	hs.finishedHash.Write(finished.marshal())
   944  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   945  		return err
   946  	}
   947  	copy(out, finished.verifyData)
   948  	return nil
   949  }
   950  
   951  // verifyServerCertificate parses and verifies the provided chain, setting
   952  // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
   953  func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
   954  	certs := make([]*x509.Certificate, len(certificates))
   955  	for i, asn1Data := range certificates {
   956  		cert, err := x509.ParseCertificate(asn1Data)
   957  		if err != nil {
   958  			c.sendAlert(alertBadCertificate)
   959  			return errors.New("tls: failed to parse certificate from server: " + err.Error())
   960  		}
   961  		certs[i] = cert
   962  	}
   963  
   964  	if !c.config.InsecureSkipVerify {
   965  		opts := x509.VerifyOptions{
   966  			Roots:         c.config.RootCAs,
   967  			CurrentTime:   c.config.time(),
   968  			DNSName:       c.config.ServerName,
   969  			Intermediates: x509.NewCertPool(),
   970  		}
   971  		for _, cert := range certs[1:] {
   972  			opts.Intermediates.AddCert(cert)
   973  		}
   974  		var err error
   975  		c.verifiedChains, err = certs[0].Verify(opts)
   976  		if err != nil {
   977  			c.sendAlert(alertBadCertificate)
   978  			return err
   979  		}
   980  	}
   981  
   982  	switch certs[0].PublicKey.(type) {
   983  	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
   984  		break
   985  	default:
   986  		c.sendAlert(alertUnsupportedCertificate)
   987  		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
   988  	}
   989  
   990  	c.peerCertificates = certs
   991  
   992  	if c.config.VerifyPeerCertificate != nil {
   993  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   994  			c.sendAlert(alertBadCertificate)
   995  			return err
   996  		}
   997  	}
   998  
   999  	if c.config.VerifyConnection != nil {
  1000  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  1001  			c.sendAlert(alertBadCertificate)
  1002  			return err
  1003  		}
  1004  	}
  1005  
  1006  	return nil
  1007  }
  1008  
  1009  // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  1010  // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  1011  func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
  1012  	cri := &certificateRequestInfo{
  1013  		AcceptableCAs: certReq.certificateAuthorities,
  1014  		Version:       vers,
  1015  		ctx:           ctx,
  1016  	}
  1017  
  1018  	var rsaAvail, ecAvail bool
  1019  	for _, certType := range certReq.certificateTypes {
  1020  		switch certType {
  1021  		case certTypeRSASign:
  1022  			rsaAvail = true
  1023  		case certTypeECDSASign:
  1024  			ecAvail = true
  1025  		}
  1026  	}
  1027  
  1028  	if !certReq.hasSignatureAlgorithm {
  1029  		// Prior to TLS 1.2, signature schemes did not exist. In this case we
  1030  		// make up a list based on the acceptable certificate types, to help
  1031  		// GetClientCertificate and SupportsCertificate select the right certificate.
  1032  		// The hash part of the SignatureScheme is a lie here, because
  1033  		// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
  1034  		switch {
  1035  		case rsaAvail && ecAvail:
  1036  			cri.SignatureSchemes = []SignatureScheme{
  1037  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1038  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1039  			}
  1040  		case rsaAvail:
  1041  			cri.SignatureSchemes = []SignatureScheme{
  1042  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
  1043  			}
  1044  		case ecAvail:
  1045  			cri.SignatureSchemes = []SignatureScheme{
  1046  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
  1047  			}
  1048  		}
  1049  		return toCertificateRequestInfo(cri)
  1050  	}
  1051  
  1052  	// Filter the signature schemes based on the certificate types.
  1053  	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
  1054  	cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
  1055  	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
  1056  		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
  1057  		if err != nil {
  1058  			continue
  1059  		}
  1060  		switch sigType {
  1061  		case signatureECDSA, signatureEd25519:
  1062  			if ecAvail {
  1063  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1064  			}
  1065  		case signatureRSAPSS, signaturePKCS1v15:
  1066  			if rsaAvail {
  1067  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  1068  			}
  1069  		}
  1070  	}
  1071  
  1072  	return toCertificateRequestInfo(cri)
  1073  }
  1074  
  1075  func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
  1076  	if c.config.GetClientCertificate != nil {
  1077  		return c.config.GetClientCertificate(cri)
  1078  	}
  1079  
  1080  	for _, chain := range c.config.Certificates {
  1081  		if err := cri.SupportsCertificate(&chain); err != nil {
  1082  			continue
  1083  		}
  1084  		return &chain, nil
  1085  	}
  1086  
  1087  	// No acceptable certificate found. Don't send a certificate.
  1088  	return new(Certificate), nil
  1089  }
  1090  
  1091  const clientSessionCacheKeyPrefix = "qtls-"
  1092  
  1093  // clientSessionCacheKey returns a key used to cache sessionTickets that could
  1094  // be used to resume previously negotiated TLS sessions with a server.
  1095  func clientSessionCacheKey(serverAddr net.Addr, config *config) string {
  1096  	if len(config.ServerName) > 0 {
  1097  		return clientSessionCacheKeyPrefix + config.ServerName
  1098  	}
  1099  	return clientSessionCacheKeyPrefix + serverAddr.String()
  1100  }
  1101  
  1102  // mutualProtocol finds the mutual ALPN protocol given list of possible
  1103  // protocols and a list of the preference order.
  1104  func mutualProtocol(protos, preferenceProtos []string) string {
  1105  	for _, s := range preferenceProtos {
  1106  		for _, c := range protos {
  1107  			if s == c {
  1108  				return s
  1109  			}
  1110  		}
  1111  	}
  1112  	return ""
  1113  }
  1114  
  1115  // hostnameInSNI converts name into an appropriate hostname for SNI.
  1116  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  1117  // See RFC 6066, Section 3.
  1118  func hostnameInSNI(name string) string {
  1119  	host := name
  1120  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  1121  		host = host[1 : len(host)-1]
  1122  	}
  1123  	if i := strings.LastIndex(host, "%"); i > 0 {
  1124  		host = host[:i]
  1125  	}
  1126  	if net.ParseIP(host) != nil {
  1127  		return ""
  1128  	}
  1129  	for len(name) > 0 && name[len(name)-1] == '.' {
  1130  		name = name[:len(name)-1]
  1131  	}
  1132  	return name
  1133  }