Exemple #1
0
 def open(self):
     """open the connection to the lircd socket"""
     def gotProtocol(result):
         """now we have a connection"""
         self.protocol = result
         self.protocol.wrapper = self
         print 'got lirc protocol'
     def gotNoProtocol(result):
         """something went wrong"""
         print "got no connection to lirc: %s" % result
     point = UNIXClientEndpoint(reactor, self.irwSocket, timeout=2)
     factory = ClientFactory()
     factory.protocol = LircProtocol
     point.connect(factory).addCallback(gotProtocol).addErrback(gotNoProtocol)
Exemple #2
0
def main():
    address = FilePath(sys.argv[1])

    startLogging(sys.stdout)

    factory = Factory()
    factory.protocol = ReceiveFDProtocol
    factory.quiet = True

    endpoint = UNIXClientEndpoint(reactor, address.path)
    connected = endpoint.connect(factory)

    def succeeded(client):
        return client.whenDisconnected

    def failed(reason):
        print("Could not connect:", reason.getErrorMessage())

    def disconnected(ignored):
        reactor.stop()

    connected.addCallbacks(succeeded, failed)
    connected.addCallback(disconnected)

    reactor.run()
Exemple #3
0
    def sign(self, challenge):
        if "SSH_AUTH_SOCK" not in os.environ:
            raise Exception("no ssh-agent is running!")

        factory = Factory()
        factory.noisy = False
        factory.protocol = SSHAgentClient
        endpoint = UNIXClientEndpoint(self._reactor, os.environ["SSH_AUTH_SOCK"])
        d = endpoint.connect(factory)

        @inlineCallbacks
        def on_connect(agent):
            # we are now connected to the locally running ssh-agent
            # that agent might be the openssh-agent, or eg on Ubuntu 14.04 by
            # default the gnome-keyring / ssh-askpass-gnome application
            blob = pack(['ssh-ed25519', self.public_key(binary=True)])

            # now ask the agent
            signature_blob = yield agent.signData(blob, challenge)
            algo, signature = unpack(signature_blob)

            agent.transport.loseConnection()

            returnValue(signature)

        return d.addCallback(on_connect)
Exemple #4
0
        def sign(self, challenge):
            if "SSH_AUTH_SOCK" not in os.environ:
                raise Exception("no ssh-agent is running!")

            factory = Factory()
            factory.noisy = False
            factory.protocol = SSHAgentClient
            endpoint = UNIXClientEndpoint(self._reactor,
                                          os.environ["SSH_AUTH_SOCK"])
            d = endpoint.connect(factory)

            @inlineCallbacks
            def on_connect(agent):
                # we are now connected to the locally running ssh-agent
                # that agent might be the openssh-agent, or eg on Ubuntu 14.04 by
                # default the gnome-keyring / ssh-askpass-gnome application
                blob = _pack(['ssh-ed25519', self.public_key(binary=True)])

                # now ask the agent
                signature_blob = yield agent.signData(blob, challenge)
                algo, signature = _unpack(signature_blob)

                agent.transport.loseConnection()

                returnValue(signature)

            return d.addCallback(on_connect)
Exemple #5
0
class Client:
    def __init__(self, addr, reactor, callback, plant, name, pid, wait_result):
        self.addr = addr
        self.reactor = reactor
        self.protocol = None
        self.deferred = defer.Deferred()
        self.deferred.addCallback(self.connected)
        self.factory = ClientFactory(callback, plant, name, pid, wait_result, self.deferred)
        self.endpoint = UNIXClientEndpoint(reactor, addr)
        
    def connect(self):
        return self.endpoint.connect(self.factory)

    def disconnect(self):
        if self.protocol is not None:
            self.protocol.disconnect()
        
    def connected(self, protocol):
        self.protocol = protocol

    def notify_death(self, wait_result):
        """Returns true if death ceritificate has been sent, false otherwise

        """
        if self.protocol is None:
            logging.error("Cannot report exit status because not connected")
            return False
        elif self.protocol.state == ACCEPTED:
            self.protocol.notify_death(wait_result)
        else:
            logging.info("Not notifying server of death because connection is not in ACCEPTED state (state = {})".format(self.protocol.state))
        return self.protocol.state >= ACCEPTED
