Esempio n. 1
0
def launch_environment_docker(unique_id: str, skip_init: bool = False):
    global wired_sniffer
    wired_sniffer = sniffer.Sniffer(_get_bridge_interface(unique_id))

    gateway = 'gateway-' + unique_id
    repeater1 = 'repeater1-' + unique_id
    repeater2 = 'repeater2-' + unique_id

    if not skip_init:
        wired_sniffer.start('init')
        try:
            subprocess.check_call((os.path.join(rootdir, "tests", "test_gw_repeater.sh"),
                                   "-f", "-u", unique_id, "-g", gateway,
                                   "-r", repeater1, "-r", repeater2, "-d", "7"))
        finally:
            wired_sniffer.stop()

    global controller, agents
    controller = ALEntityDocker(gateway, True)
    agents = (ALEntityDocker(repeater1), ALEntityDocker(repeater2))

    debug('controller: {}'.format(controller.mac))
    debug('agent1: {}'.format(agents[0].mac))
    debug('agent1 wlan0: {}'.format(agents[0].radios[0].mac))
    debug('agent1 wlan2: {}'.format(agents[0].radios[1].mac))
    debug('agent2: {}'.format(agents[1].mac))
    debug('agent2 wlan0: {}'.format(agents[1].radios[0].mac))
    debug('agent2 wlan2: {}'.format(agents[1].radios[1].mac))
Esempio n. 2
0
def main():
    ''' main function to run the application'''

    avg_hits = config.initial_anticipated_avg  #static value of avg hits
    traffic_queue = []  # keeps a tuple of (time of packet, url)
    url_counter = Counter()  # keeps a count of url section

    # instances of classes - packet sniffer, alert and display
    packet_sniffer = sniffer.Sniffer(config.dev, url_counter, traffic_queue)
    alerts = alert.Alert(packet_sniffer, avg_hits)
    app_display = display.Display(packet_sniffer, alerts)

    try:
        #log configuration
        path = os.path.dirname(os.getcwd())
        logging.basicConfig(filename=path + config.log_file,
                            level=logging.INFO)
    except IOError as e:
        print str(e)

    try:
        #start all threads
        packet_sniffer.start()
        app_display.start()
        alerts.start()

        signal.pause()

    except KeyboardInterrupt:
        os._exit(1)
Esempio n. 3
0
def launch_environment_docker(unique_id: str, skip_init: bool = False, tag: str = ""):
    global wired_sniffer
    iface = _get_bridge_interface('prplMesh-net-{}'.format(unique_id))
    wired_sniffer = sniffer.Sniffer(iface, opts.tcpdump_dir)

    gateway = 'gateway-' + unique_id
    repeater1 = 'repeater1-' + unique_id
    repeater2 = 'repeater2-' + unique_id

    if not skip_init:
        command = [os.path.join(rootdir, "tests", "test_gw_repeater.sh"), "-f", "-u", unique_id,
                   "-g", gateway, "-r", repeater1, "-r", repeater2, "-d", "7"]
        if tag:
            command += ["-t", tag]
        wired_sniffer.start('init')
        try:
            subprocess.check_call(command)
        finally:
            wired_sniffer.stop()

    global controller, agents
    controller = ALEntityDocker(gateway, True)
    agents = (ALEntityDocker(repeater1), ALEntityDocker(repeater2))

    debug('controller: {}'.format(controller.mac))
    debug('agent1: {}'.format(agents[0].mac))
    debug('agent1 wlan0: {}'.format(agents[0].radios[0].mac))
    debug('agent1 wlan2: {}'.format(agents[0].radios[1].mac))
    debug('agent2: {}'.format(agents[1].mac))
    debug('agent2 wlan0: {}'.format(agents[1].radios[0].mac))
    debug('agent2 wlan2: {}'.format(agents[1].radios[1].mac))
Esempio n. 4
0
 def capture_start(self, s, f):
     self.sniff = sniffer.Sniffer(s, f)
     self.sniff.start()
     #self.sniff.signal.connect(self.updatetable)
     self.sniff.signal.connect(self.pack_receive)
     #self.sniff.signal.connect(self.pack_receive_original)
     self.quit_button.clicked.connect(self.sniff.stop)  #暂停按钮实现
