authenticate socket.
if protection on, return authenticated socket wrapped over the original simpleSocket,
else return original socket.
557611
public static Socket authenticate(
                                      Socket simpleSocket,
                                      boolean isClientSocket,
                                      GSSCredential credential,
                                      int protection,
                                      DataChannelAuthentication dcau)
        throws Exception {

        GSSContext gssContext = null;
        GSSManager manager = ExtendedGSSManager.getInstance();

        if (isClientSocket) {
            gssContext =
                manager.createContext(
                                      null,
                                      GSSConstants.MECH_OID,
                                      credential,
                                      GSSContext.DEFAULT_LIFETIME);
        } else {
            gssContext = manager.createContext(credential);
        }

        if (protection != GridFTPSession.PROTECTION_CLEAR) {
            ((ExtendedGSSContext) gssContext).setOption(
                                                        GSSConstants.GSS_MODE,
                                                        GSIConstants.MODE_SSL);
        }

        gssContext.requestConf(protection == GridFTPSession.PROTECTION_PRIVATE);

        //Wrap the simple socket with GSI
        logger.debug("Creating secure socket");

        GssSocketFactory factory = GssSocketFactory.getDefault();
        GssSocket secureSocket =
            (GssSocket) factory.createSocket(simpleSocket, null, 0, gssContext);

        secureSocket.setUseClientMode(isClientSocket);

        if (dcau == null) {
            secureSocket.setAuthorization(null);
        } else if (dcau == DataChannelAuthentication.SELF) {
            secureSocket.setAuthorization(SelfAuthorization.getInstance());
        } else if (dcau == DataChannelAuthentication.NONE) {
            // this should never be
        } else if (dcau instanceof DataChannelAuthentication) {
            // dcau.toFtpCmdArgument() kinda hackish but it works
            secureSocket.setAuthorization(
                                          new IdentityAuthorization(dcau.toFtpCmdArgument()));
        }

        /* that will force handshake */
        secureSocket.getOutputStream().flush();

        if (protection == GridFTPSession.PROTECTION_SAFE ||
            protection == GridFTPSession.PROTECTION_PRIVATE) {
            logger.debug("Data channel protection: on");
            return secureSocket;
        } else { // PROTECTION_CLEAR
            logger.debug("Data channel protection: off");
            return simpleSocket;
        }
    }
539115
public static CheckedSocket check(SocketFace socket)
        throws SocketException
    {
        if (socket instanceof CheckedSocket) {
            return (CheckedSocket)socket;
        }
        else {
            return new CheckedSocket(socket);
        }
    }
571816
def _on_auth(self, sock, authenticated):  # pylint: disable=unused-argument
        """"""
        def ack(eventname, error, data):  # pylint: disable=unused-argument
            """Ack"""
            if error:
                self.log.error(f"""OnAuth: {error}""")
            else:
                self.connect_channels(self.channels)
                self.post_conn_cb()

        sock.emitack("auth", self.creds, ack)
880397
def authenticate(credentials, sock_info):
    """"""
    mechanism = credentials.mechanism
    auth_func = _AUTH_MAP.get(mechanism)
    auth_func(credentials, sock_info)
372938
public static GSSContext authenticateClient(final Socket socket, Subject subject, final String servicePrincipalName) {
    return Subject.doAs(subject, new PrivilegedAction<GSSContext>() {
      public GSSContext run() {
        try {
          GSSManager manager = GSSManager.getInstance();
          GSSName peerName = manager.createName(servicePrincipalName, GSSName.NT_HOSTBASED_SERVICE);
          GSSContext context = manager.createContext(peerName, null, null, GSSContext.DEFAULT_LIFETIME);

          // Loop while the context is still not established
          while (!context.isEstablished()) {
            context.initSecContext(socket.getInputStream(), socket.getOutputStream());
          }

          return context;
        } catch (Exception e) {
          log.error("Unable to authenticate client against Kerberos", e);
          return null;
        }
      }
    });
  }
137123
def authenticated_handler(self, f):
        
        @functools.wraps(f)
        def decorated():
            resp = self._handle_authenticate_response()
            return f(resp)
        self._authenticated_handler = decorated
        return decorated