Exemple #6
0
    def open(self):
        """open the connection to the lircd socket"""
        def gotProtocol(result):
            """now we have a connection"""
            self.protocol = result
            self.protocol.wrapper = self
            logDebug(self, None, 'got lirc protocol')

        def gotNoProtocol(result):
            """something went wrong"""
            print "got no connection to lirc: %s" % result

        point = UNIXClientEndpoint(reactor, self.irwSocket, timeout=2)
        factory = ClientFactory()
        factory.protocol = LircProtocol
        point.connect(factory).addCallback(gotProtocol).addErrback(
            gotNoProtocol)
Exemple #7
0
    def __init__(self, args=None):
        '''Args must be an object with the following attributes:
           socketpath, verbose
           Suitable defaults will be supplied.'''

        # Pass command line args to ProtocolIVSHMSG, then open logging.
        if args is None:
            args = argparse.Namespace()
        for arg, default in self._required_arg_defaults.items():
            setattr(args, arg, getattr(args, arg, default))

        self.args = args

        # checkPID looks for <socketpath>.lock which the server sets up
        # as a symlink to file named <PID>
        E = UNIXClientEndpoint(TIreactor,
                               args.socketpath,
                               timeout=1,
                               checkPID=False)
        E.connect(self)
    def new(cls, pubkey=None, reactor=None):
        """
        Create a proxy for a key held in SSH agent.

        :param pubkey: A string with a public Ed25519 key in SSH format.
        :type pubkey: unicode
        """
        pubkey = _read_ssh_ed25519_pubkey(pubkey)

        if not reactor:
            from twisted.internet import reactor

        from twisted.internet.defer import inlineCallbacks, returnValue
        from twisted.internet.protocol import Factory
        from twisted.internet.endpoints import UNIXClientEndpoint
        from twisted.conch.ssh.agent import SSHAgentClient

        if "SSH_AUTH_SOCK" not in os.environ:
            raise Exception("no ssh-agent is running!")

        factory = Factory()
        factory.noisy = False
        factory.protocol = SSHAgentClient
        endpoint = UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"])
        d = endpoint.connect(factory)

        @inlineCallbacks
        def on_connect(agent):
            keys = yield agent.requestIdentities()

            # if the key is found in ssh-agent, the raw public key (32 bytes), and the
            # key comment as returned from ssh-agent
            key_data = None
            key_comment = None

            for blob, comment in keys:
                raw = unpack(blob)
                algo = raw[0]
                if algo == u'ssh-ed25519':
                    algo, _pubkey = raw
                    if _pubkey == pubkey:
                        key_data = _pubkey
                        key_comment = comment.decode('utf8')
                        break

            agent.transport.loseConnection()

            if key_data:
                key = signing.VerifyKey(key_data)
                returnValue(cls(key, key_comment, reactor))
            else:
                raise Exception("Ed25519 key not held in ssh-agent")

        return d.addCallback(on_connect)
Exemple #9
0
    def passTo(self, host, protocol):
        orig_socket = protocol.transport.socket

        if not host:
            host = b'default'
        try:
            for vhost in self.vhosts:
                if vhost.hostname.match(host):
                    dest_socket = vhost.socket
                    endpoint = UNIXClientEndpoint(reactor, dest_socket)
                    connected = endpoint.connect(Factory.forProtocol(Protocol))
                    connected.addCallback(
                        partial(self.passClientTo, orig_socket))
                    connected.addBoth(partial(self.disconnect, protocol))
                    return
        finally:
            pass
Exemple #10
0
def main(reactor, *argv):
    if "SSH_AUTH_SOCK" not in os.environ:
        raise Exception("no ssh-agent is running!")

    factory = Factory()
    factory.protocol = SSHAgentClient
    endpoint = UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"])
    d = endpoint.connect(factory)

    @inlineCallbacks
    def on_connect(proto):
        print("connected to agent. keys held currently:")
        keys = yield proto.requestIdentities()
        for blob, comment in keys:
            print("Key: {}".format(comment))
        proto.transport.loseConnection()

    return d.addCallback(on_connect)
Exemple #11
0
def query(ctx):

    """"
    Execute subcommand through UNIX domain socket client.
    """

    if not ctx.opts.argv:
        print("No command %s" % ctx.opts.argv[0], file=ctx.err)
        return 1

    address = FilePath(ctx.opts.flags.address)

    factory = Factory()
    factory.ctx = ctx
    ctx.rs = 0

    factory.protocol = QueryProtocol
    factory.quiet = True
    factory.cmd = ' '.join(ctx.opts.argv)
    # DEBUG:
    # print('Passthrough command to backend via socket: %r' % factory.cmd, file=sys.stderr)

    endpoint = UNIXClientEndpoint(reactor, address.path)
    connected = endpoint.connect(factory)

    def succeeded(client):
        return client.whenDisconnected
    def failed(reason):
        print("Could not connect:", reason.getErrorMessage(), file=ctx.err)
    def disconnected(ignored):
        reactor.stop()

    connected.addCallbacks(succeeded, failed)
    connected.addCallback(disconnected)

    reactor.run()

    return factory.ctx.rs