Esempio n. 5
0
    def __init__(self, iface):

        logging.info("TUI initialized")

        # Detect Nokia  N900 power kernel -> N900 does not use gpsd
        if 'power' in platform.release():
            #    from gpsN900 import GPS
            self.OS = "N900"
        else:
            #    from gpsGPSD import GPS
            self.OS = "LINUX"

        logging.info("Using: %s", self.OS)
        self.iface = iface

        self.fifo_gps = Queue.Queue()
        self.fifo_sniffer = Queue.Queue()

        self.window = curses.initscr()
        curses.noecho()
        # hide cursor (instant crash)
        # curses.curs_set(0)
        self.window.nodelay(1)

        try:
            self.sniffer = sniffer.Sniffer(self.fifo_sniffer, self.fifo_gps,
                                           self.iface)
            self.sniffer.start()
            #if 'LINUX' in OS:
            #   gps_thread = GPS(fifo_gps)
            #if 'N900' in OS:
            #    gps_thread = GPS(fifo_gps)
            #  gps_thread.start()

            # GPS = True

            while True:
                ch = self.window.getch()
                self.handleOutputMode(ch)

                # if 'LINUX' in OS:
                #    handleGPSMode(ch, gps_thread)

                self.handleSnifferdata()  # Handle received data

        except KeyboardInterrupt:
            curses.echo()
            curses.nocbreak()
            curses.endwin()
            self.sniffer.stop()
            self.sniffer.join()
        except:
            curses.echo()
            curses.nocbreak()
            curses.endwin()
            self.sniffer.stop()
            self.sniffer.join()
            raise
Esempio n. 6
0
 def run(self):
     """ Method that runs forever """
     if window.selectedDevice == None:
         device = None
     else:
         device = dic_devices[str(window.selectedDevice)]
     window.sniffer = capture.Sniffer(iface=device, window=window)
     window.scapy_packets = window.sniffer.snif()
     print window.scapy_packets
     window.stop = False
Esempio n. 7
0
    def __init__(self,
                 parent,
                 debug=False,
                 name=None,
                 shared=False,
                 agentSupport=False,
                 agent=None):
        """
		This class enables to send arp request
		The lower layer is based on the ARP adapter.
	
		@param parent: parent testcase
		@type parent: testcase

		@param name: adapter name used with from origin/to destination (default=None)
		@type name: string/none
		
		@param debug: active debug mode (default=False)
		@type debug:	boolean
	
		@param shared: shared adapter (default=False)
		@type shared:	boolean	

		@param agentSupport: agent support to use a remote socket (default=False)
		@type agentSupport: boolean

		@param agent: agent to use when this mode is activated
		@type agent: string/None
		"""
        # init adapter
        TestAdapterLib.Adapter.__init__(self,
                                        name=__NAME__,
                                        parent=parent,
                                        debug=debug,
                                        realname=name,
                                        agentSupport=agentSupport,
                                        agent=agent,
                                        caller=TestAdapterLib.caller(),
                                        agentType=AGENT_TYPE_EXPECTED)
        self.arp = sniffer.Sniffer(parent=parent,
                                   debug=debug,
                                   logEventSent=True,
                                   logEventReceived=True,
                                   shared=shared,
                                   name=name,
                                   agentSupport=agentSupport,
                                   agent=agent)

        self.cfg = {}
        self.cfg['agent-support'] = agentSupport
        if agentSupport:
            self.cfg['agent'] = agent
            self.cfg['agent-name'] = agent['name']
        self.__checkConfig()
Esempio n. 8
0
 def __init__(self, simQueue=None):
     # Init infinite queue representing the real network traffic
     self.realnetwork = Queue.Queue()
     # Simulator signal queue
     self.__simQueue = simQueue
     # Create a sniffer instance, just for DHCP
     self.__sniffer = sniffer.Sniffer(
         queue=self.realnetwork,
         filter="port 67 or tftp or arp or icmp or udp",
         debug=True)
     # Instance a dequeuer
     self.__dequeuer = dequeuer(self.realnetwork, self.__simQueue)
Esempio n. 9
0
def get_data_from_sniffer():
    mac_addr = request.args.get('mac_addr', '').lower()
    channel = request.args.get('channel', '')

    if not re.match(
            '[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}',
            mac_addr) or not re.match('[0-9]{1,2}', channel):
        return json.dumps({})
    print("mac addr: {}\tchannel: {}".format(mac_addr, channel))
    s = sniffer.Sniffer(channel, MON_IFACE, mac_addr)
    s.start()
    return json.dumps({
        "mac_addr": mac_addr,
        "averagePower": s.average_power,
        "dataPoints": s.data_points
    })
