github.com/Psiphon-Labs/tls-tris@v0.0.0-20230824155421-58bf6d336a9a/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 tls
     6  
     7  import (
     8  	"bytes"
     9  	"crypto"
    10  	"crypto/ecdsa"
    11  	"crypto/rsa"
    12  	"crypto/subtle"
    13  	"crypto/x509"
    14  	"errors"
    15  	"fmt"
    16  	"io"
    17  	"net"
    18  	"strconv"
    19  	"strings"
    20  	"sync/atomic"
    21  )
    22  
    23  type clientHandshakeState struct {
    24  	c            *Conn
    25  	serverHello  *serverHelloMsg
    26  	hello        *clientHelloMsg
    27  	suite        *cipherSuite
    28  	masterSecret []byte
    29  	session      *ClientSessionState
    30  
    31  	// TLS 1.0-1.2 fields
    32  	finishedHash finishedHash
    33  
    34  	// TLS 1.3 fields
    35  	keySchedule *keySchedule13
    36  	privateKey  []byte
    37  }
    38  
    39  func makeClientHello(config *Config) (*clientHelloMsg, error) {
    40  	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
    41  		return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
    42  	}
    43  
    44  	nextProtosLength := 0
    45  	for _, proto := range config.NextProtos {
    46  		if l := len(proto); l == 0 || l > 255 {
    47  			return nil, errors.New("tls: invalid NextProtos value")
    48  		} else {
    49  			nextProtosLength += 1 + l
    50  		}
    51  	}
    52  
    53  	if nextProtosLength > 0xffff {
    54  		return nil, errors.New("tls: NextProtos values too large")
    55  	}
    56  
    57  	if config.ClientHelloPRNGSeed == nil {
    58  		return nil, errors.New("tls: missing Config.ClientHelloPRNGSeed")
    59  	}
    60  
    61  	hello := &clientHelloMsg{
    62  		vers:                         config.maxVersion(),
    63  		compressionMethods:           []uint8{compressionNone},
    64  		random:                       make([]byte, 32),
    65  		ocspStapling:                 true,
    66  		scts:                         true,
    67  		serverName:                   hostnameInSNI(config.ServerName),
    68  		supportedCurves:              config.curvePreferences(),
    69  		supportedPoints:              []uint8{pointFormatUncompressed},
    70  		nextProtoNeg:                 len(config.NextProtos) > 0,
    71  		secureRenegotiationSupported: true,
    72  		delegatedCredential:          config.AcceptDelegatedCredential,
    73  		alpnProtocols:                config.NextProtos,
    74  		extendedMSSupported:          config.UseExtendedMasterSecret,
    75  
    76  		// [Psiphon]
    77  		clientHelloPRNGSeed: config.ClientHelloPRNGSeed,
    78  	}
    79  	possibleCipherSuites := config.cipherSuites()
    80  	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
    81  
    82  NextCipherSuite:
    83  	for _, suiteId := range possibleCipherSuites {
    84  		for _, suite := range cipherSuites {
    85  			if suite.id != suiteId {
    86  				continue
    87  			}
    88  			// Don't advertise TLS 1.2-only cipher suites unless
    89  			// we're attempting TLS 1.2.
    90  			if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
    91  				continue NextCipherSuite
    92  			}
    93  			// Don't advertise TLS 1.3-only cipher suites unless
    94  			// we're attempting TLS 1.3.
    95  			if hello.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
    96  				continue NextCipherSuite
    97  			}
    98  			hello.cipherSuites = append(hello.cipherSuites, suiteId)
    99  			continue NextCipherSuite
   100  		}
   101  	}
   102  
   103  	_, err := io.ReadFull(config.rand(), hello.random)
   104  	if err != nil {
   105  		return nil, errors.New("tls: short read from Rand: " + err.Error())
   106  	}
   107  
   108  	if hello.vers >= VersionTLS12 {
   109  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   110  	}
   111  
   112  	if hello.vers >= VersionTLS13 {
   113  		// Version preference is indicated via "supported_extensions",
   114  		// set legacy_version to TLS 1.2 for backwards compatibility.
   115  		hello.vers = VersionTLS12
   116  		hello.supportedVersions = config.getSupportedVersions()
   117  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms13
   118  		hello.supportedSignatureAlgorithmsCert = supportedSigAlgorithmsCert(supportedSignatureAlgorithms13)
   119  	}
   120  
   121  	return hello, nil
   122  }
   123  
   124  // c.out.Mutex <= L; c.handshakeMutex <= L.
   125  func (c *Conn) clientHandshake() error {
   126  	if c.config == nil {
   127  		c.config = defaultConfig()
   128  	}
   129  
   130  	// This may be a renegotiation handshake, in which case some fields
   131  	// need to be reset.
   132  	c.didResume = false
   133  
   134  	hello, err := makeClientHello(c.config)
   135  	if err != nil {
   136  		return err
   137  	}
   138  
   139  	if c.handshakes > 0 {
   140  		hello.secureRenegotiation = c.clientFinished[:]
   141  	}
   142  
   143  	var session *ClientSessionState
   144  	var cacheKey string
   145  	sessionCache := c.config.ClientSessionCache
   146  	// TLS 1.3 has no session resumption based on session tickets.
   147  	if c.config.SessionTicketsDisabled || c.config.maxVersion() >= VersionTLS13 {
   148  		sessionCache = nil
   149  	}
   150  
   151  	if sessionCache != nil {
   152  		hello.ticketSupported = true
   153  	}
   154  
   155  	// Session resumption is not allowed if renegotiating because
   156  	// renegotiation is primarily used to allow a client to send a client
   157  	// certificate, which would be skipped if session resumption occurred.
   158  	if sessionCache != nil && c.handshakes == 0 {
   159  		// Try to resume a previously negotiated TLS session, if
   160  		// available.
   161  		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
   162  		candidateSession, ok := sessionCache.Get(cacheKey)
   163  		if ok {
   164  			// Check that the ciphersuite/version used for the
   165  			// previous session are still valid.
   166  			cipherSuiteOk := false
   167  			for _, id := range hello.cipherSuites {
   168  				if id == candidateSession.cipherSuite {
   169  					cipherSuiteOk = true
   170  					break
   171  				}
   172  			}
   173  
   174  			versOk := candidateSession.vers >= c.config.minVersion() &&
   175  				candidateSession.vers <= c.config.maxVersion()
   176  			if versOk && cipherSuiteOk {
   177  				session = candidateSession
   178  			}
   179  		}
   180  	}
   181  
   182  	if session != nil {
   183  		hello.sessionTicket = session.sessionTicket
   184  		// A random session ID is used to detect when the
   185  		// server accepted the ticket and is resuming a session
   186  		// (see RFC 5077).
   187  		hello.sessionId = make([]byte, 16)
   188  		if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
   189  			return errors.New("tls: short read from Rand: " + err.Error())
   190  		}
   191  	}
   192  
   193  	hs := &clientHandshakeState{
   194  		c:       c,
   195  		hello:   hello,
   196  		session: session,
   197  	}
   198  
   199  	var clientKS keyShare
   200  	if c.config.maxVersion() >= VersionTLS13 {
   201  		// Create one keyshare for the first default curve. If it is not
   202  		// appropriate, the server should raise a HRR.
   203  		defaultGroup := c.config.curvePreferences()[0]
   204  		hs.privateKey, clientKS, err = c.config.generateKeyShare(defaultGroup)
   205  		if err != nil {
   206  			c.sendAlert(alertInternalError)
   207  			return err
   208  		}
   209  		hello.keyShares = []keyShare{clientKS}
   210  		// middlebox compatibility mode, provide a non-empty session ID
   211  		hello.sessionId = make([]byte, 16)
   212  		if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
   213  			return errors.New("tls: short read from Rand: " + err.Error())
   214  		}
   215  	}
   216  
   217  	if err = hs.handshake(); err != nil {
   218  		return err
   219  	}
   220  
   221  	// If we had a successful handshake and hs.session is different from
   222  	// the one already cached - cache a new one
   223  	if sessionCache != nil && hs.session != nil && session != hs.session && c.vers < VersionTLS13 {
   224  		sessionCache.Put(cacheKey, hs.session)
   225  	}
   226  
   227  	return nil
   228  }
   229  
   230  // Does the handshake, either a full one or resumes old session.
   231  // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
   232  func (hs *clientHandshakeState) handshake() error {
   233  	c := hs.c
   234  
   235  	// send ClientHello
   236  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   237  		return err
   238  	}
   239  
   240  	msg, err := c.readHandshake()
   241  	if err != nil {
   242  		return err
   243  	}
   244  
   245  	var ok bool
   246  	if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
   247  		c.sendAlert(alertUnexpectedMessage)
   248  		return unexpectedMessageError(hs.serverHello, msg)
   249  	}
   250  
   251  	if err = hs.pickTLSVersion(); err != nil {
   252  		return err
   253  	}
   254  
   255  	if err = hs.pickCipherSuite(); err != nil {
   256  		return err
   257  	}
   258  
   259  	var isResume bool
   260  	if c.vers >= VersionTLS13 {
   261  		hs.keySchedule = newKeySchedule13(hs.suite, c.config, hs.hello.random)
   262  		hs.keySchedule.write(hs.hello.marshal())
   263  		hs.keySchedule.write(hs.serverHello.marshal())
   264  	} else {
   265  		isResume, err = hs.processServerHello()
   266  		if err != nil {
   267  			return err
   268  		}
   269  
   270  		hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   271  
   272  		// No signatures of the handshake are needed in a resumption.
   273  		// Otherwise, in a full handshake, if we don't have any certificates
   274  		// configured then we will never send a CertificateVerify message and
   275  		// thus no signatures are needed in that case either.
   276  		if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
   277  			hs.finishedHash.discardHandshakeBuffer()
   278  		}
   279  
   280  		hs.finishedHash.Write(hs.hello.marshal())
   281  		hs.finishedHash.Write(hs.serverHello.marshal())
   282  	}
   283  
   284  	c.buffering = true
   285  	if c.vers >= VersionTLS13 {
   286  		if err := hs.doTLS13Handshake(); err != nil {
   287  			return err
   288  		}
   289  		if _, err := c.flush(); err != nil {
   290  			return err
   291  		}
   292  	} else if isResume {
   293  		if err := hs.establishKeys(); err != nil {
   294  			return err
   295  		}
   296  		if err := hs.readSessionTicket(); err != nil {
   297  			return err
   298  		}
   299  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   300  			return err
   301  		}
   302  		c.clientFinishedIsFirst = false
   303  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   304  			return err
   305  		}
   306  		if _, err := c.flush(); err != nil {
   307  			return err
   308  		}
   309  	} else {
   310  		if err := hs.doFullHandshake(); err != nil {
   311  			return err
   312  		}
   313  		if err := hs.establishKeys(); err != nil {
   314  			return err
   315  		}
   316  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
   317  			return err
   318  		}
   319  		if _, err := c.flush(); err != nil {
   320  			return err
   321  		}
   322  		c.clientFinishedIsFirst = true
   323  		if err := hs.readSessionTicket(); err != nil {
   324  			return err
   325  		}
   326  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
   327  			return err
   328  		}
   329  	}
   330  
   331  	c.didResume = isResume
   332  	c.phase = handshakeConfirmed
   333  	atomic.StoreInt32(&c.handshakeConfirmed, 1)
   334  
   335  	// [Psiphon]
   336  	// https://github.com/golang/go/commit/e5b13401c6b19f58a8439f1019a80fe540c0c687
   337  	atomic.StoreUint32(&c.handshakeStatus, 1)
   338  
   339  	return nil
   340  }
   341  
   342  func (hs *clientHandshakeState) pickTLSVersion() error {
   343  	vers, ok := hs.c.config.pickVersion([]uint16{hs.serverHello.vers})
   344  	if !ok || vers < VersionTLS10 {
   345  		// TLS 1.0 is the minimum version supported as a client.
   346  		hs.c.sendAlert(alertProtocolVersion)
   347  		return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
   348  	}
   349  
   350  	hs.c.vers = vers
   351  	hs.c.haveVers = true
   352  
   353  	return nil
   354  }
   355  
   356  func (hs *clientHandshakeState) pickCipherSuite() error {
   357  	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
   358  		hs.c.sendAlert(alertHandshakeFailure)
   359  		return errors.New("tls: server chose an unconfigured cipher suite")
   360  	}
   361  	// Check that the chosen cipher suite matches the protocol version.
   362  	if hs.c.vers >= VersionTLS13 && hs.suite.flags&suiteTLS13 == 0 ||
   363  		hs.c.vers < VersionTLS13 && hs.suite.flags&suiteTLS13 != 0 {
   364  		hs.c.sendAlert(alertHandshakeFailure)
   365  		return errors.New("tls: server chose an inappropriate cipher suite")
   366  	}
   367  
   368  	hs.c.cipherSuite = hs.suite.id
   369  	return nil
   370  }
   371  
   372  // processCertsFromServer takes a chain of server certificates from a
   373  // Certificate message and verifies them.
   374  func (hs *clientHandshakeState) processCertsFromServer(certificates [][]byte) error {
   375  	c := hs.c
   376  	certs := make([]*x509.Certificate, len(certificates))
   377  	for i, asn1Data := range certificates {
   378  		cert, err := x509.ParseCertificate(asn1Data)
   379  		if err != nil {
   380  			c.sendAlert(alertBadCertificate)
   381  			return errors.New("tls: failed to parse certificate from server: " + err.Error())
   382  		}
   383  		certs[i] = cert
   384  	}
   385  
   386  	if !c.config.InsecureSkipVerify {
   387  		opts := x509.VerifyOptions{
   388  			Roots:         c.config.RootCAs,
   389  			CurrentTime:   c.config.time(),
   390  			DNSName:       c.config.ServerName,
   391  			Intermediates: x509.NewCertPool(),
   392  		}
   393  
   394  		for i, cert := range certs {
   395  			if i == 0 {
   396  				continue
   397  			}
   398  			opts.Intermediates.AddCert(cert)
   399  		}
   400  		var err error
   401  		c.verifiedChains, err = certs[0].Verify(opts)
   402  		if err != nil {
   403  			c.sendAlert(alertBadCertificate)
   404  			return err
   405  		}
   406  	}
   407  
   408  	if c.config.VerifyPeerCertificate != nil {
   409  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   410  			c.sendAlert(alertBadCertificate)
   411  			return err
   412  		}
   413  	}
   414  
   415  	switch certs[0].PublicKey.(type) {
   416  	case *rsa.PublicKey, *ecdsa.PublicKey:
   417  		break
   418  	default:
   419  		c.sendAlert(alertUnsupportedCertificate)
   420  		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
   421  	}
   422  
   423  	c.peerCertificates = certs
   424  	return nil
   425  }
   426  
   427  // processDelegatedCredentialFromServer unmarshals the delegated credential
   428  // offered by the server (if present) and validates it using the peer
   429  // certificate and the signature scheme (`scheme`) indicated by the server in
   430  // the "signature_scheme" extension.
   431  func (hs *clientHandshakeState) processDelegatedCredentialFromServer(serialized []byte, scheme SignatureScheme) error {
   432  	c := hs.c
   433  
   434  	var dc *delegatedCredential
   435  	var err error
   436  	if serialized != nil {
   437  		// Assert that the DC extension was indicated by the client.
   438  		if !hs.hello.delegatedCredential {
   439  			c.sendAlert(alertUnexpectedMessage)
   440  			return errors.New("tls: got delegated credential extension without indication")
   441  		}
   442  
   443  		// Parse the delegated credential.
   444  		dc, err = unmarshalDelegatedCredential(serialized)
   445  		if err != nil {
   446  			c.sendAlert(alertDecodeError)
   447  			return fmt.Errorf("tls: delegated credential: %s", err)
   448  		}
   449  	}
   450  
   451  	if dc != nil && !c.config.InsecureSkipVerify {
   452  		if v, err := dc.validate(c.peerCertificates[0], c.config.time()); err != nil {
   453  			c.sendAlert(alertIllegalParameter)
   454  			return fmt.Errorf("delegated credential: %s", err)
   455  		} else if !v {
   456  			c.sendAlert(alertIllegalParameter)
   457  			return errors.New("delegated credential: signature invalid")
   458  		} else if dc.cred.expectedVersion != hs.c.vers {
   459  			c.sendAlert(alertIllegalParameter)
   460  			return errors.New("delegated credential: protocol version mismatch")
   461  		} else if dc.cred.expectedCertVerifyAlgorithm != scheme {
   462  			c.sendAlert(alertIllegalParameter)
   463  			return errors.New("delegated credential: signature scheme mismatch")
   464  		}
   465  	}
   466  
   467  	c.verifiedDc = dc
   468  	return nil
   469  }
   470  
   471  func (hs *clientHandshakeState) doFullHandshake() error {
   472  	c := hs.c
   473  
   474  	msg, err := c.readHandshake()
   475  	if err != nil {
   476  		return err
   477  	}
   478  	certMsg, ok := msg.(*certificateMsg)
   479  	if !ok || len(certMsg.certificates) == 0 {
   480  		c.sendAlert(alertUnexpectedMessage)
   481  		return unexpectedMessageError(certMsg, msg)
   482  	}
   483  	hs.finishedHash.Write(certMsg.marshal())
   484  
   485  	if c.handshakes == 0 {
   486  		// If this is the first handshake on a connection, process and
   487  		// (optionally) verify the server's certificates.
   488  		if err := hs.processCertsFromServer(certMsg.certificates); err != nil {
   489  			return err
   490  		}
   491  	} else {
   492  		// This is a renegotiation handshake. We require that the
   493  		// server's identity (i.e. leaf certificate) is unchanged and
   494  		// thus any previous trust decision is still valid.
   495  		//
   496  		// See https://mitls.org/pages/attacks/3SHAKE for the
   497  		// motivation behind this requirement.
   498  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
   499  			c.sendAlert(alertBadCertificate)
   500  			return errors.New("tls: server's identity changed during renegotiation")
   501  		}
   502  	}
   503  
   504  	msg, err = c.readHandshake()
   505  	if err != nil {
   506  		return err
   507  	}
   508  
   509  	cs, ok := msg.(*certificateStatusMsg)
   510  	if ok {
   511  		// RFC4366 on Certificate Status Request:
   512  		// The server MAY return a "certificate_status" message.
   513  
   514  		if !hs.serverHello.ocspStapling {
   515  			// If a server returns a "CertificateStatus" message, then the
   516  			// server MUST have included an extension of type "status_request"
   517  			// with empty "extension_data" in the extended server hello.
   518  
   519  			c.sendAlert(alertUnexpectedMessage)
   520  			return errors.New("tls: received unexpected CertificateStatus message")
   521  		}
   522  		hs.finishedHash.Write(cs.marshal())
   523  
   524  		if cs.statusType == statusTypeOCSP {
   525  			c.ocspResponse = cs.response
   526  		}
   527  
   528  		msg, err = c.readHandshake()
   529  		if err != nil {
   530  			return err
   531  		}
   532  	}
   533  
   534  	keyAgreement := hs.suite.ka(c.vers)
   535  
   536  	// Set the public key used to verify the handshake.
   537  	pk := c.peerCertificates[0].PublicKey
   538  
   539  	skx, ok := msg.(*serverKeyExchangeMsg)
   540  	if ok {
   541  		hs.finishedHash.Write(skx.marshal())
   542  
   543  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, pk, skx)
   544  		if err != nil {
   545  			c.sendAlert(alertUnexpectedMessage)
   546  			return err
   547  		}
   548  
   549  		msg, err = c.readHandshake()
   550  		if err != nil {
   551  			return err
   552  		}
   553  	}
   554  
   555  	var chainToSend *Certificate
   556  	var certRequested bool
   557  	certReq, ok := msg.(*certificateRequestMsg)
   558  	if ok {
   559  		certRequested = true
   560  		hs.finishedHash.Write(certReq.marshal())
   561  
   562  		if chainToSend, err = hs.getCertificate(certReq); err != nil {
   563  			c.sendAlert(alertInternalError)
   564  			return err
   565  		}
   566  
   567  		msg, err = c.readHandshake()
   568  		if err != nil {
   569  			return err
   570  		}
   571  	}
   572  
   573  	shd, ok := msg.(*serverHelloDoneMsg)
   574  	if !ok {
   575  		c.sendAlert(alertUnexpectedMessage)
   576  		return unexpectedMessageError(shd, msg)
   577  	}
   578  	hs.finishedHash.Write(shd.marshal())
   579  
   580  	// If the server requested a certificate then we have to send a
   581  	// Certificate message, even if it's empty because we don't have a
   582  	// certificate to send.
   583  	if certRequested {
   584  		certMsg = new(certificateMsg)
   585  		certMsg.certificates = chainToSend.Certificate
   586  		hs.finishedHash.Write(certMsg.marshal())
   587  		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   588  			return err
   589  		}
   590  	}
   591  
   592  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, pk)
   593  	if err != nil {
   594  		c.sendAlert(alertInternalError)
   595  		return err
   596  	}
   597  	if ckx != nil {
   598  		hs.finishedHash.Write(ckx.marshal())
   599  		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
   600  			return err
   601  		}
   602  	}
   603  	c.useEMS = hs.serverHello.extendedMSSupported
   604  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random, hs.finishedHash, c.useEMS)
   605  
   606  	if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.hello.random, hs.masterSecret); err != nil {
   607  		c.sendAlert(alertInternalError)
   608  		return errors.New("tls: failed to write to key log: " + err.Error())
   609  	}
   610  
   611  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
   612  		certVerify := &certificateVerifyMsg{
   613  			hasSignatureAndHash: c.vers >= VersionTLS12,
   614  		}
   615  
   616  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
   617  		if !ok {
   618  			c.sendAlert(alertInternalError)
   619  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
   620  		}
   621  
   622  		signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
   623  		if err != nil {
   624  			c.sendAlert(alertInternalError)
   625  			return err
   626  		}
   627  		// SignatureAndHashAlgorithm was introduced in TLS 1.2.
   628  		if certVerify.hasSignatureAndHash {
   629  			certVerify.signatureAlgorithm = signatureAlgorithm
   630  		}
   631  		digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
   632  		if err != nil {
   633  			c.sendAlert(alertInternalError)
   634  			return err
   635  		}
   636  		signOpts := crypto.SignerOpts(hashFunc)
   637  		if sigType == signatureRSAPSS {
   638  			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
   639  		}
   640  		certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
   641  		if err != nil {
   642  			c.sendAlert(alertInternalError)
   643  			return err
   644  		}
   645  
   646  		hs.finishedHash.Write(certVerify.marshal())
   647  		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
   648  			return err
   649  		}
   650  	}
   651  
   652  	hs.finishedHash.discardHandshakeBuffer()
   653  
   654  	return nil
   655  }
   656  
   657  func (hs *clientHandshakeState) establishKeys() error {
   658  	c := hs.c
   659  
   660  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   661  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   662  	var clientCipher, serverCipher interface{}
   663  	var clientHash, serverHash macFunction
   664  	if hs.suite.cipher != nil {
   665  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
   666  		clientHash = hs.suite.mac(c.vers, clientMAC)
   667  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
   668  		serverHash = hs.suite.mac(c.vers, serverMAC)
   669  	} else {
   670  		clientCipher = hs.suite.aead(clientKey, clientIV)
   671  		serverCipher = hs.suite.aead(serverKey, serverIV)
   672  	}
   673  
   674  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
   675  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
   676  	return nil
   677  }
   678  
   679  func (hs *clientHandshakeState) serverResumedSession() bool {
   680  	// If the server responded with the same sessionId then it means the
   681  	// sessionTicket is being used to resume a TLS session.
   682  	return hs.session != nil && hs.hello.sessionId != nil &&
   683  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
   684  }
   685  
   686  func (hs *clientHandshakeState) processServerHello() (bool, error) {
   687  	c := hs.c
   688  
   689  	if hs.serverHello.compressionMethod != compressionNone {
   690  		c.sendAlert(alertUnexpectedMessage)
   691  		return false, errors.New("tls: server selected unsupported compression format")
   692  	}
   693  
   694  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
   695  		c.secureRenegotiation = true
   696  		if len(hs.serverHello.secureRenegotiation) != 0 {
   697  			c.sendAlert(alertHandshakeFailure)
   698  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   699  		}
   700  	}
   701  
   702  	if c.handshakes > 0 && c.secureRenegotiation {
   703  		var expectedSecureRenegotiation [24]byte
   704  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
   705  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
   706  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
   707  			c.sendAlert(alertHandshakeFailure)
   708  			return false, errors.New("tls: incorrect renegotiation extension contents")
   709  		}
   710  	}
   711  
   712  	if hs.serverHello.extendedMSSupported {
   713  		if hs.hello.extendedMSSupported {
   714  			c.useEMS = true
   715  		} else {
   716  			// server wants to calculate master secret in a different way than client
   717  			c.sendAlert(alertUnsupportedExtension)
   718  			return false, errors.New("tls: unexpected extension (EMS) received in SH")
   719  		}
   720  	}
   721  
   722  	clientDidNPN := hs.hello.nextProtoNeg
   723  	clientDidALPN := len(hs.hello.alpnProtocols) > 0
   724  	serverHasNPN := hs.serverHello.nextProtoNeg
   725  	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
   726  
   727  	if !clientDidNPN && serverHasNPN {
   728  		c.sendAlert(alertHandshakeFailure)
   729  		return false, errors.New("tls: server advertised unrequested NPN extension")
   730  	}
   731  
   732  	if !clientDidALPN && serverHasALPN {
   733  		c.sendAlert(alertHandshakeFailure)
   734  		return false, errors.New("tls: server advertised unrequested ALPN extension")
   735  	}
   736  
   737  	if serverHasNPN && serverHasALPN {
   738  		c.sendAlert(alertHandshakeFailure)
   739  		return false, errors.New("tls: server advertised both NPN and ALPN extensions")
   740  	}
   741  
   742  	if serverHasALPN {
   743  		c.clientProtocol = hs.serverHello.alpnProtocol
   744  		c.clientProtocolFallback = false
   745  	}
   746  	c.scts = hs.serverHello.scts
   747  
   748  	if !hs.serverResumedSession() {
   749  		return false, nil
   750  	}
   751  
   752  	if hs.session.useEMS != c.useEMS {
   753  		return false, errors.New("differing EMS state")
   754  	}
   755  
   756  	if hs.session.vers != c.vers {
   757  		c.sendAlert(alertHandshakeFailure)
   758  		return false, errors.New("tls: server resumed a session with a different version")
   759  	}
   760  
   761  	if hs.session.cipherSuite != hs.suite.id {
   762  		c.sendAlert(alertHandshakeFailure)
   763  		return false, errors.New("tls: server resumed a session with a different cipher suite")
   764  	}
   765  
   766  	// Restore masterSecret and peerCerts from previous state
   767  	hs.masterSecret = hs.session.masterSecret
   768  	c.peerCertificates = hs.session.serverCertificates
   769  	c.verifiedChains = hs.session.verifiedChains
   770  	return true, nil
   771  }
   772  
   773  func (hs *clientHandshakeState) readFinished(out []byte) error {
   774  	c := hs.c
   775  
   776  	c.readRecord(recordTypeChangeCipherSpec)
   777  	if c.in.err != nil {
   778  		return c.in.err
   779  	}
   780  
   781  	msg, err := c.readHandshake()
   782  	if err != nil {
   783  		return err
   784  	}
   785  	serverFinished, ok := msg.(*finishedMsg)
   786  	if !ok {
   787  		c.sendAlert(alertUnexpectedMessage)
   788  		return unexpectedMessageError(serverFinished, msg)
   789  	}
   790  
   791  	verify := hs.finishedHash.serverSum(hs.masterSecret)
   792  	if len(verify) != len(serverFinished.verifyData) ||
   793  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
   794  		c.sendAlert(alertDecryptError)
   795  		return errors.New("tls: server's Finished message was incorrect")
   796  	}
   797  	hs.finishedHash.Write(serverFinished.marshal())
   798  	copy(out, verify)
   799  	return nil
   800  }
   801  
   802  func (hs *clientHandshakeState) readSessionTicket() error {
   803  	if !hs.serverHello.ticketSupported {
   804  		return nil
   805  	}
   806  
   807  	c := hs.c
   808  	msg, err := c.readHandshake()
   809  	if err != nil {
   810  		return err
   811  	}
   812  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
   813  	if !ok {
   814  		c.sendAlert(alertUnexpectedMessage)
   815  		return unexpectedMessageError(sessionTicketMsg, msg)
   816  	}
   817  	hs.finishedHash.Write(sessionTicketMsg.marshal())
   818  
   819  	hs.session = &ClientSessionState{
   820  		sessionTicket:      sessionTicketMsg.ticket,
   821  		vers:               c.vers,
   822  		cipherSuite:        hs.suite.id,
   823  		masterSecret:       hs.masterSecret,
   824  		serverCertificates: c.peerCertificates,
   825  		verifiedChains:     c.verifiedChains,
   826  		useEMS:             c.useEMS,
   827  	}
   828  
   829  	return nil
   830  }
   831  
   832  func (hs *clientHandshakeState) sendFinished(out []byte) error {
   833  	c := hs.c
   834  
   835  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
   836  		return err
   837  	}
   838  	if hs.serverHello.nextProtoNeg {
   839  		nextProto := new(nextProtoMsg)
   840  		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
   841  		nextProto.proto = proto
   842  		c.clientProtocol = proto
   843  		c.clientProtocolFallback = fallback
   844  
   845  		hs.finishedHash.Write(nextProto.marshal())
   846  		if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
   847  			return err
   848  		}
   849  	}
   850  
   851  	finished := new(finishedMsg)
   852  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
   853  	hs.finishedHash.Write(finished.marshal())
   854  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
   855  		return err
   856  	}
   857  	copy(out, finished.verifyData)
   858  	return nil
   859  }
   860  
   861  // tls11SignatureSchemes contains the signature schemes that we synthesise for
   862  // a TLS <= 1.1 connection, based on the supported certificate types.
   863  var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
   864  
   865  const (
   866  	// tls11SignatureSchemesNumECDSA is the number of initial elements of
   867  	// tls11SignatureSchemes that use ECDSA.
   868  	tls11SignatureSchemesNumECDSA = 3
   869  	// tls11SignatureSchemesNumRSA is the number of trailing elements of
   870  	// tls11SignatureSchemes that use RSA.
   871  	tls11SignatureSchemesNumRSA = 4
   872  )
   873  
   874  func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
   875  	c := hs.c
   876  
   877  	var rsaAvail, ecdsaAvail bool
   878  	for _, certType := range certReq.certificateTypes {
   879  		switch certType {
   880  		case certTypeRSASign:
   881  			rsaAvail = true
   882  		case certTypeECDSASign:
   883  			ecdsaAvail = true
   884  		}
   885  	}
   886  
   887  	if c.config.GetClientCertificate != nil {
   888  		var signatureSchemes []SignatureScheme
   889  
   890  		if !certReq.hasSignatureAndHash {
   891  			// Prior to TLS 1.2, the signature schemes were not
   892  			// included in the certificate request message. In this
   893  			// case we use a plausible list based on the acceptable
   894  			// certificate types.
   895  			signatureSchemes = tls11SignatureSchemes
   896  			if !ecdsaAvail {
   897  				signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
   898  			}
   899  			if !rsaAvail {
   900  				signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
   901  			}
   902  		} else {
   903  			signatureSchemes = certReq.supportedSignatureAlgorithms
   904  		}
   905  
   906  		return c.config.GetClientCertificate(&CertificateRequestInfo{
   907  			AcceptableCAs:    certReq.certificateAuthorities,
   908  			SignatureSchemes: signatureSchemes,
   909  		})
   910  	}
   911  
   912  	// RFC 4346 on the certificateAuthorities field: A list of the
   913  	// distinguished names of acceptable certificate authorities.
   914  	// These distinguished names may specify a desired
   915  	// distinguished name for a root CA or for a subordinate CA;
   916  	// thus, this message can be used to describe both known roots
   917  	// and a desired authorization space. If the
   918  	// certificate_authorities list is empty then the client MAY
   919  	// send any certificate of the appropriate
   920  	// ClientCertificateType, unless there is some external
   921  	// arrangement to the contrary.
   922  
   923  	// We need to search our list of client certs for one
   924  	// where SignatureAlgorithm is acceptable to the server and the
   925  	// Issuer is in certReq.certificateAuthorities
   926  findCert:
   927  	for i, chain := range c.config.Certificates {
   928  		if !rsaAvail && !ecdsaAvail {
   929  			continue
   930  		}
   931  
   932  		for j, cert := range chain.Certificate {
   933  			x509Cert := chain.Leaf
   934  			// parse the certificate if this isn't the leaf
   935  			// node, or if chain.Leaf was nil
   936  			if j != 0 || x509Cert == nil {
   937  				var err error
   938  				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
   939  					c.sendAlert(alertInternalError)
   940  					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
   941  				}
   942  			}
   943  
   944  			switch {
   945  			case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
   946  			case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
   947  			default:
   948  				continue findCert
   949  			}
   950  
   951  			if len(certReq.certificateAuthorities) == 0 {
   952  				// they gave us an empty list, so just take the
   953  				// first cert from c.config.Certificates
   954  				return &chain, nil
   955  			}
   956  
   957  			for _, ca := range certReq.certificateAuthorities {
   958  				if bytes.Equal(x509Cert.RawIssuer, ca) {
   959  					return &chain, nil
   960  				}
   961  			}
   962  		}
   963  	}
   964  
   965  	// No acceptable certificate found. Don't send a certificate.
   966  	return new(Certificate), nil
   967  }
   968  
   969  // clientSessionCacheKey returns a key used to cache sessionTickets that could
   970  // be used to resume previously negotiated TLS sessions with a server.
   971  func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
   972  	if len(config.ServerName) > 0 {
   973  		return config.ServerName
   974  	}
   975  
   976  	// [Psiphon]
   977  	//
   978  	// In certain error conditions, serverAddr may be nil. In this case, since
   979  	// ServerName is blank, there is no valid session cache key. Calling code
   980  	// assumes clientSessionCacheKey always succeeds. To minimize changes to
   981  	// this tls fork, we return "" and no error.
   982  	//
   983  	// We assume the cache key won't be used for setting the cache, as the
   984  	// existing error condition in the conn should result in handshake
   985  	// failure. In the unlikely case of success and caching a session, the
   986  	// outcome could include future failure to renegotiate, although in the
   987  	// case of Psiphon, each connection has its own cache.
   988  	if serverAddr == nil {
   989  		return ""
   990  	}
   991  
   992  	return serverAddr.String()
   993  }
   994  
   995  // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
   996  // given list of possible protocols and a list of the preference order. The
   997  // first list must not be empty. It returns the resulting protocol and flag
   998  // indicating if the fallback case was reached.
   999  func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  1000  	for _, s := range preferenceProtos {
  1001  		for _, c := range protos {
  1002  			if s == c {
  1003  				return s, false
  1004  			}
  1005  		}
  1006  	}
  1007  
  1008  	return protos[0], true
  1009  }
  1010  
  1011  // hostnameInSNI converts name into an appropriate hostname for SNI.
  1012  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  1013  // See https://tools.ietf.org/html/rfc6066#section-3.
  1014  func hostnameInSNI(name string) string {
  1015  	host := name
  1016  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  1017  		host = host[1 : len(host)-1]
  1018  	}
  1019  	if i := strings.LastIndex(host, "%"); i > 0 {
  1020  		host = host[:i]
  1021  	}
  1022  	if net.ParseIP(host) != nil {
  1023  		return ""
  1024  	}
  1025  	for len(name) > 0 && name[len(name)-1] == '.' {
  1026  		name = name[:len(name)-1]
  1027  	}
  1028  	return name
  1029  }