def main():
    address = FilePath(sys.argv[1])

    startLogging(sys.stdout)

    factory = Factory()
    factory.protocol = ReceiveFDProtocol
    factory.quiet = True

    endpoint = UNIXClientEndpoint(reactor, address.path)
    connected = endpoint.connect(factory)

    def succeeded(client):
        return client.whenDisconnected
    def failed(reason):
        print("Could not connect:", reason.getErrorMessage())
    def disconnected(ignored):
        reactor.stop()

    connected.addCallbacks(succeeded, failed)
    connected.addCallback(disconnected)

    reactor.run()
Exemple #13
0
def main(reactor, *argv):
    if "SSH_AUTH_SOCK" not in os.environ:
        raise Exception("no ssh-agent is running!")
    endpoint = UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"])
    proto = yield endpoint.connect(Factory.forProtocol(SSHAgentClient))
    print("connected to agent. keys held currently:")
    for blob, comment in (yield proto.requestIdentities()):
        raw = unpack(blob)
        algo = raw[0]
        if algo == u'ssh-rsa':
            algo, exponent, modulus = raw
            print("RSA key: {} {} 0x{} {}: 0x{} ..".format(
                comment, algo, b2a_hex(exponent), len(modulus),
                b2a_hex(modulus)[:16]))
            print(b2a_base64(blob))
        elif algo == u'ssh-ed25519':
            algo, pubkey = raw
            print("Ed25519 key: {} {} {}".format(comment, algo,
                                                 b2a_hex(pubkey)))
        else:
            print("Key of unknown type {}".format(algo))

    proto.transport.loseConnection()
def main(reactor, *argv):
    if "SSH_AUTH_SOCK" not in os.environ:
        raise Exception("no ssh-agent is running!")
    endpoint = UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"])
    proto = yield endpoint.connect(Factory.forProtocol(SSHAgentClient))
    print("connected to agent. keys held currently:")
    for blob, comment in (yield proto.requestIdentities()):
        raw = unpack(blob)
        algo = raw[0]
        if algo == u"ssh-rsa":
            algo, exponent, modulus = raw
            print(
                "RSA key: {} {} 0x{} {}: 0x{} ..".format(
                    comment, algo, b2a_hex(exponent), len(modulus), b2a_hex(modulus)[:16]
                )
            )
            print(b2a_base64(blob))
        elif algo == u"ssh-ed25519":
            algo, pubkey = raw
            print("Ed25519 key: {} {} {}".format(comment, algo, b2a_hex(pubkey)))
        else:
            print("Key of unknown type {}".format(algo))

    proto.transport.loseConnection()
Exemple #15
0
def main(reactor):
    ep = UNIXClientEndpoint(reactor, '/var/run/postgresql/.s.PGSQL.5432')
    fact = ClientFactory.forProtocol(PostgresProtocol)
    proto = yield ep.connect(fact)
    # for i in range(5000):
    res = yield proto.runQuery('SELECT * from entries limit 5')