Esempio n. 10
0
 def fileOpen(self, btn):
     fileName = QtGui.QFileDialog.getOpenFileName(self, 'open File')
     if (str(fileName) != ""):
         self.pauseCaptureBtn.setEnabled(False)
         self.startCaptureBtn.setEnabled(True)
         self.stopCaptureBtn.setEnabled(False)
         self.stopped = True
         if (self.stackedWidget.currentIndex() == 0):
             self.stackedWidget.setCurrentIndex(1)
         self.clearTable()
         print str(fileName)
         self.sniffer = capture.Sniffer(window=window)
         try:
             self.sniffer.load(str(fileName))
         except:
             print "Error While loading"
Esempio n. 11
0
def create_default_thread_sniffer(use_message_factory=True):
    return sniffer.Sniffer(create_default_thread_message_factory(
    ) if use_message_factory else None)
Esempio n. 12
0
    def __init__(self,
                 parent,
                 testcase,
                 debug,
                 connType,
                 localPort,
                 remotePort=None,
                 windowSize=8000,
                 urgentPointer=0,
                 precedence=0,
                 ipVersion=4,
                 agentSupport=False,
                 agent=None):
        """
		transmission control block (TCB) to hold connection state information
		"""
        self.parent = parent
        self.testcase = testcase

        # sockets
        self.conn_type = connType
        self.local_socket = localPort  # tuple ip, port
        self.foreign_socket = remotePort  # tuple ip, port

        # Send Sequence Variables
        self.SND_UNA = 0  # send unacknowledged
        self.SND_NXT = None  # send next
        self.SND_WND = windowSize  # send window
        self.SND_UP = urgentPointer  # send urgent pointer
        self.SND_WL1 = None  # segment sequence number used for last window update
        self.SND_WL2 = None  # segment acknowledgment number used for last window update
        self.ISS = None  # initial send sequence number

        #	Receive Sequence Variables
        self.RCV_NXT = None  # receive next
        self.RCV_WND = None  # receive window
        self.RCV_UP = None  # receive urgent pointer
        self.IRS = None  # initial receive sequence number

        self.PRC = precedence
        self.ipVersion = ipVersion

        self.__id = None
        self.__tcpSniffer = SnifferTCP.Sniffer(parent=testcase,
                                               debug=False,
                                               logEventSent=True,
                                               logEventReceived=True,
                                               ipVersion=ipVersion,
                                               port2sniff=self.localPort(),
                                               separatorIn='0x00',
                                               separatorOut='0x00',
                                               separatorDisabled=True,
                                               inactivityTimeout=0.0,
                                               parentName=__NAME__,
                                               agentSupport=agentSupport,
                                               agent=agent)
        self.__tcpSniffer.handleIncomingData = self.onReceiving
        self.__tcpState = TestAdapterLib.State(parent=parent,
                                               name='CONNECTION_STATE',
                                               initial=STATE_CLOSED)

        self.__timer2MSL = TestAdapterLib.Timer(parent=parent,
                                                duration=2,
                                                name='Timer 2 MSL',
                                                callback=self.__on2MSLTimeout)
        self.__timerwait = TestAdapterLib.Timer(parent=parent,
                                                duration=2,
                                                name='Timer wait',
                                                callback=self.__onWaitTimeout)
Esempio n. 13
0
if __name__ == '__main__':
    options = [("", "")]
    iface = "eth0"
    capId = 1
    dumpFile = None
    try:
        options, args = getopt.getopt(sys.argv[1:], "i:n:o:")
    except Exception, e:
        print "Command error."
        os._exit(-1)
    for op, val in options:
        if op == "-i":
            iface = val
        elif op == "-n":
            capId = int(val)
        elif op == "-o":
            dumpFile = val
        else:
            print "Command error."
            os._exit(-1)
    if dumpFile is None:
        print "Command error."
        os._exit(-1)

    signal.signal(signal.SIGINT, sigint_handler)
    dump = flow_dump.FlowDump("Wayne_7437", capId, dumpFile)
    flowSniff = sniffer.Sniffer(iface=iface)
    flowSniff.packet_handler_callback = dump.packet_handler
    flowSniff.start()
    dump.start()
Esempio n. 14
0
#! /usr/bin/python

import sniffer

sniffer = sniffer.Sniffer()
while True:
    print '-- status =', sniffer.getStatus()

