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