Exemple #16
0
def build_tor_connection(connection,
                         build_state=True,
                         wait_for_proto=True,
                         password_function=lambda: None):
    """
    This is used to build a valid TorState (which has .protocol for
    the TorControlProtocol). For example::

        from twisted.internet import reactor
        from twisted.internet.endpoints import TCP4ClientEndpoint
        import txtorcon

        def example(state):
            print "Fully bootstrapped state:",state
            print "   with bootstrapped protocol:",state.protocol

        d = txtorcon.build_tor_connection(TCP4ClientEndpoint(reactor,
                                                             "localhost",
                                                             9051))
        d.addCallback(example)
        reactor.run()

    :param password_function:
        See :class:`txtorcon.TorControlProtocol`

    :param build_state:
        If True (the default) a TorState object will be
        built as well. If False, just a TorControlProtocol will be
        returned via the Deferred.

    :return:
        a Deferred that fires with a TorControlProtocol or, if you
        specified build_state=True, a TorState. In both cases, the
        object has finished bootstrapping
        (i.e. TorControlProtocol.post_bootstrap or
        TorState.post_bootstap has fired, as needed)
    """

    if IStreamClientEndpoint.providedBy(connection):
        endpoint = connection

    elif isinstance(connection, tuple):
        if len(connection) == 2:
            reactor, socket = connection
            if (os.path.exists(socket) and os.stat(socket).st_mode &
                (stat.S_IRGRP | stat.S_IRUSR | stat.S_IROTH)):
                endpoint = UNIXClientEndpoint(reactor, socket)
            else:
                raise ValueError('Can\'t use "%s" as a socket' % (socket, ))
        elif len(connection) == 3:
            endpoint = TCP4ClientEndpoint(*connection)
        else:
            raise TypeError('Expected either a (reactor, socket)- or a '
                            '(reactor, host, port)-tuple for argument '
                            '"connection", got %s' % (connection, ))
    else:
        raise TypeError('Expected a (reactor, socket)- or a (reactor, host, '
                        'port)-tuple or an object implementing IStreamClient'
                        'Endpoint for argument "connection", got %s' %
                        (connection, ))

    d = endpoint.connect(
        TorProtocolFactory(password_function=password_function))
    if build_state:
        d.addCallback(build_state if isinstance(build_state, collections.
                                                Callable) else _build_state)
    elif wait_for_proto:
        d.addCallback(wait_for_proto if isinstance(
            wait_for_proto, collections.Callable) else _wait_for_proto)
    return d
Exemple #17
0
def build_tor_connection(connection, build_state=True, wait_for_proto=True,
                         password_function=lambda: None):
    """
    This is used to build a valid TorState (which has .protocol for
    the TorControlProtocol). For example::

        from twisted.internet import reactor
        from twisted.internet.endpoints import TCP4ClientEndpoint
        import txtorcon

        def example(state):
            print "Fully bootstrapped state:",state
            print "   with bootstrapped protocol:",state.protocol

        d = txtorcon.build_tor_connection(TCP4ClientEndpoint(reactor,
                                                             "localhost",
                                                             9051))
        d.addCallback(example)
        reactor.run()

    :param password_function:
        See :class:`txtorcon.TorControlProtocol`

    :param build_state:
        If True (the default) a TorState object will be
        built as well. If False, just a TorControlProtocol will be
        returned via the Deferred.

    :return:
        a Deferred that fires with a TorControlProtocol or, if you
        specified build_state=True, a TorState. In both cases, the
        object has finished bootstrapping
        (i.e. TorControlProtocol.post_bootstrap or
        TorState.post_bootstap has fired, as needed)
    """

    if IStreamClientEndpoint.providedBy(connection):
        endpoint = connection

    elif isinstance(connection, tuple):
        if len(connection) == 2:
            reactor, socket = connection
            if (os.path.exists(socket) and
                os.stat(socket).st_mode & (stat.S_IRGRP | stat.S_IRUSR |
                                           stat.S_IROTH)):
                endpoint = UNIXClientEndpoint(reactor, socket)
            else:
                raise ValueError('Can\'t use "%s" as a socket' % (socket, ))
        elif len(connection) == 3:
            endpoint = TCP4ClientEndpoint(*connection)
        else:
            raise TypeError('Expected either a (reactor, socket)- or a '
                            '(reactor, host, port)-tuple for argument '
                            '"connection", got %s' % (connection, ))
    else:
        raise TypeError('Expected a (reactor, socket)- or a (reactor, host, '
                        'port)-tuple or an object implementing IStreamClient'
                        'Endpoint for argument "connection", got %s' %
                        (connection, ))

    d = endpoint.connect(TorProtocolFactory(password_function=password_function))
    if build_state:
        d.addCallback(build_state if callable(build_state) else _build_state)
    elif wait_for_proto:
        d.addCallback(wait_for_proto if callable(wait_for_proto) else
                      _wait_for_proto)
    return d