762243
@Override
    public final boolean isSecure(Socket sock)
            throws IllegalArgumentException {

        if (sock == null) {
            throw new IllegalArgumentException("Socket may not be null.");
        }
        // This check is performed last since it calls a method implemented
        // by the argument object. getClass() is final in java.lang.Object.
        if (sock.isClosed()) {
            throw new IllegalArgumentException("Socket is closed.");
        }
        return false;
    }
700891
def _get_tls_context(self) -> ssl.SSLContext:
        
        if self.tls_context is not None:
            context = self.tls_context
        else:
            # SERVER_AUTH is what we want for a client side socket
            context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
            context.check_hostname = bool(self.validate_certs)
            if self.validate_certs:
                context.verify_mode = ssl.CERT_REQUIRED
            else:
                context.verify_mode = ssl.CERT_NONE

            if self.cert_bundle is not None:
                context.load_verify_locations(cafile=self.cert_bundle)

            if self.client_cert is not None:
                context.load_cert_chain(self.client_cert, keyfile=self.client_key)

        return context
564633
def _get_client(self, server):
        
        return Client(
            server=server[0],
            authport=server[1],
            secret=server[2],
            dict=self._get_dictionary(),
        )
478419
def _get_socket_no_auth(self):
        """"""
        # We use the pid here to avoid issues with fork / multiprocessing.
        # See test.test_client:TestClient.test_fork for an example of
        # what could go wrong otherwise
        if self.pid != os.getpid():
            self.reset()

        # Get a free socket or create one.
        if not self._socket_semaphore.acquire(
                True, self.opts.wait_queue_timeout):
            self._raise_wait_queue_timeout()
        with self.lock:
            self.active_sockets += 1

        # We've now acquired the semaphore and must release it on error.
        try:
            try:
                # set.pop() isn't atomic in Jython less than 2.7, see
                # http://bugs.jython.org/issue1854
                with self.lock:
                    # Can raise ConnectionFailure.
                    sock_info = self.sockets.pop()
            except KeyError:
                # Can raise ConnectionFailure or CertificateError.
                sock_info = self.connect()
            else:
                # Can raise ConnectionFailure.
                sock_info = self._check(sock_info)
        except:
            self._socket_semaphore.release()
            with self.lock:
                self.active_sockets -= 1
            raise

        return sock_info
1012943
def get_socket(self, address, role):
        
        #
        # If this thread doesn't yet have a sockets cache
        # in its local storage, create one here.
        #
        try:
            self._tls.sockets
        except AttributeError:
            self._tls.sockets = {}
        
        # Convert the address to a single canonical string.
        #
        # If a list of addresses is passed, turn it into a tuple
        # of canonical addresses for use as a dictionary key. 
        # Otherwise convert it to a single canonical string.
        #
        if isinstance(address, list):
            caddress = tuple(core.address(a) for a in address)
        else:
            caddress = core.address(address)
            
        #
        # Each socket is identified for this thread by its address(es)
        # and the role the socket is playing (listener, publisher, etc.)
        # That is, within one thread, we are cacheing a read or a write
        # socket to the same address(es).
        #
        # The slight corner case from this is that if you attempt to
        # send to [addressA, addressB] and then to addressA and then
        # to [addressB, addressA], three separate sockets will be
        # created and used.
        #
        identifier = caddress
        
        if identifier not in self._tls.sockets:
            _logger.debug("%s does not exist in local sockets", identifier)
            #
            # If this is a listening / subscribing socket, it can only
            # be bound once, regardless of thread. Therefore keep a
            # threads-global list of addresses used and make sure this
            # one hasn't been used elsewhere.
            #
            if role in Socket.binding_roles:
                with self._lock:
                    if identifier in self._sockets:
                        raise core.SocketAlreadyExistsError("You cannot create a listening socket in more than one thread")
                    else:
                        self._sockets.add(identifier)
            
            type = self.roles[role]
            socket = context.socket(type)
            socket.role = role
            socket.address = caddress
            #
            # Do this last so that an exception earlier will result
            # in the socket not being cached
            #
            self._tls.sockets[identifier] = socket
        else:
            _logger.debug("%s already not exist in local sockets", identifier)
            #
            # Only return sockets created in this thread
            #
            socket = self._tls.sockets[identifier]

        return socket
