def test_unix_already_listening(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path, and delete it if required.
        """
        path = FilePath("/tmp").child(uuid4().hex).path
        self.addCleanup(os.remove, path)

        # Something is already there
        FilePath(path).setContent(b"")

        reactor = SelectReactor()
        config = {
            "type": "unix",
            "path": path
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir,
                                                         reactor, self.log)
        self.assertTrue(isinstance(endpoint, UNIXServerEndpoint))

        factory = Factory.forProtocol(Echo)
        endpoint.listen(factory)

        self.assertIn(
            factory,
            [getattr(x, "factory", None) for x in reactor.getReaders()])
示例#2
0
    def test_hello(self):
        def _check(lc, reactor):
            if "published to 'oncounter'" in self.stdout.getvalue():
                lc.stop()
                try:
                    reactor.stop()
                except:
                    pass

        appdir = self.mktemp()
        cbdir = os.path.join(appdir, ".crossbar")

        reactor = SelectReactor()
        cli.run("crossbar", ["init", "--appdir={}".format(appdir), "--template=hello:python"], reactor=reactor)

        self.assertIn("Application template initialized", self.stdout.getvalue())

        reactor = SelectReactor()
        make_lc(self, reactor, _check)

        # In case it hard-locks
        reactor.callLater(self._subprocess_timeout, reactor.stop)

        cli.run("crossbar", ["start", "--cbdir={}".format(cbdir.path), "--logformat=syslogd"], reactor=reactor)

        stdout_expected = ["published to 'oncounter'"]

        for i in stdout_expected:
            self.assertIn(i, self.stdout.getvalue())
示例#3
0
    def _start_run(self, config, app, stdout_expected, stderr_expected, end_on):

        with open(self.config, "wb") as f:
            f.write(json.dumps(config, ensure_ascii=False).encode("utf8"))

        with open(self.code_location + "/myapp.py", "w") as f:
            f.write(app)

        reactor = SelectReactor()

        make_lc(self, reactor, end_on)

        # In case it hard-locks
        reactor.callLater(self._subprocess_timeout, reactor.stop)

        cli.run("crossbar", ["start", "--cbdir={}".format(self.cbdir), "--logformat=syslogd"], reactor=reactor)

        out = self.stdout.getvalue()
        err = self.stderr.getvalue()
        for i in stdout_expected:
            if i not in out:
                self.fail(u"Error: '{}' not in:\n{}".format(i, out))

        for i in stderr_expected:
            if i not in err:
                self.fail(u"Error: '{}' not in:\n{}".format(i, err))
示例#4
0
    def _start_run(self, config, app, stdout_expected, stderr_expected,
                   end_on):

        with open(self.config, "wb") as f:
            f.write(json.dumps(config, ensure_ascii=False).encode('utf8'))

        with open(self.code_location + "/myapp.py", "w") as f:
            f.write(app)

        reactor = SelectReactor()

        make_lc(self, reactor, end_on)

        # In case it hard-locks
        reactor.callLater(self._subprocess_timeout, reactor.stop)

        cli.run("crossbar",
                ["start",
                 "--cbdir={}".format(self.cbdir),
                 "--logformat=syslogd"],
                reactor=reactor)

        for i in stdout_expected:
            self.assertIn(i, self.stdout.getvalue())

        for i in stderr_expected:
            self.assertIn(i, self.stderr.getvalue())
示例#5
0
def test_uninvited_pubrel(host, port):
    record = [
        Frame(
            send=True,
            data=Connect(client_id=u"test_pubrel",
                         flags=ConnectFlags(clean_session=True))),
        Frame(
            send=False,
            data=ConnACK(session_present=False, return_code=0)),
        Frame(
            send=True,
            data=PubREL(packet_identifier=1234)),
        Frame(
            send=False,
            data=PubCOMP(packet_identifier=1234)),
        Frame(
            send=True,
            data=Disconnect()),
        ConnectionLoss(),
    ]

    r = SelectReactor()
    f = ReplayClientFactory(r, record)
    e = TCP4ClientEndpoint(r, host, port)
    e.connect(f)
    r.run()

    return Result("uninvited_pubrel", f.success, f.reason, f.client_transcript)
 def _preenDescriptors(self):
     for fdMap in (self.readFdMap, self.writeFdMap):
         lst = fdMap.keys()
         for fd in lst:
             try:
                 select(fd + 1, [fd], [fd], [fd], 0)
             except Exception:
                 fdMap.pop(fd, None)
     SelectReactor._preenDescriptors(self)
示例#7
0
文件: reactor.py 项目: MaxFangX/viff
    def doIteration(self, t):
        # Do the same as in mainLoop() first.
        self.runUntilCurrent()
        t2 = self.timeout()

        if t2 is not None:
            t = min(t, self.running and t2)

        SelectReactor.doIteration(self, t)
        self.loopCall()
示例#8
0
        def __init__(self):
            SelectReactor.__init__(self)
            self.paused = False
            self._return_value = None
            self._release_requested = False
            self._mainLoopGen = None

            # Older versions of twisted do not have the _started attribute, make it a synonym for running in that case
            if not hasattr(self, '_started'):
                PausingReactor._started = property(lambda self: self.running)
示例#9
0
        def stop(self):
            """Stops the reactor."""
            SelectReactor.stop(self)
            # If this was called while the reactor was paused we have to resume in order for it to complete
            if self.paused:
                self.run()

            # These need to be re-registered so that the PausingReactor can be safely restarted after a stop
            self.addSystemEventTrigger('during', 'shutdown', self.crash)
            self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)
示例#10
0
 def __init__(self, tempo=130, meters=(), reactor=None):
     self.tempo = tempo
     self.ticks = 0
     # self.setTempo(tempo)
     self._tick_interval = (60.0 / tempo) * (1.0 / 24)
     self.meters = meters
     self._meter_schedule = {}
     if not self.meters:
         self.meters = [Meter(4, 4, 1)]
     if not reactor:
         from twisted.internet import reactor
     self.reactor = reactor
     SelectReactor.__init__(self)
示例#11
0
 def _preenDescriptors(self):
     for fdMap, lst in (
         (self.readFdMap, self.readFdMap.keys()),
         (self.writeFdMap.keys(), self.writeFdMap.keys())
         ):
         for fd in lst:
             try:
                 select(fd + 1, [fd], [fd], [fd], 0)
             except:
                 try:
                     fdMap.pop(fd)
                 except IndexError:
                     pass
     SelectReactor._preenDescriptors(self)
示例#12
0
def test_qos2_send_wrong_confirm(host, port):
    record = [
        Frame(
            send=True,
            data=Connect(client_id=u"test_wrong_confirm_qos2",
                         flags=ConnectFlags(clean_session=True))),
        Frame(
            send=False,
            data=ConnACK(session_present=False, return_code=0)),
        Frame(
            send=True,
            data=Subscribe(packet_identifier=1234,
                           topic_requests=[SubscriptionTopicRequest(u"foo", 2)])),
        Frame(
            send=False,
            data=SubACK(packet_identifier=1234, return_codes=[2])),
        Frame(
            send=True,
            data=Publish(duplicate=False, qos_level=2, topic_name=u"foo",
                         payload=b"abc", retain=False, packet_identifier=12)),
        Frame(
            send=False,
            data=[
                PubREC(packet_identifier=12),
                Publish(duplicate=False, qos_level=2, topic_name=u"foo",
                        payload=b"abc", retain=False, packet_identifier=1),
                PubCOMP(packet_identifier=12)]),
        Frame(
            send=True,
            data=PubREL(packet_identifier=12)),
        Frame(
            send=True,
            data=PubACK(packet_identifier=1)),
        Frame(
            send=False,
            data=b""),
        Frame(
            send=True,
            data=Disconnect()),
        ConnectionLoss(),
    ]

    r = SelectReactor()
    f = ReplayClientFactory(r, record)
    e = TCP4ClientEndpoint(r, host, port)
    e.connect(f)
    r.run()

    return Result("qos2_wrong_confirm", f.success, f.reason, f.client_transcript)
示例#13
0
	def __init__(self, evManager):
		self.state = ReactorSpinController.STATE_STOPPED
		self.evManager = evManager
		self.evManager.RegisterListener( self )
		self.reactor = SelectReactor()
		installReactor(self.reactor)
		self.loopingCall = LoopingCall(self.FireTick)
示例#14
0
    def test_start(self):
        """
        A basic start, that doesn't actually enter the reactor.
        """
        with open(self.config, "w") as f:
            f.write("""{"controller": {}}""")

        reactor = SelectReactor()
        reactor.run = lambda: False

        cli.run("crossbar",
                ["start", "--cbdir={}".format(self.cbdir),
                 "--logformat=syslogd"],
                reactor=reactor)

        self.assertIn("Entering reactor event loop", self.stdout.getvalue())
示例#15
0
def supplicant():
    """Run a reactor and provide access to the supplicant driver"""
    reactor = SelectReactor()
    t = threading.Thread(target=reactor.run, kwargs={'installSignalHandlers': 0})
    t.start()
    time.sleep(0.1)  # let reactor start
    driver = WpaSupplicantDriver(reactor)
    supplicant = driver.connect()
    try:
        yield supplicant
    except Exception as e:
        print('FAIL - {}'.format(e))
    else:
        print('OK')
    reactor.disconnectAll()
    reactor.sigTerm()
    t.join()
 def __init__(self):
     self.keepGoing = True
     self.reactor = SelectReactor()
     installReactor(self.reactor)
     connection = self.reactor.connectTCP('localhost', 8000, factory)
     self.reactor.startRunning()
     self.futureCall = None
     self.futureCallTimeout = None
     pygame_test.prepare()
示例#17
0
    def doIteration(self, delay):
        """
        Perform a single iteration of the reactor. Here we make sure that
        all of our file descriptors that we need to watch are and then delegate
        the actual watching back to the twisted reactor.
        """

        self.callTimeouts(delay)
        return SelectReactor.doIteration(self, delay)
示例#18
0
    def test_fileLogging(self):
        """
        Running `crossbar start --logtofile` will log to cbdir/node.log.
        """
        with open(self.config, "w") as f:
            f.write("""{"controller": {}}""")

        reactor = SelectReactor()
        reactor.run = lambda: None

        cli.run("crossbar",
                ["start", "--cbdir={}".format(self.cbdir), "--logtofile"],
                reactor=reactor)

        with open(os.path.join(self.cbdir, "node.log"), "r") as f:
            logFile = f.read()

        self.assertIn("Entering reactor event loop", logFile)
        self.assertEqual("", self.stderr.getvalue())
        self.assertEqual("", self.stdout.getvalue())
示例#19
0
 def setUp(self):
     mocks.init()
     self._taskrunner = ThreadedTaskRunner()
     self._taskrunner.start()
     self._reactor = SelectReactor()
     self._driver = WpaSupplicantDriver(self._reactor)
     self._reactor_thread = threading.Thread(target=self._reactor.run,
                                             kwargs={'installSignalHandlers': 0})
     self._reactor_thread.start()
     time.sleep(0.1)
     self._supplicant = self._driver.connect()
示例#20
0
def test_quirks_mode_connect(host, port):
    record = [
        Frame(
            send=True,
            data=b"\x10\x15\x00\x04MQTT\x04\x02\x00x\x00\x07testqrk\x00\x00"),
        Frame(
            send=False,
            data=ConnACK(session_present=False, return_code=0)),
        Frame(
            send=True,
            data=Disconnect()),
        ConnectionLoss(),
    ]

    r = SelectReactor()
    f = ReplayClientFactory(r, record)
    e = TCP4ClientEndpoint(r, host, port)
    e.connect(f)
    r.run()

    return Result("connect_quirks", f.success, f.reason, f.client_transcript)
示例#21
0
    def test_stalePID(self):

        with open(self.config, "w") as f:
            f.write("""{"controller": {}}""")

        with open(os.path.join(self.cbdir, "node.pid"), "w") as f:
            f.write("""{"pid": 9999999}""")

        reactor = SelectReactor()
        reactor.run = lambda: None

        cli.run("crossbar",
                ["start", "--cbdir={}".format(self.cbdir),
                 "--logformat=syslogd"],
                reactor=reactor)

        self.assertIn(
            ("Stale Crossbar.io PID file (pointing to non-existing process "
             "with PID {pid}) {fp} removed").format(
                 fp=os.path.abspath(os.path.join(self.cbdir, "node.pid")),
                 pid=9999999),
            self.stdout.getvalue())
示例#22
0
def test_connect(host, port):
    record = [
        Frame(
            send=True,
            data=Connect(client_id=u"test_cleanconnect",
                         flags=ConnectFlags(clean_session=True))),
        Frame(
            send=False,
            data=ConnACK(session_present=False, return_code=0)),
        Frame(
            send=True,
            data=Disconnect()),
        ConnectionLoss(),
    ]

    r = SelectReactor()
    f = ReplayClientFactory(r, record)
    e = TCP4ClientEndpoint(r, host, port)
    e.connect(f)
    r.run()

    return Result("connect", f.success, f.reason, f.client_transcript)
示例#23
0
 def AttemptConnection(self):
     print "attempting a connection to", serverHost, serverPort
     self.state = NetworkServerView.STATE_CONNECTING
     if self.reactor:
         self.reactor.stop()
         self.PumpReactor()
     else:
         self.reactor = SelectReactor()
         installReactor(self.reactor)
     connection = self.reactor.connectTCP(serverHost, serverPort, self.pbClientFactory)
     deferred = self.pbClientFactory.getRootObject()
     deferred.addCallback(self.Connected)
     deferred.addErrback(self.ConnectFailed)
     self.reactor.startRunning()
示例#24
0
def test_reserved_packet_15(host, port):
    record = [
        Frame(
            send=True,
            data=Connect(client_id=u"test_reserved15",
                         flags=ConnectFlags(clean_session=True))),
        Frame(
            send=False,
            data=ConnACK(session_present=False, return_code=0)),
        Frame(
            send=True,
            #        v pkt 15 right here
            data=b"\xf0\x13\x00\x04MQTT\x04\x02\x00\x02\x00\x07test123"),
        ConnectionLoss()
    ]

    r = SelectReactor()
    f = ReplayClientFactory(r, record)
    e = TCP4ClientEndpoint(r, host, port)
    e.connect(f)
    r.run()

    return Result("reserved_pkt15", f.success, f.reason, f.client_transcript)
示例#25
0
    def test_unix(self):
        """
        A config with type = "unix" will create an endpoint for a UNIX socket
        at the given path.
        """
        path = os.path.join("/", "tmp", uuid4().hex)
        self.addCleanup(os.remove, path)

        reactor = SelectReactor()
        config = {
            "type": "unix",
            "path": path
        }

        endpoint = create_listening_endpoint_from_config(config, self.cbdir, reactor, self.log)
        self.assertTrue(isinstance(endpoint, UNIXServerEndpoint))

        factory = Factory.forProtocol(Echo)
        endpoint.listen(factory)

        self.assertIn(
            factory,
            [getattr(x, "factory", None) for x in reactor.getReaders()])
示例#26
0
 def __init__(self, tempo=TEMPO_120_24, meter=None, meters=(), reactor=None,
              syncClockClass=None, default=False):
     """
     tempo: The tempo object (default: Tempo(120, 24))
     meter: Meter used by the clock - default to Meter(4,4,tempo=tempo)
     reactor: The underlying reactor to drive this BeatClock - this defaults
         to the global reactor (i.e "from twisted.internet import
         reactor")
     syncClockClass: SyncClock class to use for synchronizing the clock's
         ticks and scheduling offset (if None, no SyncClock will be used).
         See bl.sync.
     default: If True, BeatClock.defaultClock will be set to the instance -
         this is used by other components to get the default global
         BeatClock.
     """
     global clock
     self.tempo = tempo
     self.ticks = 0
     self.meters = meters
     self._meter_schedule = {}
     if not self.meters:
         self.meters = [Meter(4, 4, 1, tempo=self.tempo)]
     else:
         warnings.warn('meters argument is deprecated, use '
                       'meter=oneMeterNotAList instead')
     self.meter = meter or self.meters[0]
     if not reactor:
         from twisted.internet import reactor
     self.reactor = reactor
     if default or (self.defaultClock is None):
         BeatClock.defaultClock = self
         clock = self
     if syncClockClass:
         self.syncClock = syncClockClass(self)
         lasttick, ts = self.syncClock.lastTick()
         self.ticks = lasttick
     SelectReactor.__init__(self)
示例#27
0
    def test_basic_subresources(self):
        """
        A basic WSGI app can be ran, with subresources
        """
        temp_reactor = SelectReactor()
        r = router.RouterWorkerSession(config=self.config,
                                       reactor=temp_reactor)

        # Open the transport
        transport = FakeWAMPTransport(r)
        r.onOpen(transport)

        realm_config = {
            u"name": u"realm1",
            u'roles': []
        }

        r.start_router_realm(u"realm1", realm_config)
        r.start_router_transport(
            "component1",
            {
                u"type": u"web",
                u"endpoint": {
                    u"type": u"tcp",
                    u"port": 8080
                },
                u"paths": {
                    u"/": {
                        "module": u"crossbar.worker.test.test_router",
                        "object": u"hello",
                        "type": u"wsgi"
                    },
                    u"json": {
                        "type": u"json",
                        "value": {}
                    }
                }
            })

        # Make a request to the /json endpoint, which is technically a child of
        # the WSGI app, but is not served by WSGI.
        d = treq.get("http://localhost:8080/json", reactor=temp_reactor)
        d.addCallback(treq.content)
        d.addCallback(self.assertEqual, b"{}")
        d.addCallback(lambda _: temp_reactor.stop())

        def escape():
            if temp_reactor.running:
                temp_reactor.stop()

        temp_reactor.callLater(1, escape)
        temp_reactor.run()

        return d
示例#28
0
文件: client.py 项目: dmalves/galgrav
 def attempt_connection(self):
     print "Attempting connection to", SERVERHOST, SERVERPORT
     
     self.state = NetworkServerView.STATE_CONNECTING
     
     if self.reactor:
         self.reactor.stop()
         self.pump_reactor()
     else:
         self.reactor = SelectReactor()
         installReactor(self.reactor)
     
     connection = self.reactor.connectTCP(SERVERHOST, SERVERPORT,
                                          self.pbClientFactory)
     deferred = self.pbClientFactory.getRootObject()        
     deferred.addCallback(self.connected)
     deferred.addErrback(self.connection_failed)
     self.reactor.run()
示例#29
0
 def AttemptConnection(self):
     print "attempting a connection to", serverHost, serverPort
     self.state = NetworkServerView.STATE_CONNECTING
     if self.reactor:
         self.reactor.stop()
         self.PumpReactor()
     else:
         self.reactor = SelectReactor()
         installReactor(self.reactor)
     connection = self.reactor.connectTCP(serverHost, serverPort,
                                          self.pbClientFactory)
     # TODO: make this anonymous login()
     #deferred = self.pbClientFactory.login(credentials.Anonymous())
     userCred = credentials.UsernamePassword(avatarID, 'pass1')
     controller = NetworkServerController( self.evManager )
     deferred = self.pbClientFactory.login(userCred, client=controller)
     deferred.addCallback(self.Connected)
     deferred.addErrback(self.ConnectFailed)
     self.reactor.startRunning()
示例#30
0
    def test_basic(self):
        """
        A basic WSGI app can be ran.
        """
        temp_reactor = SelectReactor()
        r = router.RouterController(config=self.config,
                                    reactor=temp_reactor)

        # Open the transport
        transport = FakeWAMPTransport(r)
        r.onOpen(transport)

        realm_config = {
            u"name": u"realm1",
            u'roles': []
        }

        r.start_router_realm(u"realm1", realm_config)
        r.start_router_transport(
            u"component1",
            {
                u"type": u"web",
                u"endpoint": {
                    u"type": u"tcp",
                    u"port": 8080
                },
                u"paths": {
                    u"/": {
                        "module": u"crossbar.worker.test.test_router",
                        "object": u"hello",
                        "type": u"wsgi"
                    }
                }
            })

        # Make a request to the WSGI app.
        d = treq.get("http://localhost:8080/", reactor=temp_reactor)
        d.addCallback(treq.content)
        d.addCallback(self.assertEqual, b"hello!")
        d.addCallback(lambda _: temp_reactor.stop())

        def escape():
            if temp_reactor.running:
                temp_reactor.stop()

        temp_reactor.callLater(1, escape)
        temp_reactor.run()

        return d
示例#31
0
class NetworkServerView(pb.Root):
    """We SEND events to the server through this object"""
    STATE_PREPARING = 0
    STATE_CONNECTING = 1
    STATE_CONNECTED = 2
    STATE_DISCONNECTING = 3
    STATE_DISCONNECTED = 4

    #----------------------------------------------------------------------
    def __init__(self, evManager, sharedObjectRegistry):
            self.evManager = evManager
            self.evManager.RegisterListener( self )

            self.pbClientFactory = pb.PBClientFactory()
            self.state = NetworkServerView.STATE_PREPARING
            self.reactor = None
            self.server = None

            self.sharedObjs = sharedObjectRegistry

    #----------------------------------------------------------------------
    def AttemptConnection(self):
            print "attempting a connection to", serverHost, serverPort
            self.state = NetworkServerView.STATE_CONNECTING
            if self.reactor:
                    self.reactor.stop()
                    self.PumpReactor()
            else:
                    self.reactor = SelectReactor()
                    installReactor(self.reactor)
            connection = self.reactor.connectTCP(serverHost, serverPort,
                                                 self.pbClientFactory)
            deferred = self.pbClientFactory.getRootObject()
            deferred.addCallback(self.Connected)
            deferred.addErrback(self.ConnectFailed)
            self.reactor.startRunning()

    #----------------------------------------------------------------------
    def Disconnect(self):
            print "disconnecting"
            if not self.reactor:
                    return
            print 'stopping the reactor'
            self.reactor.stop()
            self.PumpReactor()
            self.state = NetworkServerView.STATE_DISCONNECTING

    #----------------------------------------------------------------------
    def Connected(self, server):
            print "CONNECTED"
            self.server = server
            self.state = NetworkServerView.STATE_CONNECTED
            ev = ServerConnectEvent( server )
            self.evManager.Post( ev )

    #----------------------------------------------------------------------
    def ConnectFailed(self, server):
            print "CONNECTION FAILED"
            #self.state = NetworkServerView.STATE_PREPARING
            self.state = NetworkServerView.STATE_DISCONNECTED

    #----------------------------------------------------------------------
    def PumpReactor(self):
            self.reactor.runUntilCurrent()
            self.reactor.doIteration(0)

    #----------------------------------------------------------------------
    def Notify(self, event):
            NSV = NetworkServerView
            if isinstance( event, TickEvent ):
                    if self.state == NSV.STATE_PREPARING:
                            self.AttemptConnection()
                    elif self.state in [NSV.STATE_CONNECTED,
                                        NSV.STATE_DISCONNECTING,
                                        NSV.STATE_CONNECTING]:
                            self.PumpReactor()
                    return

            if isinstance( event, QuitEvent ):
                    self.Disconnect()
                    return

            ev = event
            if not isinstance( event, pb.Copyable ):
                    evName = event.__class__.__name__
                    copyableClsName = "Copyable"+evName
                    if not hasattr( network, copyableClsName ):
                            return
                    copyableClass = getattr( network, copyableClsName )
                    #NOTE, never even construct an instance of an event that
                    # is serverToClient, as a side effect is often adding a
                    # key to the registry with the local id().
                    if copyableClass not in network.clientToServerEvents:
                        return
                    print 'creating instance of copyable class', copyableClsName
                    ev = copyableClass( event, self.sharedObjs )

            if ev.__class__ not in network.clientToServerEvents:
                    #print "CLIENT NOT SENDING: " +str(ev)
                    return
                    
            if self.server:
                    print " ====   Client sending", str(ev)
                    remoteCall = self.server.callRemote("EventOverNetwork", ev)
            else:
                    print " =--= Cannot send while disconnected:", str(ev)
示例#32
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015 Digi International Inc. All Rights Reserved.

from wpa_supplicant.core import WpaSupplicantDriver
from twisted.internet.selectreactor import SelectReactor
import threading
import time

# Start a simple Twisted SelectReactor
reactor = SelectReactor()
threading.Thread(target=reactor.run, kwargs={'installSignalHandlers': 0}).start()
time.sleep(0.1)  # let reactor start

# Start Driver
driver = WpaSupplicantDriver(reactor)

# Connect to the supplicant, which returns the "root" D-Bus object for wpa_supplicant
supplicant = driver.connect()

# Register an interface w/ the supplicant, this can raise an error if the supplicant
# already knows about this interface
interface = supplicant.create_interface('wlan0')

# Issue the scan
scan_results = interface.scan(block=True)
for bss in scan_results:
    print(bss.get_ssid())
示例#33
0
def main():
    # Create Arguments
    args = arguments.parse_args()
    # Set Queue to infinite
    Queue_user = Queue(maxsize=0)  #CHECK queue may remove this feature.
    Queue_password = Queue(maxsize=0)  #CHECK queue may remove this feature.

    # Argpparse Vars
    mode = args.mode
    ssid = args.ssid
    user = args.user
    password = args.password
    channel = args.channel
    apmac = args.deauth
    packets = args.packets
    seconds = args.seconds
    location = args.location
    macaddress = args.mac
    # EAP Cert Vars
    # ca_cert = '/opt/my_scripts/ProjectEAP/eapSpray/RadiusServer.pem'
    # server_cert = args.server_cert # Not a requirement, if defined it must point to correct ca_cert else connection will fail.
    server_cert_path = ''
    client_cert = ''
    #EvilTwin Vars
    certname = args.certname
    public = args.public
    server_cert = args.server_cert
    private_key = args.private_key
    country = args.country
    band = args.band
    state = args.state
    city = args.city
    company = args.company
    ou = args.ou
    email = args.email
    debug = args.debug

    # Launch DATABASE module if called from CLI.
    if mode in 'database':
        database.main()
        reactor.callFromThread(reactor.stop)
    # If DATABASE was not called, Launch Twisted Reactor and creates supplicant interface.
    else:
        # Starts Twisted Reactor in the background via reactorThread
        reactor = SelectReactor()
        reactorThread = threading.Thread(target=reactor.run, \
         kwargs={'installSignalHandlers': 0}, name='Reactor thread').start()
        # let reactor start
        time.sleep(0.1)
        # Start Driver
        driver = WpaSupplicantDriver(reactor)
        # Connect to the supplicant, which returns the "root" D-Bus object for wpa_supplicant
        supplicant = driver.connect()

        # Create interface in wpa supplicant
        try:
            interface0 = supplicant.create_interface(args.interface)
        except Exception as e:
            print(' [!] Error: ' + str(e))
            reactor.callFromThread(reactor.stop)
            sys.exit(1)

        # Assigns interface 0 Supplicant Interface 0
        supplicantInt0 = supplicant.get_interfaces()[0]

        # User(s) value from CLI Args
        try:
            # Read users from a file.
            userList = args.user
            with open(userList, 'r') as f1:
                x = f1.read()
            userList = x.split()
            # Create user queue
            Queue_user.put(userList)
        except IOError:
            # Read user(s) given as a value on the CLI seperated by commas
            userList = userList.split(',')
            Queue_user.put(userList)
        except TypeError:
            # If arg does not have user option, pass.
            pass

        # Password(s) value from CLI Args
        try:
            # Read passwords from a file.
            passwordList = args.password
            with open(passwordList, 'r') as f1:
                x = f1.read()
                z = ' '.join([w for w in x.split() if len(w) > 7])
                print(' Passwords less than 8 Characters have been excluded. ')
                passwordList = z.split()
                # Create password queue
                Queue_password.put(passwordList)
        except IOError:
            # Read password(s) given as a value on the CLI seperated by commas
            passwordList = passwordList.split(',')
            # Verify password(s) is at least 8 chars.
            for password in passwordList:
                # print(len(x))
                if len(password) < 7:
                    print(' Password(s) must be atleast 8 Characters. ')
                    print(' Invalid: ' + '(' + password + ')')
                    reactor.callFromThread(reactor.stop)
                    sys.exit(1)
            # Create password queue
            Queue_password.put(passwordList)
        except TypeError:
            # If arg does not have password option, pass.
            pass

    # MODULE Menu
    if mode in 'scan':
        # I may remove threading for scanner, as there not much need.
        seconds = 5
        apscanT1 = scanner.apScan(location, seconds, supplicantInt0,
                                  interface0).start()
        reactor.callFromThread(reactor.stop)
    elif mode in 'eviltwin':
        # Consider placing macchange inside the evilTwin class.
        if macaddress:
            macchange.macManual(interface0, macaddress)
        elif not macaddress:
            macchange.macRandom(interface0)
        # Time not needed, but provides smoother exit.
        time.sleep(.5)
        eviltwinT1 = eviltwin.evilTwin(interface0, ssid, channel, macaddress, certname, public, band, server_cert, \
         private_key, country, state, city, company, ou, email, debug).start()
        # Time not needed, but provides smoother exit.
        time.sleep(.5)
        reactor.callFromThread(reactor.stop)
    elif mode in 'enum':
        # Place interface in Monitor mode, prior to DeAuth and Enum
        wirelessInt = str(interface0.get_ifname())
        monitormode.monitor_start(wirelessInt, channel)

        try:
            # Create Enum-Sniffing Thread (non-daemon)
            enum_Thread = eapenum.eapEnum(apmac, seconds, interface0, channel)
            enum_Thread.start()
            time.sleep(2.5)
            # Create a deAuth Thread (non-daemon)
            deAuth_Thread = deauthentication.deAuth(apmac, packets, interface0)
            deAuth_Thread.start()
        except KeyboardInterrupt:
            print('\n' + red('!') + 'Ctrl-C detected: ')
            monitormode.monitor_stop(wirelessInt)
        # Stop reator Thread / Terminate script
        reactor.callFromThread(reactor.stop)

    elif mode in 'spray':
        print(
            blue('i') + 'Using Interface(s): ' + str(interface0.get_ifname()))
        '''Determines if Brute-force attack will be EAP or WPA by checking if the USER parameter is present'''
        if user:
            # initiates eapSpray worker thread
            eapSprayT1 = eapspray.eapSpray(ssid, Queue_user, userList, password, server_cert,\
            server_cert_path, client_cert, supplicantInt0, interface0).start()
            # Starts Queue
            Queue_user.join()

            # Stops Twisted Reactor after the Queue is empty.
            def check_stop_flag():
                if Queue_user.empty() == True:
                    reactor.callFromThread(reactor.stop)

            lc = task.LoopingCall(check_stop_flag)
            lc.start(10)
        else:
            # initiates wpaBrute worker thread
            wpaBruteT1 = wpabrute.wpaBrute(ssid, Queue_password, passwordList, supplicantInt0,\
            interface0).start()
            # Starts Queue
            Queue_password.join()

            def check_stop_flag():
                if Queue_password.empty() == True:
                    reactor.callFromThread(reactor.stop)

            lc = task.LoopingCall(check_stop_flag)
            lc.start(10)

    elif mode in 'connect':
        '''Determines if Connection will be EAP or WPA by checking if the USER parameter is present'''
        if user:
            # initiates eapConnect worker thread
            eapConnectT1 = eapconnect.eapConnect(ssid, Queue_user, password, server_cert,\
            server_cert_path, client_cert, supplicantInt0, interface0).start()
            # Starts Queue
            Queue_user.join()

            # Stops Twisted Reactor after the Queue is empty.
            def check_stop_flag():
                if Queue_user.empty() == True:
                    reactor.callFromThread(reactor.stop)

            lc = task.LoopingCall(check_stop_flag)
            lc.start(10)
        elif password:
            # initiates wpaConnect worker thread
            wpaConnectT1 = wpaconnect.wpaConnect(ssid, Queue_password,
                                                 supplicantInt0,
                                                 interface0).start()
            # Waits until Queue is Empty and all Threads are done working.
            Queue_password.join()

            # Stops Twisted Reactor after the Queue is empty.
            def check_stop_flag():
                if Queue_password.empty() == True:
                    reactor.callFromThread(reactor.stop)

            lc = task.LoopingCall(check_stop_flag)
            lc.start(10)
        else:
            openconnect.openConnect(ssid, supplicantInt0, interface0).run()
            reactor.callFromThread(reactor.stop)
    elif mode in 'mac':
        if macaddress:
            macchange.macManual(interface0, macaddress)
        elif not macaddress:
            macchange.macRandom(interface0)
        # Time not needed, but provides smoother exit.
        time.sleep(.5)
        reactor.callFromThread(reactor.stop)
示例#34
0
from wpa_supplicant.core import WpaSupplicantDriver
from twisted.internet.selectreactor import SelectReactor
import threading
import time

# Start a simple Twisted SelectReactor
reactor = SelectReactor()
recThread = threading.Thread(target=reactor.run,
                             kwargs={'installSignalHandlers': 0})
recThread.start()
time.sleep(0.1)  # let reactor start

# Start Driver
driver = WpaSupplicantDriver(reactor)

# Connect to the supplicant, which returns the "root" D-Bus object for wpa_supplicant
supplicant = driver.connect()

# Register an interface w/ the supplicant, this can raise an error if the supplicant
# already knows about this interface
interface = supplicant.create_interface('wlx001d43100027')

# Issue the scan
print("Issue the scan:")
scan_results = interface.scan(block=True)
for bss in scan_results:
    print bss.get_ssid()

desired_network = interface.add_network({
    'ssid': 'iHome',
    'psk': 'beijingjiaotongdaxue'
示例#35
0
 def __init__(self, *args):
     SelectReactor.__init__(self, *args)
     self._releaseRequested = False
     self._mainLoopGen = None
示例#36
0
    def test_root_not_required(self):
        """
        Not including a '/' path will mean that path has a 404, but children
        will still be routed correctly.
        """
        temp_reactor = SelectReactor()
        r = router.RouterWorkerSession(config=self.config,
                                       reactor=temp_reactor)

        # Open the transport
        transport = FakeWAMPTransport(r)
        r.onOpen(transport)

        realm_config = {
            u"name": u"realm1",
            u'roles': []
        }

        # Make a file
        with open(os.path.join(self.cbdir, 'file.txt'), "wb") as f:
            f.write(b"hello!")

        r.start_router_realm(u"realm1", realm_config)
        r.start_router_transport(
            u"component1",
            {
                u"type": u"web",
                u"endpoint": {
                    u"type": u"tcp",
                    u"port": 8080
                },
                u"paths": {
                    u"static": {
                        u"directory": u".",
                        u"type": u"static"
                    }
                }
            })

        d1 = treq.get("http://localhost:8080/", reactor=temp_reactor)
        d1.addCallback(lambda resp: self.assertEqual(resp.code, 404))

        d2 = treq.get("http://localhost:8080/static/file.txt",
                      reactor=temp_reactor)
        d2.addCallback(treq.content)
        d2.addCallback(self.assertEqual, b"hello!")

        def done(results):
            for item in results:
                if not item[0]:
                    return item[1]

        d = defer.DeferredList([d1, d2])
        d.addCallback(done)
        d.addCallback(lambda _: temp_reactor.stop())

        def escape():
            if temp_reactor.running:
                temp_reactor.stop()

        temp_reactor.callLater(1, escape)
        temp_reactor.run()
示例#37
0
class TestWpaSupplicant(unittest.TestCase):
    def setUp(self):
        mocks.init()
        self._taskrunner = ThreadedTaskRunner()
        self._taskrunner.start()
        self._reactor = SelectReactor()
        self._driver = WpaSupplicantDriver(self._reactor)
        self._reactor_thread = threading.Thread(
            target=self._reactor.run, kwargs={'installSignalHandlers': 0})
        self._reactor_thread.start()
        time.sleep(0.1)
        self._supplicant = self._driver.connect()

    def tearDown(self):
        self._reactor.disconnectAll()
        self._reactor.sigTerm(signal.SIGTERM, None)
        self._reactor_thread.join()
        self._taskrunner.stop()

    #
    # Helpers
    #
    def _get_interface(self, interface_name):
        return self._supplicant.get_interface(interface_name)

    def _get_any_bss(self):
        iface = self._get_interface('wlan0')
        return BSS('/fi/w1/wpa_supplicant1/Interfaces/1/BSSs/1', iface._conn,
                   iface._reactor)

    #
    # Test Driver
    #
    def test_connect(self):
        supplicant = self._driver.connect()
        self.assertIsInstance(supplicant, WpaSupplicant)

    #
    # Test Base
    #
    def test_register_for_signal(self):
        cb = mock.Mock()
        self._supplicant.register_signal('mysig', cb)
        self._supplicant._introspection.fire_signal('mysig', True)
        cb.assert_called_once_with(True)

    def test_register_for_signal_once(self):
        def fire_signal(result):
            time.sleep(1)
            self._supplicant._introspection.fire_signal('mysig', result)

        deferred_queue = self._supplicant.register_signal_once('mysig')
        self._taskrunner.queue(Task(fire_signal, True))
        result = deferred_queue.get()
        self.assertEqual(result, True)

    #
    # Test Supplicant
    #
    def test_get_interface(self):
        interface = self._supplicant.get_interface('wlan0')
        self._supplicant._without_introspection.callRemote.assert_called_with(
            'GetInterface', 'wlan0')
        self.assertTrue(isinstance(interface, Interface))
        self.assertEqual(interface.get_path(),
                         '/fi/w1/wpa_supplicant1/Interfaces/3')

    def test_get_unknown_interface(self):
        self.assertRaises(InterfaceUnknown, self._supplicant.get_interface,
                          'wlan99')

    def test_create_interface(self):
        interface = self._supplicant.create_interface('wlan0')
        self._supplicant._without_introspection.callRemote.assert_called_with(
            'CreateInterface', {
                'Ifname': 'wlan0',
                'Driver': None
            })
        self.assertTrue(isinstance(interface, Interface))
        self.assertEqual(interface.get_path(),
                         '/fi/w1/wpa_supplicant1/Interfaces/3')

    def test_create_interface_already_exists(self):
        self.test_create_interface()
        self.assertRaises(InterfaceExists, self._supplicant.create_interface,
                          'wlan0')

    def test_remove_interface(self):
        self._supplicant.create_interface('wlan0')
        returnval = self._supplicant.remove_interface(
            '/fi/w1/wpa_supplicant1/Interfaces/3')
        self._supplicant._without_introspection.callRemote.assert_called_with(
            'RemoveInterface', '/fi/w1/wpa_supplicant1/Interfaces/3')
        self.assertEqual(returnval, None)

    def test_remove_unknown_interface(self):
        supplicant = self._driver.connect()
        self.assertRaises(InterfaceUnknown, supplicant.remove_interface,
                          'wlan99')

    def test_get_debug_level(self):
        supplicant = self._driver.connect()
        self.assertEqual(supplicant.get_debug_level(), six.u('info'))

    def test_get_debug_timestamp(self):
        supplicant = self._driver.connect()
        self.assertEqual(supplicant.get_debug_timestamp(), False)

    def test_get_debug_showkeys(self):
        supplicant = self._driver.connect()

    def test_get_interfaces(self):
        supplicant = self._driver.connect()
        self.assertEqual(supplicant.get_interfaces(),
                         [u'/fi/w1/wpa_supplicant1/Interfaces/7'])

    def test_get_eap_methods(self):
        supplicant = self._driver.connect()
        self.assertEqual(supplicant.get_eap_methods(), [
            u'MD5', u'TLS', u'MSCHAPV2', u'PEAP', u'TTLS', u'GTC', u'OTP',
            u'SIM', u'LEAP', u'PSK', u'AKA', u"AKA'", u'FAST', u'PAX', u'SAKE',
            u'GPSK', u'WSC', u'IKEV2', u'TNC', u'PWD'
        ])

    #
    # Test Interface
    #
    def test_interface_scan(self):
        interface = self._get_interface('wlan0')
        scan_results = interface.scan()
        self.assertEqual(scan_results, None)

    def test_interface_blocking_scan(self):
        interface = self._get_interface('wlan0')

        def fire_signal():
            time.sleep(1)
            interface._introspection.fire_signal('ScanDone', True)

        self._taskrunner.queue(Task(fire_signal))
        scan_results = interface.scan(block=True)
        for res in scan_results:
            self.assertTrue(isinstance(res, BSS))
            self.assertEqual(res.get_path(),
                             '/fi/w1/wpa_supplicant1/Interfaces/3/BSSs/1234')

    def test_add_network(self):
        interface = self._get_interface('wlan0')
        network = interface.add_network({})
        self.assertTrue(isinstance(network, Network))
        self.assertEqual(network.get_path(),
                         '/fi/w1/wpa_supplicant1/Networks/0')

    def test_remove_network(self):
        interface = self._get_interface('wlan0')
        network = interface.add_network({})
        result = interface.remove_network(network.get_path())
        self.assertEqual(result, None)

    def test_remove_unknown_network(self):
        interface = self._get_interface('wlan0')
        self.assertRaises(NetworkUnknown, interface.remove_network,
                          '/fi/w1/wpa_supplicant1/Networks/44')

    def test_select_network(self):
        interface = self._get_interface('wlan0')
        network = interface.add_network({})
        interface.select_network(network.get_path())
        current_network = interface.get_current_network()
        self.assertEqual(current_network.get_path(), network.get_path())

    def test_get_ifname(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_ifname(), 'wlan0')

    def test_get_current_bss(self):
        interface = self._get_interface('wlan0')
        bss = interface.get_current_bss()
        self.assertTrue(isinstance(bss, BSS))

    def test_get_current_network(self):
        interface = self._get_interface('wlan0')
        net = interface.get_current_network()
        self.assertEqual(net, None)

    def test_network_disconnect(self):
        interface = self._get_interface('wlan0')
        network = interface.add_network({})
        interface.select_network(network.get_path())
        interface.disconnect_network()
        self.assertIsNone(interface.get_current_network())

    def test_network_disconnect_not_connected(self):
        interface = self._get_interface('wlan0')
        self.assertRaises(NotConnected, interface.disconnect_network)

    def test_get_networks(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_networks(), [])

    def test_get_state(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_state(), u'inactive')

    def test_get_scanning(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_scanning(), False)

    def test_get_scan_interval(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_scan_interval(), 5)

    def test_get_fast_reauth(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_fast_reauth(), True)

    def test_get_all_bss(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_all_bss(), [
            '/fi/w1/wpa_supplicant1/Interfaces/3/BSSs/1234',
        ])

    def test_get_driver(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_driver(), u'nl80211')

    def test_get_country(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_country(), u'US')

    def test_get_bridge_ifname(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_bridge_ifname(), u'')

    def test_get_bss_expire_age(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_bss_expire_age(), 180)

    def test_get_bss_expire_count(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_bss_expire_count(), 2)

    def test_get_ap_scan(self):
        interface = self._get_interface('wlan0')
        self.assertEqual(interface.get_ap_scan(), 1)

    #
    # Test BSS
    #
    def test_get_channel(self):
        # The "channel" is a conversion from frequency, so we need to test
        # the calculation being used
        bss = self._get_any_bss()
        self.assertEqual(bss.get_channel(), 11)

    def test_get_ssid(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_ssid(), 'FGHI')

    def test_get_bssid(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_bssid(), '46:47:48:49')

    def test_get_frequency(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_frequency(), 2462)

    def test_get_wpa(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_wpa(), {
            u'Group': u'tkip',
            u'KeyMgmt': [u'wpa-psk'],
            u'Pairwise': [u'tkip']
        })

    def test_get_rsn(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_rsn(), {
            u'Group': u'',
            u'KeyMgmt': [],
            u'Pairwise': []
        })

    def test_get_ies(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_ies(), [0, 9, 68, 65, 80, 150, 24, 36])

    def test_get_privacy(self):
        interface = self._get_interface('wlan0')
        bss = interface.get_current_bss()
        self.assertEqual(bss.get_privacy(), True)

    def test_get_mode(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_mode(), u'infrastructure')

    def test_get_rates(self):
        bss = self._get_any_bss()
        self.assertEqual(bss.get_rates(), [54000000, 48000000, 6000000])

    def test_get_signal_dbm(self):
        interface = self._get_interface('wlan0')
        bss = interface.get_current_bss()
        self.assertEqual(-60, bss.get_signal_dbm())

    def test_get_signal_quality(self):
        interface = self._get_interface('wlan0')
        bss = interface.get_current_bss()
        self.assertEqual(80, bss.get_signal_quality())

    #
    # Test Network
    #
    def test_get_properties(self):
        interface = self._get_interface('wlan0')
        desired_network = interface.add_network({'ssid': 'foo', 'psk': 'bar'})
        interface.select_network(desired_network.get_path())
        curr_network = interface.get_current_network()
        props = curr_network.get_properties()
        self.assertEqual(props['ssid'], 'wdnu-dvt1')

    def test_get_enabled(self):
        pass