Exemple #18
0
class ContainerModule:
   """
   The ComponentModule creates component hosts in a Worker
   process. Component hosts can dynamically load, reload and
   unload Python application classes and components (WAMPlets).
   """

   def __init__(self, cbdir, debug = False):
      self._cbdir = cbdir
      self.debug = debug
      self._client = None
      self._session = None


   def connect(self, session):
      assert(self._session is None)

      self._session = session
      self._pid = session._pid
      self._node_name = session._node_name

      dl = []
      procs = [
         'start_component',
      ]

      for proc in procs:
         uri = 'crossbar.node.{}.worker.{}.container.{}'.format(self._node_name, self._pid, proc)
         dl.append(self._session.register(getattr(self, proc), uri))

      d = DeferredList(dl)
      return d


   def start_component(self, component, router):
      """
      Starts a Class or WAMPlet in this component container.
      """
      if component['type'] == 'wamplet':

         try:
            dist = component['dist']
            name = component['entry']

            if self.debug:
               log.msg("Worker {}: starting WAMPlet '{}/{}' in realm '{}' ..".format(self._pid, dist, name, router['realm']))

            ## make is supposed to make instances of ApplicationSession
            make = pkg_resources.load_entry_point(dist, 'autobahn.twisted.wamplet', name)

         except Exception as e:
            log.msg("Worker {}: failed to import class - {}".format(e))
            raise ApplicationError("crossbar.error.class_import_failed", str(e))
   
      elif component['type'] == 'class':

         try:
            klassname = component['name']

            if self.debug:
               log.msg("Worker {}: starting class '{}' in realm '{}' ..".format(self._pid, klassname, router['realm']))

            import importlib
            c = klassname.split('.')
            mod, kls = '.'.join(c[:-1]), c[-1]
            app = importlib.import_module(mod)

            ## make is supposed to be of class ApplicationSession
            make = getattr(app, kls)

         except Exception as e:
            log.msg("Worker {}: failed to import class - {}".format(e))
            raise ApplicationError("crossbar.error.class_import_failed", str(e))

      else:
         raise ApplicationError("crossbar.error.invalid_configuration", "unknown component type '{}'".format(component['type']))


      def create():
         cfg = ComponentConfig(realm = router['realm'], extra = component.get('extra', None))
         c = make(cfg)
         return c

      ## create a WAMP-over-WebSocket transport client factory
      ##
      from autobahn.twisted.websocket import WampWebSocketClientFactory
      transport_factory = WampWebSocketClientFactory(create, router['url'], debug = self.debug)
      transport_factory.setProtocolOptions(failByDrop = False)

      ## start a WebSocket client from an endpoint
      ##
      from twisted.internet import reactor
      from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint, UNIXClientEndpoint
      from twisted.internet.endpoints import clientFromString

      from crossbar.twisted.tlsctx import TlsClientContextFactory


      if False:
         self._client = clientFromString(reactor, router['endpoint'])
      else:
         try:
            endpoint_config = router.get('endpoint')

            ## a TCP4 endpoint
            ##
            if endpoint_config['type'] == 'tcp':

               ## the host to connect ot
               ##
               host = str(endpoint_config['host'])

               ## the port to connect to
               ##
               port = int(endpoint_config['port'])

               ## connection timeout in seconds
               ##
               timeout = int(endpoint_config.get('timeout', 10))

               if 'tls' in endpoint_config:

                  ctx = TlsClientContextFactory()

                  ## create a TLS client endpoint
                  ##
                  self._client = SSL4ClientEndpoint(reactor,
                                                    host,
                                                    port,
                                                    ctx,
                                                    timeout = timeout)
               else:
                  ## create a non-TLS client endpoint
                  ##
                  self._client = TCP4ClientEndpoint(reactor,
                                                    host,
                                                    port,
                                                    timeout = timeout)

            ## a Unix Domain Socket endpoint
            ##
            elif endpoint_config['type'] == 'unix':

               ## the path
               ##
               path = os.path.abspath(os.path.join(self._cbdir, endpoint_config['path']))

               ## connection timeout in seconds
               ##
               timeout = int(endpoint_config['type'].get('timeout', 10))

               ## create the endpoint
               ##
               self._client = UNIXClientEndpoint(reactor, path, timeout = timeout)

            else:
               raise ApplicationError("crossbar.error.invalid_configuration", "invalid endpoint type '{}'".format(endpoint_config['type']))

         except Exception as e:
            log.msg("endpoint creation failed: {}".format(e))
            raise e


      retry = True
      retryDelay = 1000

      def try_connect():
         if self.debug:
            log.msg("Worker {}: connecting to router ..".format(self._pid))

         d = self._client.connect(transport_factory)

         def success(res):
            if self.debug:
               log.msg("Worker {}: client connected to router".format(self._pid))

         def error(err):
            log.msg("Worker {}: client failed to connect to router - {}".format(self._pid, err))
            if retry:
               log.msg("Worker {}: retrying in {} ms".format(self._pid, retryDelay))
               reactor.callLater(float(retryDelay) / 1000., try_connect)
            else:
               log.msg("Worker {}: giving up.".format(seld._pid))

         d.addCallbacks(success, error)

      try_connect()