1249612
def _check_socket(self, timeout=None):
        """"""
        sock = self.sock
        available_socks = select.select([sock], [sock], [sock], timeout)
        if available_socks[2]:
            raise OSError
        return available_socks
834246
function authenticateClient (req, res, next) {
  Client.authenticate(req, function (err, client) {
    if (err) { return next(err) }
    req.client = client
    next()
  })
}
119626
def fake_wrap_socket(orig_wrap_socket_fn, *args, **kw):
    
    server_hostname = kw.get('server_hostname')
    if server_hostname is not None:
        matcher = httpretty.match_https_hostname(server_hostname)
        if matcher is None:
                return orig_wrap_socket_fn(*args, **kw)
    if 'sock' in kw:
        return kw['sock']
    else:
        return args[0]
603751
def wrap(self, sock):
        """"""
        EMPTY_RESULT = None, {}
        try:
            s = self.context.wrap_socket(
                sock, do_handshake_on_connect=True, server_side=True,
            )
        except ssl.SSLError as ex:
            if ex.errno == ssl.SSL_ERROR_EOF:
                # This is almost certainly due to the cherrypy engine
                # 'pinging' the socket to assert it's connectable;
                # the 'ping' isn't SSL.
                return EMPTY_RESULT
            elif ex.errno == ssl.SSL_ERROR_SSL:
                if _assert_ssl_exc_contains(ex, 'http request'):
                    # The client is speaking HTTP to an HTTPS server.
                    raise errors.NoSSLError

                # Check if it's one of the known errors
                # Errors that are caught by PyOpenSSL, but thrown by
                # built-in ssl
                _block_errors = (
                    'unknown protocol', 'unknown ca', 'unknown_ca',
                    'unknown error',
                    'https proxy request', 'inappropriate fallback',
                    'wrong version number',
                    'no shared cipher', 'certificate unknown',
                    'ccs received early',
                    'certificate verify failed',  # client cert w/o trusted CA
                )
                if _assert_ssl_exc_contains(ex, *_block_errors):
                    # Accepted error, let's pass
                    return EMPTY_RESULT
            elif _assert_ssl_exc_contains(ex, 'handshake operation timed out'):
                # This error is thrown by builtin SSL after a timeout
                # when client is speaking HTTP to an HTTPS server.
                # The connection can safely be dropped.
                return EMPTY_RESULT
            raise
        except generic_socket_error as exc:
            """It is unclear why exactly this happens.

            It's reproducible only with openssl>1.0 and stdlib ``ssl`` wrapper.
            In CherryPy it's triggered by Checker plugin, which connects
            to the app listening to the socket port in TLS mode via plain
            HTTP during startup (from the same process).


            Ref: https://github.com/cherrypy/cherrypy/issues/1618
            """
            is_error0 = exc.args == (0, 'Error')

            if is_error0 and IS_ABOVE_OPENSSL10:
                return EMPTY_RESULT
            raise
        return s, self.get_environ(s)
479509
def authenticate(self):
        '''
        
        '''
        if "username" in self.options and "password" in self.options:
            self.login_oauth2(
                self.options["username"],
                self.options["password"],
                self.options.get('mfa_code'))
        elif "access_token" in self.options:
            if "refresh_token" in self.options:
                self.access_token = self.options["access_token"]
                self.refresh_token = self.options["refresh_token"]
                self.__set_account_info()
        else:
            self.authenticated = False
        return self.authenticated
699989
def _authenticate_websocket(self, websocket, event_handler):
		
		log.debug('Authenticating websocket')
		json_data = json.dumps({
			"seq": 1,
			"action": "authentication_challenge",
			"data": {
				"token": self._token
			}
		}).encode('utf8')
		yield from websocket.send(json_data)
		while True:
			message = yield from websocket.recv()
			status = json.loads(message)
			log.debug(status)
			# We want to pass the events to the event_handler already
			# because the hello event could arrive before the authentication ok response
			yield from event_handler(message)
			if ('status' in status and status['status'] == 'OK') and \
					('seq_reply' in status and status['seq_reply'] == 1):
				log.info('Websocket authentification OK')
				return True
			elif 'seq_reply' in status and status['seq_reply'] == 1:
				log.error('Websocket authentification failed')