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