Exemple #19
0
def main(reactor):
    ep = UNIXClientEndpoint(reactor, '/var/run/postgresql/.s.PGSQL.5432')
    fact = ClientFactory.forProtocol(PostgresProtocol)
    proto = yield ep.connect(fact)
    # for i in range(5000):
    res = yield proto.runQuery('SELECT * from entries limit 5')
Exemple #20
0
class XmppService(xmppim.MessageProtocol):

    def __init__(self, cfg):
        self.cfg     = cfg
        self.active  = {}
        self.redis   = None
        self.core    = UNIXClientEndpoint(reactor, self.cfg.get("xmpp", "dmproc"))
        self.pooling = task.LoopingCall(self.redis_pooling)

    @defer.inlineCallbacks
    def redis_pooling(self):
        data0 = yield self.redis.hgetall("leela.xmpp")
        for (key, conn) in list(self.active.iteritems()):
            if (key not in data0):
                logger.warn("reaping connection: %s" % (key,))
                conn.shutdown()
        for (key, data1) in data0.iteritems():
            data = parser.parse_json(data1)
            if (key not in self.active):
                logger.debug("spawning connection: %s: %s" % (key, data["sender"]))
                conn = Connection(key, xmppim.JID(data["sender"]), data["request"]["select"], self)
                self.core.connect(conn.factory())

    @defer.inlineCallbacks
    def handle_select(self, request, sender, cc):
        try:
            if ((request["select"]["regex"] == "leela.xmpp") and (request["select"]["proc"] == "*")):
                data0 = yield self.redis.hgetall("leela.xmpp")
                tmp   = []
                for (key, data1) in data0.iteritems():
                    data = parser.parse_json(data1)
                    sql  = pp.render_select(data["request"]["select"]["proc"],
                                            data["request"]["select"]["regex"])
                    if (data["sender"] == sender.userhost()):
                        tmp.append({"key": key,
                                    "cmd": sql
                                   })
                cc(200, {"results": tmp})
            else:
                hcode = hashlib.sha512()
                hcode.update(sender.userhost())
                hcode.update(request["select"]["proc"])
                hcode.update(request["select"]["regex"])
                key   = hcode.hexdigest()
                self.redis.hsetnx("leela.xmpp", key, pp.render_json({"request": request, "sender": sender.userhost()}))
        except:
            logger.exception()
            cc(500, {"reason": "internal server error"})

    @defer.inlineCallbacks
    def handle_delete_all(self, sender, cc):
        data0 = yield self.redis.hgetall("leela.xmpp")
        keys  = []
        for (key, data1) in data0.iteritems():
            data = parser.parse_json(data1)
            if (data["sender"] == sender.userhost()):
                keys.append({"key": key})
                self.redis.hdel("leela.xmpp", key)
        cc(200, {"results": keys})

    @defer.inlineCallbacks
    def handle_delete_one(self, key, sender, cc):
        data0 = yield self.redis.hget("leela.xmpp", key)
        if (data0 is not None):
            data = parser.parse_json(data0)
            if (data["sender"] == sender.userhost()):
                yield self.redis.hdel("leela.xmpp", key)
                cc(200, {"results": {"key": key}})
            else:
                cc(403, {"reason": "forbidden"})
        else:
            cc(404, {"reason": "not found"})

    def handle_delete(self, request, sender, cc):
        try:
            key = request["delete"]["key"]
            if (key is None):
                self.handle_delete_all(sender, cc)
            else:
                self.handle_delete_one(key, sender, cc)
        except:
            logger.exception()
            cc(500, {"reason": "internal server error"})

    def handle_request(self, request, sender, cc):
        if ("select" in request):
            self.handle_select(request, sender, cc)
        elif ("delete" in request):
            self.handle_delete(request, sender, cc)
        else:
            cc(400, {"reason": "unknow command"})

    def mkcc(self, envelope, debug={}):
        def f(status, results=None):
            if (results is None):
                envelope.addElement("body", content=pp.render_json({"status": status, "debug": debug}))
            else:
                msg = dict(results)
                msg.update({"status": status, "debug": debug})
                envelope.addElement("body", content=pp.render_json(msg))
            self.send(envelope)
        return(f)

    def onMessage(self, message):
        if (message.body is None):
            return
        sender = xmppim.JID(message.getAttribute("from"))
        req    = parser.parse_sql_(unicode(message.body))
        debug  = {"request": unicode(message.body)}
        resp   = xmppim.Message(recipient = sender).toElement()
        cc     = self.mkcc(resp, debug)
        if (req in [{}, None]):
            logger.debug("message [%s] - 400" % message.body)
            cc(400, {"reason": "parse error"})
        else:
            logger.debug("message [%s] %s - 200" % (message.getAttribute("from"), message.body))
            self.handle_request(req, sender, cc)

    @defer.inlineCallbacks
    def connectionMade(self):
        try:
            self.redis = yield redis.ConnectionPool(self.cfg.get("redis", "host"),
                                                    self.cfg.getint("redis", "port"),
                                                    self.cfg.getint("redis", "db"),
                                                    True)
            self.pooling.start(5)
            xmppim.MessageProtocol.connectionMade(self)
        except:
            logger.exception()

    def connectionLost(self, reason):
        xmppim.MessageProtocol.connectionLost(self, reason)
        funcs.suppress(self.pooling.stop)()
        funcs.suppress(self.redis.disconnect)()
