github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/tls-tris/handshake_server.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  	"sync/atomic"
    19  	"time"
    20  )
    21  
    22  // serverHandshakeState contains details of a server handshake in progress.
    23  // It's discarded once the handshake has completed.
    24  type serverHandshakeState struct {
    25  	c                     *Conn
    26  	suite                 *cipherSuite
    27  	masterSecret          []byte
    28  	cachedClientHelloInfo *ClientHelloInfo
    29  	clientHello           *clientHelloMsg
    30  	hello                 *serverHelloMsg
    31  	cert                  *Certificate
    32  	privateKey            crypto.PrivateKey
    33  
    34  	// A marshalled DelegatedCredential to be sent to the client in the
    35  	// handshake.
    36  	delegatedCredential []byte
    37  
    38  	// TLS 1.0-1.2 fields
    39  	ellipticOk      bool
    40  	ecdsaOk         bool
    41  	rsaDecryptOk    bool
    42  	rsaSignOk       bool
    43  	sessionState    *sessionState
    44  	finishedHash    finishedHash
    45  	certsFromClient [][]byte
    46  
    47  	// TLS 1.3 fields
    48  	hello13Enc        *encryptedExtensionsMsg
    49  	keySchedule       *keySchedule13
    50  	clientFinishedKey []byte
    51  	hsClientCipher    interface{}
    52  	appClientCipher   interface{}
    53  }
    54  
    55  // serverHandshake performs a TLS handshake as a server.
    56  // c.out.Mutex <= L; c.handshakeMutex <= L.
    57  func (c *Conn) serverHandshake() error {
    58  	// If this is the first server handshake, we generate a random key to
    59  	// encrypt the tickets with.
    60  	c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
    61  
    62  	hs := serverHandshakeState{
    63  		c: c,
    64  	}
    65  	c.in.traceErr = hs.traceErr
    66  	c.out.traceErr = hs.traceErr
    67  	isResume, err := hs.readClientHello()
    68  
    69  	// [Psiphon]
    70  	// The ClientHello with the passthrough message is now available. Route the
    71  	// client to passthrough based on message inspection. This code assumes the
    72  	// client TCP conn has been wrapped with recordingConn, which has recorded
    73  	// all bytes sent by the client, which will be replayed, byte-for-byte, to
    74  	// the passthrough; as a result, passthrough clients will perform their TLS
    75  	// handshake with the passthrough target, receive its certificate, and in the
    76  	// case of HTTPS, receive the passthrough target's HTTP responses.
    77  	//
    78  	// Passthrough is also triggered if readClientHello fails. E.g., on other
    79  	// invalid input cases including "tls: handshake message of length..." or if
    80  	// the ClientHello is otherwise invalid. This ensures that clients sending
    81  	// random data will be relayed to the passthrough and not receive a
    82  	// distinguishing error response.
    83  	//
    84  	// The `tls` API performs handshakes on demand. E.g., the first call to
    85  	// tls.Conn.Read will perform a handshake if it's not yet been performed.
    86  	// Consumers such as `http` may call Read and then Close. To minimize code
    87  	// changes, in the passthrough case the ownership of Conn.conn, the client
    88  	// TCP conn, is transferred to the passthrough relay and a closedConn is
    89  	// substituted for Conn.conn. This allows the remaining `tls` code paths to
    90  	// continue reference a net.Conn, albeit one that is closed, so Reads and
    91  	// Writes will fail.
    92  
    93  	if c.config.PassthroughAddress != "" {
    94  
    95  		doPassthrough := false
    96  
    97  		if err != nil {
    98  			doPassthrough = true
    99  			err = fmt.Errorf("passthrough: %s", err)
   100  		}
   101  
   102  		clientAddr := c.conn.RemoteAddr().String()
   103  		clientIP, _, _ := net.SplitHostPort(clientAddr)
   104  
   105  		if !doPassthrough {
   106  			if !c.config.PassthroughVerifyMessage(hs.clientHello.random) {
   107  
   108  				c.config.PassthroughLogInvalidMessage(clientIP)
   109  
   110  				doPassthrough = true
   111  				err = errors.New("passthrough: invalid client random")
   112  			}
   113  		}
   114  
   115  		if !doPassthrough {
   116  			if !c.config.PassthroughHistoryAddNew(
   117  				clientIP, hs.clientHello.random) {
   118  
   119  				doPassthrough = true
   120  				err = errors.New("passthrough: duplicate client random")
   121  			}
   122  		}
   123  
   124  		// Call GetReadBuffer, in both passthrough and non-passthrough cases, to
   125  		// stop buffering all read bytes.
   126  
   127  		passthroughReadBuffer := c.conn.(*recorderConn).GetReadBuffer().Bytes()
   128  
   129  		if doPassthrough {
   130  
   131  			// When performing passthrough, we must exit at the "return err" below.
   132  			// This is a failsafe to ensure err is always set.
   133  			if err == nil {
   134  				err = errors.New("passthrough: missing error")
   135  			}
   136  
   137  			// Modifying c.conn directly is safe only because Conn.Handshake, which
   138  			// calls Conn.serverHandshake, is holding c.handshakeMutex and c.in locks,
   139  			// and because of the serial nature of c.conn access during the handshake
   140  			// sequence.
   141  			conn := c.conn
   142  			c.conn = newClosedConn(conn)
   143  
   144  			go func() {
   145  
   146  				// Perform the passthrough relay.
   147  				//
   148  				// Limitations:
   149  				//
   150  				// - The local TCP stack may differ from passthrough target in a
   151  				//   detectable way.
   152  				//
   153  				// - There may be detectable timing characteristics due to the network hop
   154  				//   to the passthrough target.
   155  				//
   156  				// - Application-level socket operations may produce detectable
   157  				//   differences (e.g., CloseWrite/FIN).
   158  				//
   159  				// - The dial to the passthrough, or other upstream network operations,
   160  				//   may fail. These errors are not logged.
   161  				//
   162  				// - There's no timeout on the passthrough dial and no time limit on the
   163  				//   passthrough relay so that the invalid client can't detect a timeout
   164  				//   shorter than the passthrough target; this may cause additional load.
   165  
   166  				defer conn.Close()
   167  
   168  				passthroughConn, err := net.Dial("tcp", c.config.PassthroughAddress)
   169  				if err != nil {
   170  					return
   171  				}
   172  				_, err = passthroughConn.Write(passthroughReadBuffer)
   173  				if err != nil {
   174  					return
   175  				}
   176  
   177  				// Allow garbage collection.
   178  				passthroughReadBuffer = nil
   179  
   180  				go func() {
   181  					_, _ = io.Copy(passthroughConn, conn)
   182  					passthroughConn.Close()
   183  				}()
   184  				_, _ = io.Copy(conn, passthroughConn)
   185  			}()
   186  
   187  		}
   188  	}
   189  
   190  	if err != nil {
   191  		return err
   192  	}
   193  
   194  	// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
   195  	// and https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2
   196  	c.buffering = true
   197  	if c.vers >= VersionTLS13 {
   198  		if err := hs.doTLS13Handshake(); err != nil {
   199  			return err
   200  		}
   201  		if _, err := c.flush(); err != nil {
   202  			return err
   203  		}
   204  		c.hs = &hs
   205  		// If the client is sending early data while the server expects
   206  		// it, delay the Finished check until HandshakeConfirmed() is
   207  		// called or until all early data is Read(). Otherwise, complete
   208  		// authenticating the client now (there is no support for
   209  		// sending 0.5-RTT data to a potential unauthenticated client).
   210  		if c.phase != readingEarlyData {
   211  			if err := hs.readClientFinished13(false); err != nil {
   212  				return err
   213  			}
   214  		}
   215  		atomic.StoreUint32(&c.handshakeStatus, 1)
   216  		return nil
   217  	} else if isResume {
   218  		// The client has included a session ticket and so we do an abbreviated handshake.
   219  		if err := hs.doResumeHandshake(); err != nil {
   220  			return err
   221  		}
   222  		if err := hs.establishKeys(); err != nil {
   223  			return err
   224  		}
   225  		// ticketSupported is set in a resumption handshake if the
   226  		// ticket from the client was encrypted with an old session
   227  		// ticket key and thus a refreshed ticket should be sent.
   228  		if hs.hello.ticketSupported {
   229  			if err := hs.sendSessionTicket(); err != nil {
   230  				return err
   231  			}
   232  		}
   233  		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
   234  			return err
   235  		}
   236  		if _, err := c.flush(); err != nil {
   237  			return err
   238  		}
   239  		c.clientFinishedIsFirst = false
   240  		if err := hs.readFinished(nil); err != nil {
   241  			return err
   242  		}
   243  		c.didResume = true
   244  	} else {
   245  		// The client didn't include a session ticket, or it wasn't
   246  		// valid so we do a full handshake.
   247  		if err := hs.doFullHandshake(); err != nil {
   248  			return err
   249  		}
   250  		if err := hs.establishKeys(); err != nil {
   251  			return err
   252  		}
   253  		if err := hs.readFinished(c.clientFinished[:]); err != nil {
   254  			return err
   255  		}
   256  		c.clientFinishedIsFirst = true
   257  		c.buffering = true
   258  		if err := hs.sendSessionTicket(); err != nil {
   259  			return err
   260  		}
   261  		if err := hs.sendFinished(nil); err != nil {
   262  			return err
   263  		}
   264  		if _, err := c.flush(); err != nil {
   265  			return err
   266  		}
   267  	}
   268  	if c.hand.Len() > 0 {
   269  		return c.sendAlert(alertUnexpectedMessage)
   270  	}
   271  	c.phase = handshakeConfirmed
   272  	atomic.StoreInt32(&c.handshakeConfirmed, 1)
   273  
   274  	// [Psiphon]
   275  	// https://github.com/golang/go/commit/e5b13401c6b19f58a8439f1019a80fe540c0c687
   276  	atomic.StoreUint32(&c.handshakeStatus, 1)
   277  
   278  	return nil
   279  }
   280  
   281  // [Psiphon]
   282  // recorderConn is a net.Conn which records all bytes read from the wrapped
   283  // conn until GetReadBuffer is called, which returns the buffered bytes and
   284  // stops recording. This is used to replay, byte-for-byte, the bytes sent by a
   285  // client when switching to passthrough.
   286  //
   287  // recorderConn operations are not safe for concurrent use and intended only
   288  // to be used in the initial phase of the TLS handshake, where the order of
   289  // operations is deterministic.
   290  type recorderConn struct {
   291  	net.Conn
   292  	readBuffer *bytes.Buffer
   293  }
   294  
   295  func newRecorderConn(conn net.Conn) *recorderConn {
   296  	return &recorderConn{
   297  		Conn:       conn,
   298  		readBuffer: new(bytes.Buffer),
   299  	}
   300  }
   301  
   302  func (c *recorderConn) Read(p []byte) (n int, err error) {
   303  	n, err = c.Conn.Read(p)
   304  	if n > 0 && c.readBuffer != nil {
   305  		_, _ = c.readBuffer.Write(p[:n])
   306  	}
   307  	return n, err
   308  }
   309  
   310  func (c *recorderConn) GetReadBuffer() *bytes.Buffer {
   311  	b := c.readBuffer
   312  	c.readBuffer = nil
   313  	return b
   314  }
   315  
   316  func (c *recorderConn) IsRecording() bool {
   317  	return c.readBuffer != nil
   318  }
   319  
   320  // [Psiphon]
   321  // closedConn is a net.Conn which behaves as if it were closed: all reads and
   322  // writes fail. This is used when switching to passthrough mode: ownership of
   323  // the invalid client conn is taken by the passthrough relay and a closedConn
   324  // replaces the network conn used by the local TLS server code path.
   325  type closedConn struct {
   326  	localAddr  net.Addr
   327  	remoteAddr net.Addr
   328  }
   329  
   330  var closedClosedError = errors.New("closed")
   331  
   332  func newClosedConn(conn net.Conn) *closedConn {
   333  	return &closedConn{
   334  		localAddr:  conn.LocalAddr(),
   335  		remoteAddr: conn.RemoteAddr(),
   336  	}
   337  }
   338  
   339  func (c *closedConn) Read(_ []byte) (int, error) {
   340  	return 0, closedClosedError
   341  }
   342  
   343  func (c *closedConn) Write(_ []byte) (int, error) {
   344  	return 0, closedClosedError
   345  }
   346  
   347  func (c *closedConn) Close() error {
   348  	return nil
   349  }
   350  
   351  func (c *closedConn) LocalAddr() net.Addr {
   352  	return c.localAddr
   353  }
   354  
   355  func (c *closedConn) RemoteAddr() net.Addr {
   356  	return c.remoteAddr
   357  }
   358  
   359  func (c *closedConn) SetDeadline(_ time.Time) error {
   360  	return closedClosedError
   361  }
   362  
   363  func (c *closedConn) SetReadDeadline(_ time.Time) error {
   364  	return closedClosedError
   365  }
   366  
   367  func (c *closedConn) SetWriteDeadline(_ time.Time) error {
   368  	return closedClosedError
   369  }
   370  
   371  // readClientHello reads a ClientHello message from the client and decides
   372  // whether we will perform session resumption.
   373  func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
   374  	c := hs.c
   375  
   376  	msg, err := c.readHandshake()
   377  	if err != nil {
   378  		return false, err
   379  	}
   380  	var ok bool
   381  	hs.clientHello, ok = msg.(*clientHelloMsg)
   382  	if !ok {
   383  		c.sendAlert(alertUnexpectedMessage)
   384  		return false, unexpectedMessageError(hs.clientHello, msg)
   385  	}
   386  
   387  	if c.config.GetConfigForClient != nil {
   388  		if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
   389  			c.out.traceErr, c.in.traceErr = nil, nil // disable tracing
   390  			c.sendAlert(alertInternalError)
   391  			return false, err
   392  		} else if newConfig != nil {
   393  			newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
   394  			c.config = newConfig
   395  		}
   396  	}
   397  
   398  	var keyShares []CurveID
   399  	for _, ks := range hs.clientHello.keyShares {
   400  		keyShares = append(keyShares, ks.group)
   401  	}
   402  
   403  	if hs.clientHello.supportedVersions != nil {
   404  		c.vers, ok = c.config.pickVersion(hs.clientHello.supportedVersions)
   405  		if !ok {
   406  			c.sendAlert(alertProtocolVersion)
   407  			return false, fmt.Errorf("tls: none of the client versions (%x) are supported", hs.clientHello.supportedVersions)
   408  		}
   409  	} else {
   410  		c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
   411  		if !ok {
   412  			c.sendAlert(alertProtocolVersion)
   413  			return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
   414  		}
   415  	}
   416  	c.haveVers = true
   417  
   418  	preferredCurves := c.config.curvePreferences()
   419  Curves:
   420  	for _, curve := range hs.clientHello.supportedCurves {
   421  		for _, supported := range preferredCurves {
   422  			if supported == curve {
   423  				hs.ellipticOk = true
   424  				break Curves
   425  			}
   426  		}
   427  	}
   428  
   429  	// [Psiphon]
   430  	hasSupportedPoints := false
   431  
   432  	// If present, the supported points extension must include uncompressed.
   433  	// Can be absent. This behavior mirrors BoringSSL.
   434  	if hs.clientHello.supportedPoints != nil {
   435  		supportedPointFormat := false
   436  		for _, pointFormat := range hs.clientHello.supportedPoints {
   437  			if pointFormat == pointFormatUncompressed {
   438  				supportedPointFormat = true
   439  				break
   440  			}
   441  		}
   442  		if !supportedPointFormat {
   443  			c.sendAlert(alertHandshakeFailure)
   444  			return false, errors.New("tls: client does not support uncompressed points")
   445  		}
   446  		hasSupportedPoints = true
   447  	}
   448  
   449  	foundCompression := false
   450  	// We only support null compression, so check that the client offered it.
   451  	for _, compression := range hs.clientHello.compressionMethods {
   452  		if compression == compressionNone {
   453  			foundCompression = true
   454  			break
   455  		}
   456  	}
   457  
   458  	if !foundCompression {
   459  		c.sendAlert(alertIllegalParameter)
   460  		return false, errors.New("tls: client does not support uncompressed connections")
   461  	}
   462  	if len(hs.clientHello.compressionMethods) != 1 && c.vers >= VersionTLS13 {
   463  		c.sendAlert(alertIllegalParameter)
   464  		return false, errors.New("tls: 1.3 client offered compression")
   465  	}
   466  
   467  	if len(hs.clientHello.secureRenegotiation) != 0 {
   468  		c.sendAlert(alertHandshakeFailure)
   469  		return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
   470  	}
   471  
   472  	if c.vers < VersionTLS13 {
   473  		hs.hello = new(serverHelloMsg)
   474  		hs.hello.vers = c.vers
   475  		hs.hello.random = make([]byte, 32)
   476  		_, err = io.ReadFull(c.config.rand(), hs.hello.random)
   477  		if err != nil {
   478  			c.sendAlert(alertInternalError)
   479  			return false, err
   480  		}
   481  		hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
   482  		hs.hello.compressionMethod = compressionNone
   483  	} else {
   484  		hs.hello = new(serverHelloMsg)
   485  		hs.hello13Enc = new(encryptedExtensionsMsg)
   486  		hs.hello.vers = c.vers
   487  		hs.hello.random = make([]byte, 32)
   488  		hs.hello.sessionId = hs.clientHello.sessionId
   489  		_, err = io.ReadFull(c.config.rand(), hs.hello.random)
   490  		if err != nil {
   491  			c.sendAlert(alertInternalError)
   492  			return false, err
   493  		}
   494  	}
   495  
   496  	// [Psiphon]
   497  	// https://github.com/golang/go/commit/02a5502ab8d862309aaec3c5ec293b57b913d01d
   498  	if hasSupportedPoints && c.vers < VersionTLS13 {
   499  		// Although omitting the ec_point_formats extension is permitted, some
   500  		// old OpenSSL versions will refuse to handshake if not present.
   501  		//
   502  		// Per RFC 4492, section 5.1.2, implementations MUST support the
   503  		// uncompressed point format. See golang.org/issue/31943.
   504  		hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
   505  	}
   506  
   507  	if len(hs.clientHello.serverName) > 0 {
   508  		c.serverName = hs.clientHello.serverName
   509  	}
   510  
   511  	if len(hs.clientHello.alpnProtocols) > 0 {
   512  		if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
   513  			if hs.hello13Enc != nil {
   514  				hs.hello13Enc.alpnProtocol = selectedProto
   515  			} else {
   516  				hs.hello.alpnProtocol = selectedProto
   517  			}
   518  			c.clientProtocol = selectedProto
   519  		}
   520  	} else {
   521  		// Although sending an empty NPN extension is reasonable, Firefox has
   522  		// had a bug around this. Best to send nothing at all if
   523  		// c.config.NextProtos is empty. See
   524  		// https://golang.org/issue/5445.
   525  		if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 && c.vers < VersionTLS13 {
   526  			hs.hello.nextProtoNeg = true
   527  			hs.hello.nextProtos = c.config.NextProtos
   528  		}
   529  	}
   530  
   531  	hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
   532  	if err != nil {
   533  		c.sendAlert(alertInternalError)
   534  		return false, err
   535  	}
   536  
   537  	// Set the private key for this handshake to the certificate's secret key.
   538  	hs.privateKey = hs.cert.PrivateKey
   539  
   540  	if hs.clientHello.scts {
   541  		hs.hello.scts = hs.cert.SignedCertificateTimestamps
   542  	}
   543  
   544  	// Set the private key to the DC private key if the client and server are
   545  	// willing to negotiate the delegated credential extension.
   546  	//
   547  	// Check to see if a DelegatedCredential is available and should be used.
   548  	// If one is available, the session is using TLS >= 1.2, and the client
   549  	// accepts the delegated credential extension, then set the handshake
   550  	// private key to the DC private key.
   551  	if c.config.GetDelegatedCredential != nil && hs.clientHello.delegatedCredential && c.vers >= VersionTLS12 {
   552  		dc, sk, err := c.config.GetDelegatedCredential(hs.clientHelloInfo(), c.vers)
   553  		if err != nil {
   554  			c.sendAlert(alertInternalError)
   555  			return false, err
   556  		}
   557  
   558  		// Set the handshake private key.
   559  		if dc != nil {
   560  			hs.privateKey = sk
   561  			hs.delegatedCredential = dc
   562  		}
   563  	}
   564  
   565  	if priv, ok := hs.privateKey.(crypto.Signer); ok {
   566  		switch priv.Public().(type) {
   567  		case *ecdsa.PublicKey:
   568  			hs.ecdsaOk = true
   569  		case *rsa.PublicKey:
   570  			hs.rsaSignOk = true
   571  		default:
   572  			c.sendAlert(alertInternalError)
   573  			return false, fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
   574  		}
   575  	}
   576  	if priv, ok := hs.privateKey.(crypto.Decrypter); ok {
   577  		switch priv.Public().(type) {
   578  		case *rsa.PublicKey:
   579  			hs.rsaDecryptOk = true
   580  		default:
   581  			c.sendAlert(alertInternalError)
   582  			return false, fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
   583  		}
   584  	}
   585  
   586  	if c.vers != VersionTLS13 && hs.checkForResumption() {
   587  		return true, nil
   588  	}
   589  
   590  	var preferenceList, supportedList []uint16
   591  	if c.config.PreferServerCipherSuites {
   592  		preferenceList = c.config.cipherSuites()
   593  		supportedList = hs.clientHello.cipherSuites
   594  	} else {
   595  		preferenceList = hs.clientHello.cipherSuites
   596  		supportedList = c.config.cipherSuites()
   597  	}
   598  
   599  	for _, id := range preferenceList {
   600  		if hs.setCipherSuite(id, supportedList, c.vers) {
   601  			break
   602  		}
   603  	}
   604  
   605  	if hs.suite == nil {
   606  		c.sendAlert(alertHandshakeFailure)
   607  		return false, errors.New("tls: no cipher suite supported by both client and server")
   608  	}
   609  
   610  	// See https://tools.ietf.org/html/rfc7507.
   611  	for _, id := range hs.clientHello.cipherSuites {
   612  		if id == TLS_FALLBACK_SCSV {
   613  			// The client is doing a fallback connection.
   614  			if c.vers < c.config.maxVersion() {
   615  				c.sendAlert(alertInappropriateFallback)
   616  				return false, errors.New("tls: client using inappropriate protocol fallback")
   617  			}
   618  			break
   619  		}
   620  	}
   621  
   622  	return false, nil
   623  }
   624  
   625  // checkForResumption reports whether we should perform resumption on this connection.
   626  func (hs *serverHandshakeState) checkForResumption() bool {
   627  	c := hs.c
   628  
   629  	if c.config.SessionTicketsDisabled {
   630  		return false
   631  	}
   632  
   633  	sessionTicket := append([]uint8{}, hs.clientHello.sessionTicket...)
   634  	serializedState, usedOldKey := c.decryptTicket(sessionTicket)
   635  	hs.sessionState = &sessionState{usedOldKey: usedOldKey}
   636  	if hs.sessionState.unmarshal(serializedState) != alertSuccess {
   637  		return false
   638  	}
   639  
   640  	// Never resume a session for a different TLS version.
   641  	if c.vers != hs.sessionState.vers {
   642  		return false
   643  	}
   644  
   645  	// [Psiphon]
   646  	// When using obfuscated session tickets, the client-generated session ticket
   647  	// state never uses EMS. ClientHellos vary in EMS support. So, in this mode,
   648  	// skip this check to ensure the obfuscated session tickets are not
   649  	// rejected.
   650  	if !c.config.UseObfuscatedSessionTickets {
   651  
   652  		// Do not resume connections where client support for EMS has changed
   653  		if (hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret) != hs.sessionState.usedEMS {
   654  			return false
   655  		}
   656  	}
   657  
   658  	cipherSuiteOk := false
   659  	// Check that the client is still offering the ciphersuite in the session.
   660  	for _, id := range hs.clientHello.cipherSuites {
   661  		if id == hs.sessionState.cipherSuite {
   662  			cipherSuiteOk = true
   663  			break
   664  		}
   665  	}
   666  	if !cipherSuiteOk {
   667  		return false
   668  	}
   669  
   670  	// Check that we also support the ciphersuite from the session.
   671  	if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
   672  		return false
   673  	}
   674  
   675  	sessionHasClientCerts := len(hs.sessionState.certificates) != 0
   676  	needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
   677  	if needClientCerts && !sessionHasClientCerts {
   678  		return false
   679  	}
   680  	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   681  		return false
   682  	}
   683  
   684  	return true
   685  }
   686  
   687  func (hs *serverHandshakeState) doResumeHandshake() error {
   688  	c := hs.c
   689  
   690  	hs.hello.cipherSuite = hs.suite.id
   691  	// We echo the client's session ID in the ServerHello to let it know
   692  	// that we're doing a resumption.
   693  	hs.hello.sessionId = hs.clientHello.sessionId
   694  	hs.hello.ticketSupported = hs.sessionState.usedOldKey
   695  	hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
   696  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   697  	hs.finishedHash.discardHandshakeBuffer()
   698  	hs.finishedHash.Write(hs.clientHello.marshal())
   699  	hs.finishedHash.Write(hs.hello.marshal())
   700  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   701  		return err
   702  	}
   703  
   704  	if len(hs.sessionState.certificates) > 0 {
   705  		if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
   706  			return err
   707  		}
   708  	}
   709  
   710  	hs.masterSecret = hs.sessionState.masterSecret
   711  	c.useEMS = hs.sessionState.usedEMS
   712  
   713  	return nil
   714  }
   715  
   716  func (hs *serverHandshakeState) doFullHandshake() error {
   717  	c := hs.c
   718  
   719  	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
   720  		hs.hello.ocspStapling = true
   721  	}
   722  
   723  	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
   724  	hs.hello.cipherSuite = hs.suite.id
   725  	hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
   726  
   727  	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
   728  	if c.config.ClientAuth == NoClientCert {
   729  		// No need to keep a full record of the handshake if client
   730  		// certificates won't be used.
   731  		hs.finishedHash.discardHandshakeBuffer()
   732  	}
   733  	hs.finishedHash.Write(hs.clientHello.marshal())
   734  	hs.finishedHash.Write(hs.hello.marshal())
   735  	if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
   736  		return err
   737  	}
   738  
   739  	certMsg := new(certificateMsg)
   740  	certMsg.certificates = hs.cert.Certificate
   741  	hs.finishedHash.Write(certMsg.marshal())
   742  	if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
   743  		return err
   744  	}
   745  
   746  	if hs.hello.ocspStapling {
   747  		certStatus := new(certificateStatusMsg)
   748  		certStatus.statusType = statusTypeOCSP
   749  		certStatus.response = hs.cert.OCSPStaple
   750  		hs.finishedHash.Write(certStatus.marshal())
   751  		if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
   752  			return err
   753  		}
   754  	}
   755  
   756  	keyAgreement := hs.suite.ka(c.vers)
   757  	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.privateKey, hs.clientHello, hs.hello)
   758  	if err != nil {
   759  		c.sendAlert(alertHandshakeFailure)
   760  		return err
   761  	}
   762  	if skx != nil {
   763  		hs.finishedHash.Write(skx.marshal())
   764  		if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
   765  			return err
   766  		}
   767  	}
   768  
   769  	if c.config.ClientAuth >= RequestClientCert {
   770  		// Request a client certificate
   771  		certReq := new(certificateRequestMsg)
   772  		certReq.certificateTypes = []byte{
   773  			byte(certTypeRSASign),
   774  			byte(certTypeECDSASign),
   775  		}
   776  		if c.vers >= VersionTLS12 {
   777  			certReq.hasSignatureAndHash = true
   778  			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
   779  		}
   780  
   781  		// An empty list of certificateAuthorities signals to
   782  		// the client that it may send any certificate in response
   783  		// to our request. When we know the CAs we trust, then
   784  		// we can send them down, so that the client can choose
   785  		// an appropriate certificate to give to us.
   786  		if c.config.ClientCAs != nil {
   787  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   788  		}
   789  		hs.finishedHash.Write(certReq.marshal())
   790  		if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
   791  			return err
   792  		}
   793  	}
   794  
   795  	helloDone := new(serverHelloDoneMsg)
   796  	hs.finishedHash.Write(helloDone.marshal())
   797  	if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
   798  		return err
   799  	}
   800  
   801  	if _, err := c.flush(); err != nil {
   802  		return err
   803  	}
   804  
   805  	var pub crypto.PublicKey // public key for client auth, if any
   806  
   807  	msg, err := c.readHandshake()
   808  	if err != nil {
   809  		return err
   810  	}
   811  
   812  	var ok bool
   813  	// If we requested a client certificate, then the client must send a
   814  	// certificate message, even if it's empty.
   815  	if c.config.ClientAuth >= RequestClientCert {
   816  		if certMsg, ok = msg.(*certificateMsg); !ok {
   817  			c.sendAlert(alertUnexpectedMessage)
   818  			return unexpectedMessageError(certMsg, msg)
   819  		}
   820  		hs.finishedHash.Write(certMsg.marshal())
   821  
   822  		if len(certMsg.certificates) == 0 {
   823  			// The client didn't actually send a certificate
   824  			switch c.config.ClientAuth {
   825  			case RequireAnyClientCert, RequireAndVerifyClientCert:
   826  				c.sendAlert(alertBadCertificate)
   827  				return errors.New("tls: client didn't provide a certificate")
   828  			}
   829  		}
   830  
   831  		pub, err = hs.processCertsFromClient(certMsg.certificates)
   832  		if err != nil {
   833  			return err
   834  		}
   835  
   836  		msg, err = c.readHandshake()
   837  		if err != nil {
   838  			return err
   839  		}
   840  	}
   841  
   842  	// Get client key exchange
   843  	ckx, ok := msg.(*clientKeyExchangeMsg)
   844  	if !ok {
   845  		c.sendAlert(alertUnexpectedMessage)
   846  		return unexpectedMessageError(ckx, msg)
   847  	}
   848  	hs.finishedHash.Write(ckx.marshal())
   849  
   850  	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.privateKey, ckx, c.vers)
   851  	if err != nil {
   852  		if err == errClientKeyExchange {
   853  			c.sendAlert(alertDecodeError)
   854  		} else {
   855  			c.sendAlert(alertInternalError)
   856  		}
   857  		return err
   858  	}
   859  	c.useEMS = hs.hello.extendedMSSupported
   860  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random, hs.finishedHash, c.useEMS)
   861  	if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.clientHello.random, hs.masterSecret); err != nil {
   862  		c.sendAlert(alertInternalError)
   863  		return err
   864  	}
   865  
   866  	// If we received a client cert in response to our certificate request message,
   867  	// the client will send us a certificateVerifyMsg immediately after the
   868  	// clientKeyExchangeMsg. This message is a digest of all preceding
   869  	// handshake-layer messages that is signed using the private key corresponding
   870  	// to the client's certificate. This allows us to verify that the client is in
   871  	// possession of the private key of the certificate.
   872  	if len(c.peerCertificates) > 0 {
   873  		msg, err = c.readHandshake()
   874  		if err != nil {
   875  			return err
   876  		}
   877  		certVerify, ok := msg.(*certificateVerifyMsg)
   878  		if !ok {
   879  			c.sendAlert(alertUnexpectedMessage)
   880  			return unexpectedMessageError(certVerify, msg)
   881  		}
   882  
   883  		// Determine the signature type.
   884  		_, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
   885  		if err != nil {
   886  			c.sendAlert(alertIllegalParameter)
   887  			return err
   888  		}
   889  
   890  		var digest []byte
   891  		if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
   892  			err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
   893  		}
   894  		if err != nil {
   895  			c.sendAlert(alertBadCertificate)
   896  			return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
   897  		}
   898  
   899  		hs.finishedHash.Write(certVerify.marshal())
   900  	}
   901  
   902  	hs.finishedHash.discardHandshakeBuffer()
   903  
   904  	return nil
   905  }
   906  
   907  func (hs *serverHandshakeState) establishKeys() error {
   908  	c := hs.c
   909  
   910  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   911  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   912  
   913  	var clientCipher, serverCipher interface{}
   914  	var clientHash, serverHash macFunction
   915  
   916  	if hs.suite.aead == nil {
   917  		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
   918  		clientHash = hs.suite.mac(c.vers, clientMAC)
   919  		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
   920  		serverHash = hs.suite.mac(c.vers, serverMAC)
   921  	} else {
   922  		clientCipher = hs.suite.aead(clientKey, clientIV)
   923  		serverCipher = hs.suite.aead(serverKey, serverIV)
   924  	}
   925  
   926  	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
   927  	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
   928  
   929  	return nil
   930  }
   931  
   932  func (hs *serverHandshakeState) readFinished(out []byte) error {
   933  	c := hs.c
   934  
   935  	c.readRecord(recordTypeChangeCipherSpec)
   936  	if c.in.err != nil {
   937  		return c.in.err
   938  	}
   939  
   940  	if hs.hello.nextProtoNeg {
   941  		msg, err := c.readHandshake()
   942  		if err != nil {
   943  			return err
   944  		}
   945  		nextProto, ok := msg.(*nextProtoMsg)
   946  		if !ok {
   947  			c.sendAlert(alertUnexpectedMessage)
   948  			return unexpectedMessageError(nextProto, msg)
   949  		}
   950  		hs.finishedHash.Write(nextProto.marshal())
   951  		c.clientProtocol = nextProto.proto
   952  	}
   953  
   954  	msg, err := c.readHandshake()
   955  	if err != nil {
   956  		return err
   957  	}
   958  	clientFinished, ok := msg.(*finishedMsg)
   959  	if !ok {
   960  		c.sendAlert(alertUnexpectedMessage)
   961  		return unexpectedMessageError(clientFinished, msg)
   962  	}
   963  
   964  	verify := hs.finishedHash.clientSum(hs.masterSecret)
   965  	if len(verify) != len(clientFinished.verifyData) ||
   966  		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
   967  		c.sendAlert(alertDecryptError)
   968  		return errors.New("tls: client's Finished message is incorrect")
   969  	}
   970  
   971  	hs.finishedHash.Write(clientFinished.marshal())
   972  	copy(out, verify)
   973  	return nil
   974  }
   975  
   976  func (hs *serverHandshakeState) sendSessionTicket() error {
   977  	if !hs.hello.ticketSupported {
   978  		return nil
   979  	}
   980  
   981  	c := hs.c
   982  	m := new(newSessionTicketMsg)
   983  
   984  	var err error
   985  	state := sessionState{
   986  		vers:         c.vers,
   987  		cipherSuite:  hs.suite.id,
   988  		masterSecret: hs.masterSecret,
   989  		certificates: hs.certsFromClient,
   990  		usedEMS:      c.useEMS,
   991  	}
   992  	m.ticket, err = c.encryptTicket(state.marshal())
   993  	if err != nil {
   994  		return err
   995  	}
   996  
   997  	hs.finishedHash.Write(m.marshal())
   998  	if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
   999  		return err
  1000  	}
  1001  
  1002  	return nil
  1003  }
  1004  
  1005  func (hs *serverHandshakeState) sendFinished(out []byte) error {
  1006  	c := hs.c
  1007  
  1008  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  1009  		return err
  1010  	}
  1011  
  1012  	finished := new(finishedMsg)
  1013  	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  1014  	hs.finishedHash.Write(finished.marshal())
  1015  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  1016  		return err
  1017  	}
  1018  
  1019  	c.cipherSuite = hs.suite.id
  1020  	copy(out, finished.verifyData)
  1021  
  1022  	return nil
  1023  }
  1024  
  1025  // processCertsFromClient takes a chain of client certificates either from a
  1026  // Certificates message or from a sessionState and verifies them. It returns
  1027  // the public key of the leaf certificate.
  1028  func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
  1029  	c := hs.c
  1030  
  1031  	hs.certsFromClient = certificates
  1032  	certs := make([]*x509.Certificate, len(certificates))
  1033  	var err error
  1034  	for i, asn1Data := range certificates {
  1035  		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  1036  			c.sendAlert(alertBadCertificate)
  1037  			return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
  1038  		}
  1039  	}
  1040  
  1041  	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  1042  		opts := x509.VerifyOptions{
  1043  			Roots:         c.config.ClientCAs,
  1044  			CurrentTime:   c.config.time(),
  1045  			Intermediates: x509.NewCertPool(),
  1046  			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  1047  		}
  1048  
  1049  		for _, cert := range certs[1:] {
  1050  			opts.Intermediates.AddCert(cert)
  1051  		}
  1052  
  1053  		chains, err := certs[0].Verify(opts)
  1054  		if err != nil {
  1055  			c.sendAlert(alertBadCertificate)
  1056  			return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
  1057  		}
  1058  
  1059  		c.verifiedChains = chains
  1060  	}
  1061  
  1062  	if c.config.VerifyPeerCertificate != nil {
  1063  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  1064  			c.sendAlert(alertBadCertificate)
  1065  			return nil, err
  1066  		}
  1067  	}
  1068  
  1069  	if len(certs) == 0 {
  1070  		return nil, nil
  1071  	}
  1072  
  1073  	var pub crypto.PublicKey
  1074  	switch key := certs[0].PublicKey.(type) {
  1075  	case *ecdsa.PublicKey, *rsa.PublicKey:
  1076  		pub = key
  1077  	default:
  1078  		c.sendAlert(alertUnsupportedCertificate)
  1079  		return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  1080  	}
  1081  	c.peerCertificates = certs
  1082  	return pub, nil
  1083  }
  1084  
  1085  // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
  1086  // suite if that cipher suite is acceptable to use.
  1087  // It returns a bool indicating if the suite was set.
  1088  func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
  1089  	for _, supported := range supportedCipherSuites {
  1090  		if id == supported {
  1091  			var candidate *cipherSuite
  1092  
  1093  			for _, s := range cipherSuites {
  1094  				if s.id == id {
  1095  					candidate = s
  1096  					break
  1097  				}
  1098  			}
  1099  			if candidate == nil {
  1100  				continue
  1101  			}
  1102  
  1103  			if version >= VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  1104  				hs.suite = candidate
  1105  				return true
  1106  			}
  1107  			if version < VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  1108  				continue
  1109  			}
  1110  
  1111  			// Don't select a ciphersuite which we can't
  1112  			// support for this client.
  1113  			if candidate.flags&suiteECDHE != 0 {
  1114  				if !hs.ellipticOk {
  1115  					continue
  1116  				}
  1117  				if candidate.flags&suiteECDSA != 0 {
  1118  					if !hs.ecdsaOk {
  1119  						continue
  1120  					}
  1121  				} else if !hs.rsaSignOk {
  1122  					continue
  1123  				}
  1124  			} else if !hs.rsaDecryptOk {
  1125  				continue
  1126  			}
  1127  			if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
  1128  				continue
  1129  			}
  1130  			hs.suite = candidate
  1131  			return true
  1132  		}
  1133  	}
  1134  	return false
  1135  }
  1136  
  1137  // suppVersArray is the backing array of ClientHelloInfo.SupportedVersions
  1138  var suppVersArray = [...]uint16{VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  1139  
  1140  func (hs *serverHandshakeState) clientHelloInfo() *ClientHelloInfo {
  1141  	if hs.cachedClientHelloInfo != nil {
  1142  		return hs.cachedClientHelloInfo
  1143  	}
  1144  
  1145  	var supportedVersions []uint16
  1146  	if hs.clientHello.supportedVersions != nil {
  1147  		supportedVersions = hs.clientHello.supportedVersions
  1148  	} else if hs.clientHello.vers > VersionTLS12 {
  1149  		supportedVersions = suppVersArray[:]
  1150  	} else if hs.clientHello.vers >= VersionSSL30 {
  1151  		supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
  1152  	}
  1153  
  1154  	var pskBinder []byte
  1155  	if len(hs.clientHello.psks) > 0 {
  1156  		pskBinder = hs.clientHello.psks[0].binder
  1157  	}
  1158  
  1159  	hs.cachedClientHelloInfo = &ClientHelloInfo{
  1160  		CipherSuites:               hs.clientHello.cipherSuites,
  1161  		ServerName:                 hs.clientHello.serverName,
  1162  		SupportedCurves:            hs.clientHello.supportedCurves,
  1163  		SupportedPoints:            hs.clientHello.supportedPoints,
  1164  		SignatureSchemes:           hs.clientHello.supportedSignatureAlgorithms,
  1165  		SupportedProtos:            hs.clientHello.alpnProtocols,
  1166  		SupportedVersions:          supportedVersions,
  1167  		Conn:                       hs.c.conn,
  1168  		Offered0RTTData:            hs.clientHello.earlyData,
  1169  		AcceptsDelegatedCredential: hs.clientHello.delegatedCredential,
  1170  		Fingerprint:                pskBinder,
  1171  	}
  1172  
  1173  	return hs.cachedClientHelloInfo
  1174  }