print '-- Dumping registers'
for i in range(7) + [17, 18, 26, 27, 29, 30, 31]:
    print 'reg{0:02} = 0x{1:04x}'.format(i, sniffer.readReg(i))
print '-- status =', sniffer.getStatus()
print '-- capturing...'
sniffer.capture()
print '-- done'
print '-- status =', sniffer.getStatus()
print '-- Downloading frame'
frame = sniffer.getFrame()
frameX = ['0x{0:02x}'.format(b) for b in frame]
print frameX
print '-- status =', sniffer.getStatus()
sniffer.close()
Esempio n. 15
0
def create_default_thread_sniffer():
    return sniffer.Sniffer(create_default_thread_message_factory())
Esempio n. 16
0
    websites = content.split("\n")

    i = 0
    failedWebsites = []
    server_domain = "no-such-domain-exists-ignore-no-match-1clwishoawchneowahemlwaouxmoluqxhwaq88hwxn"
    while i < len(websites):
        websiteData = websites[i].split(",")
        print("Beginning with website: " + websiteData[0] + ", domain: " +
              websiteData[1] + ", IP: " + websiteData[2])

        previous_domain = server_domain
        server_domain = websiteData[1]
        server_ip = websiteData[2]
        server_port = 443

        sniffer = sniffer.Sniffer(server_ip)

        sniffer.start()

        # rows, columns = os.popen('stty size', 'r').read().split()
        rows = 50
        columns = 80
        # Create server and bind to set ip
        socketserver.TCPServer.allow_reuse_address = True

        # httpd = socketserver.TCPServer(("127.0.0.1", 9999), MyTCPHandler)
        proxy_server.ProxyTCPHandler.set_configurations(
            server_ip, server_port, server_domain, previous_domain)
        httpd = socketserver.TCPServer(("127.0.0.1", 9999),
                                       proxy_server.ProxyTCPHandler)
        proxy = threading.Thread(target=httpd.serve_forever)
Esempio n. 17
0
    def sniffer(self):

        self.sn = sniff.Sniffer(self.iface, AK=self.url_check)
Esempio n. 18
0
def create_default_thread_sniffer(nodeid=SNIFFER_ID):
    return sniffer.Sniffer(nodeid, create_default_thread_message_factory())
Esempio n. 19
0
    def __init__(self,
                 parent,
                 debug=False,
                 name=None,
                 shared=False,
                 agentSupport=False,
                 agent=None):
        """
		This class enables to send arp request
		The lower layer is based on the ARP adapter.
	
		@param parent: parent testcase
		@type parent: testcase

		@param name: adapter name used with from origin/to destination (default=None)
		@type name: string/none
		
		@param debug: active debug mode (default=False)
		@type debug:	boolean
	
		@param shared: shared adapter (default=False)
		@type shared:	boolean	

		@param agentSupport: agent support to use a remote socket (default=False)
		@type agentSupport: boolean

		@param agent: agent to use when this mode is activated
		@type agent: string/None
		"""
        # check agent
        if agentSupport and agent is None:
            raise TestAdapterLib.ValueException(TestAdapterLib.caller(),
                                                "Agent cannot be undefined!")

        if agentSupport:
            if not isinstance(agent, dict):
                raise TestAdapterLib.ValueException(
                    TestAdapterLib.caller(),
                    "agent argument is not a dict (%s)" % type(agent))
            if not len(agent['name']):
                raise TestAdapterLib.ValueException(
                    TestAdapterLib.caller(), "agent name cannot be empty")
            if unicode(agent['type']) != unicode(AGENT_TYPE_EXPECTED):
                raise TestAdapterLib.ValueException(
                    TestAdapterLib.caller(),
                    'Bad agent type: %s, expected: %s' %
                    (agent['type'], unicode(AGENT_TYPE_EXPECTED)))

        # init adapter
        TestAdapterLib.Adapter.__init__(self,
                                        name=__NAME__,
                                        parent=parent,
                                        debug=debug,
                                        realname=name,
                                        agentSupport=agentSupport,
                                        agent=agent)
        self.arp = sniffer.Sniffer(parent=parent,
                                   debug=debug,
                                   logEventSent=True,
                                   logEventReceived=True,
                                   shared=shared,
                                   name=name,
                                   agentSupport=agentSupport,
                                   agent=agent)

        self.cfg = {}
        self.cfg['agent-support'] = agentSupport
        if agentSupport:
            self.cfg['agent'] = agent
            self.cfg['agent-name'] = agent['name']
        self.__checkConfig()