Exemple #21
0
class ComponentModule:
   """
   """

   def __init__(self, session, pid):
      self._session = session
      self._pid = pid
      self._client = None

      self.debug = self._session.factory.options.debug

      session.register(self.start, 'crossbar.node.module.{}.component.start'.format(self._pid))


   def start(self, transport, klassname, realm):
      """
      Dynamically start an application component to run next to the router in "embedded mode".
      """

      ## dynamically load the application component ..
      ##
      try:
         if self.debug:
            log.msg("Worker {}: starting class '{}' in realm '{}' ..".format(self._pid, klassname, realm))

         import importlib
         c = klassname.split('.')
         mod, klass = '.'.join(c[:-1]), c[-1]
         app = importlib.import_module(mod)
         SessionKlass = getattr(app, klass)

      except Exception as e:
         if self.debug:
            log.msg("Worker {}: failed to import class - {}".format(e))
         raise ApplicationError("crossbar.error.class_import_failed", str(e))

      else:
         ## create a WAMP application session factory
         ##
         #from autobahn.twisted.wamp import ApplicationSessionFactory
         #session_factory = ApplicationSessionFactory()
         session_factory = ComponentSessionFactory(realm)
         session_factory.session = SessionKlass

         ## create a WAMP-over-WebSocket transport client factory
         ##
         from autobahn.twisted.websocket import WampWebSocketClientFactory
         transport_factory = WampWebSocketClientFactory(session_factory, transport['url'], debug = self.debug)
         transport_factory.setProtocolOptions(failByDrop = False)

         ## start a WebSocket client from an endpoint
         ##
         from twisted.internet import reactor
         from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint, UNIXClientEndpoint
         from twisted.internet.endpoints import clientFromString
         from tlsctx import TlsClientContextFactory


         if False:
            self._client = clientFromString(reactor, transport['endpoint'])
         else:
            try:
               endpoint_config = transport.get('endpoint')

               ## a TCP4 endpoint
               ##
               if endpoint_config['type'] == 'tcp':

                  ## the host to connect ot
                  ##
                  host = str(endpoint_config['host'])

                  ## the port to connect to
                  ##
                  port = int(endpoint_config['port'])

                  ## connection timeout in seconds
                  ##
                  timeout = int(endpoint_config.get('timeout', 10))

                  if 'tls' in endpoint_config:

                     ctx = TlsClientContextFactory()

                     ## create a TLS client endpoint
                     ##
                     self._client = SSL4ClientEndpoint(reactor,
                                                       host,
                                                       port,
                                                       ctx,
                                                       timeout = timeout)
                  else:
                     ## create a non-TLS client endpoint
                     ##
                     self._client = TCP4ClientEndpoint(reactor,
                                                       host,
                                                       port,
                                                       timeout = timeout)

               ## a Unix Domain Socket endpoint
               ##
               elif endpoint_config['type'] == 'unix':

                  ## the path
                  ##
                  path = str(endpoint_config['path'])

                  ## connection timeout in seconds
                  ##
                  timeout = int(endpoint_config['type'].get('timeout', 10))

                  ## create the endpoint
                  ##
                  self._client = UNIXClientEndpoint(reactor, path, timeout = timeout)

               else:
                  raise ApplicationError("crossbar.error.invalid_configuration", "invalid endpoint type '{}'".format(endpoint_config['type']))

            except Exception as e:
               log.msg("endpoint creation failed: {}".format(e))
               raise e


         retry = True
         retryDelay = 1000

         def try_connect():
            print "Trying to connect .."
            d = self._client.connect(transport_factory)

            def success(res):
               if True or self.debug:
                  log.msg("Worker {}: client connected to router".format(self._pid))

            def error(err):
               log.msg("Worker {}: client failed to connect to router - {}".format(self._pid, err))
               if retry:
                  log.msg("Worker {}: retrying in {} ms".format(self._pid, retryDelay))
                  reactor.callLater(float(retryDelay) / 1000., try_connect)
               else:
                  log.msg("Worker {}: giving up.".format(seld._pid))

            d.addCallbacks(success, error)

         try_connect()
Exemple #22
0
def main(reactor, *argv):
    if "SSH_AUTH_SOCK" not in os.environ:
        raise Exception("no ssh-agent is running!")

    factory = Factory()
    factory.protocol = SSHAgentClient
    endpoint = UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"])
    d = endpoint.connect(factory)

    @inlineCallbacks
    def on_connect(agent):
        # we are now connected to the locally running ssh-agent
        # that agent might be the openssh-agent, or eg on Ubuntu 14.04 by
        # default the gnome-keyring / ssh-askpass-gnome application
        print("connected to ssh-agent!")

        print("keys currently held in ssh-agent:\n")
        keys = yield agent.requestIdentities()
        for blob, comment in keys:
            print(comment)
            raw = unpack(blob)
            algo = raw[0]
            if algo == u'ssh-rsa':
                algo, exponent, modulus = raw
                print("RSA key: {} {} 0x{} {}: 0x{} ..".format(comment, algo, b2a_hex(exponent), len(modulus), b2a_hex(modulus)[:16]))
                print(b2a_base64(blob))
            elif algo == u'ssh-ed25519':
                algo, pubkey = raw
                print("Ed25519 key: {} {} {}".format(comment, algo, b2a_hex(pubkey)))

        # we will now ask the ssh-agent to sign some data using the private
        # key that corresponds to the public key that we selected

        print("sign some data:\n")

        # message to sign
        message = 'Hello, world!'

        # the public key that corrsponds to the private key we ask the agent to sign with
        key_blob, key_comment = keys[-1]

        # now ask the agent
        signature_blob = yield agent.signData(key_blob, message)
        algo, signature = unpack(signature_blob)
        print(algo)
        print(b2a_base64(signature))

        # we now verify the signature using cryptography.

        # https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.load_ssh_public_key
        public_key = load_ssh_public_key("ssh-rsa {} {}".format(b2a_base64(key_blob), key_comment), backend=default_backend())
        isinstance(public_key, rsa.RSAPublicKey)

        verifier = public_key.verifier(signature, padding.PKCS1v15(), hashes.SHA1())
        verifier.update(message)

        # here we can provoke a failing signature to check that it actually works
        provoke_signature_failure = False
        if provoke_signature_failure:
            verifier.update('make the sig fail')

        try:
            verifier.verify()
        except InvalidSignature:
            print("** Signature is invalid!! **")
        else:
            print("Signature looks good.")

        # that's it. say goodbye.
        print("disconnecting ..")
        agent.transport.loseConnection()

    return d.addCallback(on_connect)
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import UNIXClientEndpoint


class Greeter(Protocol):
    def sendMessage(self, msg):
        print "Sending message"
        self.transport.write("MESSAGE %s\r\n" % msg)


def gotProtocol(p):
    print "gotProtocol"
    p.sendMessage("Hello \r\n")
    reactor.callLater(1, p.sendMessage, "This is sent in a second")
    reactor.callLater(2, p.transport.loseConnection)


factory = Factory()
factory.protocol = Greeter
point = UNIXClientEndpoint(reactor, "tmpSoc")
d = point.connect(factory)
d.addCallback(gotProtocol)
print "point = ", point
Exemple #24
0
        else:
            print k,v

    if 'defaults' in sys.argv:
        print "Set to default value:"
        for k in defaults:
            print "# %s" % k
            
    reactor.stop()
    
def setup_failed(arg):
    print "SETUP FAILED",arg
    reactor.stop()

def bootstrap(c):
    conf = TorConfig(c)
    conf.post_bootstrap.addCallback(setup_complete).addErrback(setup_failed)
    print "Connection is live, bootstrapping state..."

if os.stat('/var/run/tor/control').st_mode & (stat.S_IRGRP | stat.S_IRUSR | stat.S_IROTH):
    print "using control socket"
    point = UNIXClientEndpoint(reactor, "/var/run/tor/control")
    
else:
    point = TCP4ClientEndpoint(reactor, "localhost", 9051)
    
d = point.connect(TorProtocolFactory())
# do not use addCallbacks() here, in case bootstrap has an error
d.addCallback(bootstrap).addErrback(setup_failed)
reactor.run()