예제 #1
0
def inter_packet_correcto():
    test_pass = False
    sn = Sniffer()

    sn.inter()

    test_pass = (self.count == 1)
예제 #2
0
def test_sniff(fake_recv):
    with mock.patch("socket.socket") as fake_socket:
        fake_socket.return_value.recv.return_value = fake_recv
        sniffer = Sniffer(count_of_packets=1, validate_packets=True)
        sniffer.start()

        assert sniffer.raw_packets.get() == fake_recv
예제 #3
0
def main():
    parser = argparse.ArgumentParser("pft_icmp_check.py",
                                     description="ICMP error validation tool")
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--fromaddr',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet(s) will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        help='The interface on which to expect the ICMP error')

    args = parser.parse_args()
    sniffer = None
    if not args.recvif is None:
        sniffer = Sniffer(args, check_icmp_too_big)

    ping(args.sendif[0], args.to[0], args)

    if sniffer:
        sniffer.join()

        if sniffer.foundCorrectPacket:
            sys.exit(0)
        else:
            sys.exit(1)
예제 #4
0
파일: grpc_server.py 프로젝트: p4vbox/vIFC
def sniffer_thread():
    global packetLim

    sniffer_instance = Sniffer(ServerConfig.PACKETIN_IFACE, 1500)

    newPacketIn = PacketInStruct()
    c_packet_id = 0

    print "Sniffer Thread Started"

    while True:
        pack_data = sniffer_instance.recv_packet_in()
        if (pack_data != False) and pack_data[0] >= 0 and pack_data[0] < len(
                packetLim) and (not packetLim[pack_data[0]]):
            packetLim[pack_data[0]] = True

            newPacketIn = PacketInStruct()
            newPacketIn.packetInResponse = p4runtime_pb2.StreamMessageResponse(
            )
            newPacketIn.packetInResponse.packet.payload = pack_data[2]
            newPacketIn.metadata = newPacketIn.packetInResponse.packet.metadata.add(
            )
            newPacketIn.metadata.metadata_id = pack_data[0]
            newPacketIn.metadata.value = pack_data[1]
            newPacketIn.packet_id = c_packet_id

            c_packet_id = c_packet_id + 1

            print "EXPT: Packet-in (%d): interface => server %.9f" % (
                c_packet_id, time.time())
            ConnectionArray.sendPacketInToBuffer(newPacketIn)
예제 #5
0
def test_seleccion_interfaz():
    test_pass = False
    sn = Sniffer()
    if_example = 'example'

    sn.select_iface(if_example)
    test_pass = (sn.selected_iface == if_example)
    assert test_pass
예제 #6
0
파일: client.py 프로젝트: Hainish/cerealbox
    def new_connection_handler(self, code, lport, rmac, rip, rport, cc, cont):
        push_arr = [str(code), Sniffer.mac_to_hex(rmac), Sniffer.ip_to_hex(rip), Sniffer.port_to_hex(rport), cc, cont]
        push = ",".join(push_arr)
        print push,
        print "(%s:%s <-> %s)" % (rip, rport, lport)
        self._write_to_client(push)

        curr = self.sniffer.numopen - self.sniffer.numclose
        print "close: %s open: %s, current: %s" % (str(self.sniffer.numclose), str(self.sniffer.numopen), str(curr))
예제 #7
0
파일: asniff.py 프로젝트: xpumapu/wifi-exp
def test():
        ip = "127.0.0.1"
        iface = "moni0"
        log = "tc1.pcap"
	res = "tc1_res.pcap"
	text_res = "tc1_text_res.log"

        snif = Sniffer(ip = ip, iface = iface)
        snif.show_info()
        snif.set_log_file(log)
예제 #8
0
def test_se_detectan_interfaces():
    test_pass = False
    sn = Sniffer()
    res = []

    res = sn.detect_ifaces()

    if res:
        test_pass = True

    assert test_pass
예제 #9
0
def pcap_to_flow_convertor(config):
    print "Start conversion from pcap to flow..."

    from sniffer import Sniffer
    sniff = Sniffer(config.get_protocol_file(), config.get_flow_timeout())

    files = config.pcap_files()
    for f in files:
        sniff.convert_flow(f['src'], f['dest'])

    print "Conversion done."
예제 #10
0
    def __init__(self):
        self.clear_packet_queue()

        self._db = musicalDatabase.request_database("MusicalPackets")
        self._db_collection = self._db.open_collection("packets")

        networkSniffer = Sniffer()
        networkSniffer.add_callback(self)

        self._thread = threading.Thread(target=networkSniffer)
        self._thread.daemon = True
        self._thread.start()
예제 #11
0
파일: main.py 프로젝트: lzchmily/WiFi--
def action_sniff(db, args):
    "Run sniffing thread"
    from sniffer import Sniffer

    sniffer = Sniffer(db,
                      args.interface,
                      args.related_interface,
                      sniffer_name=args.sniffer_name,
                      enable_hopping=args.enable_hopping,
                      use_24=args.use_24,
                      use_pop5=args.use_pop5)
    sniffer.run()
예제 #12
0
    def __init__(self):
        self.clear_packet_queue()

        self._db = musicalDatabase.request_database("MusicalPackets")
        self._db_collection = self._db.open_collection("packets")

        networkSniffer = Sniffer()
        networkSniffer.add_callback(self)

        self._thread = threading.Thread(target=networkSniffer)
        self._thread.daemon = True
        self._thread.start()
예제 #13
0
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    # Start sniffing on recvif
    sniffer = Sniffer(args, check_icmp6_error)

    ########################################################################
    #
    # A single start fragment with payload length not % 8.
    #
    # A:  Error handling in code.
    # R:  ICMPv6 param problem.
    #
    data = "6" * 1287
    ip6f01 = sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0]) / \
     sp.IPv6ExtHdrFragment(offset=0, m=1, id=5) / \
     sp.UDP(dport=3456, sport=6543) / \
     data
    if args.debug:
        ip6f01.display()
    sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

    sleep(0.10)
    sniffer.join()
    if not sniffer.foundCorrectPacket:
        sys.exit(1)

    sys.exit(0)
예제 #14
0
def main():
    parser = argparse.ArgumentParser("pft_ping.py",
                                     description="Ping test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet(s) will be sent')
    parser.add_argument(
        '--recvif',
        nargs=1,
        help='The interface on which to expect the ICMP echo response')
    parser.add_argument('--ip6', action='store_true', help='Use IPv6')
    parser.add_argument(
        '--to',
        nargs=1,
        required=True,
        help='The destination IP address for the ICMP echo request')

    # Packet settings
    parser.add_argument('--send-tos',
                        nargs=1,
                        help='Set the ToS value for the transmitted packet')

    # Expectations
    parser.add_argument('--expect-tos',
                        nargs=1,
                        help='The expected ToS value in the received packet')

    args = parser.parse_args()

    # We may not have a default route. Tell scapy where to start looking for routes
    sp.conf.iface6 = args.sendif[0]

    sniffer = None
    if not args.recvif is None:
        sniffer = Sniffer(args, check_ping_request)

    if args.ip6:
        ping6(args.sendif[0], args.to[0], args)
    else:
        ping(args.sendif[0], args.to[0], args)

    if sniffer:
        sniffer.join()

        if sniffer.foundCorrectPacket:
            sys.exit(0)
        else:
            sys.exit(1)
예제 #15
0
 def __init__(self, args, loop=None, packet_callback=None, **kwargs):
     self.sniffer = Sniffer(argv=args,
                            packet_callback=packet_callback,
                            loop=loop,
                            **kwargs)
     self.packets_count = 0
     self.packets = []
     self.packets_by_time = defaultdict(list)
     self.start_time = None
     self.last_time = None
     self.ips = set()
     self.ports_by_addr = defaultdict(set)
     self.filters = defaultdict(lambda: ANY)
     self.online = None
예제 #16
0
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    # Start sniffing on recvif
    sniffer = Sniffer(args, check_icmp6_error)

    ########################################################################
    #
    # 0-byte first fragment.
    #
    # A:  0-byte fragment payload not allowed. Discarded.
    # R:  ICMPv6 param prob, paramprob header.
    #
    ip6f01 = sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0]) / \
     sp.IPv6ExtHdrFragment(offset=0, m=1, id=4)
    if args.debug:
        ip6f01.display()
    sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

    sleep(0.10)
    sniffer.join()
    if not sniffer.foundCorrectPacket:
        sys.exit(1)

    sys.exit(0)
예제 #17
0
def sniffing(config, algorithm, feature, logger):
    if config.sniffer_active():
        print "Start sniffing..."

        print "implement continuous monitoring"
        print "This means:"
        print "\t capturing packets"
        print "\t converting to netflow"
        print "\t analyse closed flow"

        from sniffer import Sniffer
        sniff = Sniffer(config.get_protocol_file(), feature, logger, config.get_flow_timeout())
        sniff.sniff_tshark(algorithm)

        print "End sniffing.\n"
예제 #18
0
def test_connect():
    print("Got a connection")
    global thread
    global pcap_file
    if thread is None:
        thread = socketio.start_background_task(
            target=lambda: Sniffer(socketio, pcap_file=pcap_file).run())
예제 #19
0
 def test_hello(self):
     print ""
     print "TEST HELLO"
     print ""
     config_client = {
         "sync_server_ip": "stacksync.urv.cat",
         "sync_server_port": 8080,
         "packet_limit": -1,
         "max_bytes": 65535,
         "promiscuous": False,
         "read_timeout": 100
     }
     print config_client
     sniff = Sniffer(self.personal_cloud,  config_client)
     result = sniff.hello()
     self.assertEqual(result, 0)
예제 #20
0
    def __init__(self, master=None):
        self.master = master
        master.title = self.TITLE
        master.wm_title(self.TITLE)
        width = master.winfo_screenwidth()
        height = master.winfo_screenheight()

        self.canvas = Canvas(
            width=master.winfo_screenwidth(),
            height=master.winfo_screenheight(),
            bg=self.BACKGROUND_COLOR,
            highlightthickness=0
        )
        self.canvas.pack(expand=YES, fill=BOTH)
        self.canvas.create_line(
            width - (width/10),
            0,
            width - (width/10),
            height,
            width = 10,
            fill = '#839496'
        )
        self.sniffer = Sniffer(self.canvas, width, height)
        thread = threading.Thread(target=self.sniffer.sniff)
        thread.start()
예제 #21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--interface', help="the interface to bind to")
    parser.add_argument('-p', '--port', type=int, help="the port to grab packets from.  Default: 6379", default=6379)
    parser.add_argument('--out', help="the location to generate the full or event logs, defaults to the directory the \
                        application is executed from")
    parser.add_argument('-l', choices=['debug', 'event', 'full'], default='full', help="the type of log(s) you want to \
                        create. Default: both")
    parser.add_argument('-el', '--event-log', default="event_sniff", help="the name of the event outout file. \
                        Default: event_sniff")
    parser.add_argument('-fl', '--full-log', default="full_sniff", help="the name of the full sniff output file. \
                        Default: full_sniff")
    parser.add_argument('-f', '--filter', default="none", help="comma separated list of events to log(ex: setex,delete)"
                        )
    parser.add_argument('--append', default="_sniff", help="the suffix to append to command logs")
    args = parser.parse_args()
    fmt_full = '%.6f %-21s %8d %8d %s\n'
    fmt = '%s\n'
    path = ""
    event_filters = args.filter.split(',')
    if args.out:
        path = args.out
    logger = Log(args.l, path, {'event': args.event_log, 'full': args.full_log}, event_filters, args.append)

    for session in Sniffer.sniff(args.interface, args.port):
        ptime, client, req_size, resp_size, command = session
        comm_parts = command.split()
        if comm_parts[0].lower() in event_filters:
            logger.write_command(comm_parts[0].lower(), command)
        if args.l == 'event':
            logger.write_event(fmt % command)
        if args.l == 'full':
            logger.write_log(fmt_full % (ptime, client, req_size, resp_size, command))
예제 #22
0
파일: app.py 프로젝트: matheper/sniffer
    def __init__(self):
        #carrega o arquivo Glade
        self.appglade = "app.glade"
        #carrega xml
        self.xml = gtk.glade.XML(self.appglade)
        self.xml.signal_autoconnect(self)

        #Campo Tree
        self.lstConsulta = self.xml.get_widget("lstConsulta")
        self.entryFilter = self.xml.get_widget("entry1")
        self.lstConsulta.set_headers_visible(True)
        self.sniffer = Sniffer()
        self.format_grid()
        self.capturing = False

        # carrega botoes
        self.btnIniciar = self.xml.get_widget("btnIniciar")
        self.btnParar = self.xml.get_widget("btnParar")
        self.btnCarregar = self.xml.get_widget("btnCarregar")
        self.btnEstatisticas = self.xml.get_widget("btnEstatisticas")
        self.btnGraficos = self.xml.get_widget("btnGraficos")
        self.btnLimparCaptura = self.xml.get_widget("btnLimparCaptura")
        self.btnFiltrar = self.xml.get_widget("btnFiltrar")
        self.btnLimpar = self.xml.get_widget("btnLimpar")
        self.set_buttons()
예제 #23
0
파일: client.py 프로젝트: Hainish/cerealbox
    def start(self):
        self.client = SSLClientWrapper()
        self.client.start(self.host, self.port, self.password)

        self.sniffer = Sniffer()
        self.sniffer.set_new_connection_handler(self.new_connection_handler)
        self.sniffer.sniff(self.net_device, self.my_ipaddr, self.dns)
예제 #24
0
def main():
    parser = argparse.ArgumentParser("CVE-2019-icmp.py",
                                     description="CVE-2019-icmp test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')

    args = parser.parse_args()

    # Send the allowed packet to establish state
    udp = sp.Ether() / \
        sp.IP(src=args.src[0], dst=args.to[0]) / \
        sp.UDP(dport=53, sport=1234)
    sp.sendp(udp, iface=args.sendif[0], verbose=False)

    # Start sniffing on recvif
    sniffer = Sniffer(args, check_icmp_error)

    # Send the bad error packet
    icmp_reachable = sp.Ether() / \
               sp.IP(src=args.src[0], dst=args.to[0]) / \
        sp.ICMP(type=3, code=3) / \
        sp.IP(src=args.src[0], dst=args.to[0]) / \
        sp.UDP(dport=53, sport=1234)
    sp.sendp(icmp_reachable, iface=args.sendif[0], verbose=False)

    sniffer.join()
    if sniffer.foundCorrectPacket:
        sys.exit(1)

    sys.exit(0)
예제 #25
0
def main():
	parser = argparse.ArgumentParser("pft_ping.py",
		description="Ping test tool")
	parser.add_argument('--sendif', nargs=1,
		required=True,
		help='The interface through which the packet(s) will be sent')
	parser.add_argument('--recvif', nargs=1,
		help='The interface on which to expect the ICMP echo response')
	parser.add_argument('--ip6', action='store_true',
		help='Use IPv6')
	parser.add_argument('--to', nargs=1,
		required=True,
		help='The destination IP address for the ICMP echo request')

	# Packet settings
	parser.add_argument('--send-tos', nargs=1,
		help='Set the ToS value for the transmitted packet')

	# Expectations
	parser.add_argument('--expect-tos', nargs=1,
		help='The expected ToS value in the received packet')

	args = parser.parse_args()

	# We may not have a default route. Tell scapy where to start looking for routes
	sp.conf.iface6 = args.sendif[0]

	sniffer = None
	if not args.recvif is None:
		sniffer = Sniffer(args, check_ping_request)

	if args.ip6:
		ping6(args.sendif[0], args.to[0], args)
	else:
		ping(args.sendif[0], args.to[0], args)

	if sniffer:
		sniffer.join()

		if sniffer.foundCorrectPacket:
			sys.exit(0)
		else:
			sys.exit(1)
예제 #26
0
파일: pcp.py 프로젝트: mola/FreeBSD-src
def main():
	parser = argparse.ArgumentParser("pcp.py",
		description="PCP test tool")
	parser.add_argument('--recvif', nargs=1,
		required=True,
		help='The interface where to look for packets to check')
	parser.add_argument('--expect-pcp', nargs=1,
		help='The expected PCP value on VLAN packets')

	args = parser.parse_args()

	sniffer = Sniffer(args, check_pcp, recvif=args.recvif[0], timeout=20)

	sniffer.join()

	if sniffer.foundCorrectPacket:
		sys.exit(0)

	sys.exit(1)
예제 #27
0
def main():
    parser = argparse.ArgumentParser()
    source_group = parser.add_mutually_exclusive_group(required=True)
    source_group.add_argument('-i', '--interface', help="the interface to bind to")
    source_group.add_argument('-F', '--file', help="pcap file containing captured traffic to analyze")
    parser.add_argument('-p', '--port', type=int, help="the port to grab packets from.  Default: 6379", default=6379)
    parser.add_argument('--out', default='.', help="the location to generate the full or event logs, defaults to the \
                        directory the application is executed from")
    parser.add_argument('-l', choices=['debug', 'event', 'full'], default='full', help="the type of log(s) you want to \
                        create. Default: full")
    parser.add_argument('-el', '--event-log', default="event", help="the name of the event outout file. \
                        Default: event_sniff")
    parser.add_argument('-fl', '--full-log', default="full", help="the name of the full sniff output file. \
                        Default: full_sniff")
    parser.add_argument('-f', '--filter', default="", help="comma separated list of events to log(ex: setex,delete)"
                        )
    parser.add_argument('--append', default="_sniff", help="the suffix to append to command logs")
    parser.add_argument('--extra', help="log non-redis traffic")
    args = parser.parse_args()
    fmt_full = '%.6f %-21s %8d %8d %s\n'
    fmt = '%s\n'
    event_filters = args.filter.split(',') if args.filter else []

    logger = Log(args.l, args.out, {'event': args.event_log, 'full': args.full_log}, event_filters, args.append)

    log_level = logging.INFO
    if args.l == 'debug':
        log_level = logging.DEBUG

    logging.basicConfig(filename=os.path.join(args.out, 'sniffer.log'), level=log_level)

    source = args.interface if args.interface else args.file
    sniffer = Sniffer(source, args.port)

    for session in sniffer.sniff():
        ptime, client, req_size, resp_size, command = session
        comm_parts = command.split()
        if comm_parts[0].lower() in event_filters:
            logger.write_command(comm_parts[0].lower(), command)
        if logger.event_log:
            logger.write_event(fmt % command)
        if logger.full_log:
            logger.write_log(fmt_full % (ptime, client, req_size, resp_size, command))
예제 #28
0
    def __init__(self, *args, **kwargs):
        """Initialize device."""
        self.args = args
        self.kwargs = kwargs
        config = kwargs.get("config", kwargs)

        self.unique_id = os.getenv("SUDO_USER", os.getenv("USER", ""))
        self.docker_network = config.get("docker_network",
                                         "prplMesh-net-{}".format(self.unique_id))
        self.role = config.get("role", "agent")
        self.connection_type = config.get("connection_type", None)
        self.conn_cmd = config.get("conn_cmd", None)
        self.wan_ip = config.get("wan_ip", None)
        self.username = config.get("username", "root")

        self.name = "-".join((config.get("name", "netgear-rax40"), self.unique_id))

        # If no WAN IP is set in config file retrieve IP from docker network set in config
        # X.X.X.245 IP will be selected from docker network
        if not self.wan_ip:
            self.connection = connection_decider.connection(device=self,
                                                            conn_type="local_serial",
                                                            **kwargs)
            self.connection.connect()
            self.consoles = [self]
            self.logfile_read = sys.stdout
            self.wan_network = self.get_docker_subnet()
            self.wan_ip = self.wan_network[+245]
            self.set_iface_ip("br-lan", self.wan_ip, self.wan_network.prefixlen)
            self.close()
            self.kill(signal.SIGTERM)
            # Removal of PID is required by pexpect in order to spawn a new process
            # serial connection should be terminated by 2 commands above
            self.pid = None

        self.wired_sniffer = Sniffer(_get_bridge_interface(self.docker_network),
                                     boardfarm.config.output_dir)
        self.connection = connection_decider.connection(device=self,
                                                        conn_type="ssh",
                                                        conn_cmd="ssh {}@{}".format(
                                                            self.username, self.wan_ip))
        self.connection.connect()
        # Append active connection to the general array for logging
        self.consoles = [self]
        # Point what to log as data read from child process of pexpect
        # Result: boardfarm will log communication in separate file
        self.logfile_read = sys.stdout
        self.add_iface_to_bridge(self.wan_iface, "br-lan")

        if self.role == "controller":
            self.controller_entity = ALEntityPrplWrt(self, is_controller=True)
        else:
            self.agent_entity = ALEntityPrplWrt(self, is_controller=False)
            self.prplmesh_start_agent()
예제 #29
0
    def test_capture(self):
        print ""
        print "TEST CAPTURE"
        print ""
        config_client = {
            "sync_server_ip": "stacksync.urv.cat",
            "sync_server_port": 8080,
            "packet_limit": -1,
            "max_bytes": 65535,
            "promiscuous": False,
            "read_timeout": 100
        }
        print config_client
        sniff = Sniffer(self.personal_cloud,  config_client)
        result = sniff.run()
        print result
        result = sniff.rage_quit()

        # pdb.set_trace()
        self.assertEqual(0, 0)
예제 #30
0
def run(config, args):

    url_list = np.loadtxt(args.url, delimiter='\n', dtype=str)
    url_list = np.random.permutation(url_list).tolist()  # Shuffle url list
    sniff_done_dict = {url: 0 for url in url_list}  # Record sniff result

    browser_path = config['TorBrowser']['browser_path']
    socks_port = int(config['TorBrowser']['socks_port'])
    control_port = int(config['TorBrowser']['control_port'])
    headless = config['TorBrowser'].getboolean('headless')
    executable_path = config['TorBrowser']['executable_path']
    capture_screen = config['TorBrowser']['capture_screen']

    # default save_path is current_directory/result
    # batch directory save_path/url/epoch/batch
    # sequence directory save_path/url/epoch
    save_path = config['CaptureProgram']['save_path']
    save_path = os.path.join(os.getcwd(), save_path)

    batch_size = int(config['Batch']['batch_size'])
    total_size = int(config['Batch']['total_size'])
    sleep_batch = int(config['Batch']['sleep_batch'])
    sleep_url = int(config['Batch']['sleep_url'])
    sleep_epoch = int(config['Batch']['sleep_epoch'])

    tor_driver = TorBrowser(browser_path=browser_path,
                            socks_port=socks_port,
                            executable_path=executable_path,
                            control_port=control_port,
                            headless=headless)
    sniffer = Sniffer(tbb_driver=tor_driver,
                      config=config,
                      capture_screen=capture_screen,
                      sniff_done_dict=sniff_done_dict)

    if args.batch is True:
        run_batch(sniffer, batch_size, total_size, url_list, save_path,
                  sleep_batch, sleep_url, sleep_epoch)
    elif args.batch is False:
        num_of_repeat = args.num
        run_sequence(sniffer, url_list, num_of_repeat, save_path, sleep_batch,
                     sleep_epoch)
    elif args.reamin is True:
        try:
            remain_json = open(args.json)
            remain_json = json.load(remain_json)
        except:
            logger.error('File not existed')
            exit(1)
        run_remain(sniffer, batch_size, total_size, remain_json, save_path,
                   sleep_batch, sleep_url, sleep_epoch)
    else:
        logger.error('Wrong argument is inserted. Please read argument help.')
        exit(1)
예제 #31
0
def sniffer_thread():
    sniffer_instance = Sniffer(ServerConfig.PACKETIN_IFACE, 1500)

    newPacketIn = PacketInStruct()

    print "Sniffer Thread Started"

    while True:
        pack_data = sniffer_instance.recv_packet_in()
        if pack_data is not False and pack_data[
                0] < 4:  #TODO: Remover "and pack_data[0] < 4", esta aqui para nao capturar outros pacotes na interface de teste
            newPacketIn.packetInResponse = p4runtime_pb2.StreamMessageResponse(
            )
            newPacketIn.packetInResponse.packet.payload = pack_data[2]
            newPacketIn.metadata = newPacketIn.packetInResponse.packet.metadata.add(
            )
            newPacketIn.metadata.metadata_id = pack_data[0]
            newPacketIn.metadata.value = pack_data[1]

            print "Packet-in: interface => server %.9f" % time.time()
            ConnectionArray.sendPacketInToBuffer(newPacketIn)
예제 #32
0
def main():
    parser = argparse.ArgumentParser(
        "frag6.py", description="IPv6 fragementation test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet will be sent')
    parser.add_argument('--recvif',
                        nargs=1,
                        required=True,
                        help='The interface on which to check for the packet')
    parser.add_argument('--src',
                        nargs=1,
                        required=True,
                        help='The source IP address')
    parser.add_argument('--to',
                        nargs=1,
                        required=True,
                        help='The destination IP address')
    parser.add_argument('--debug',
                        required=False,
                        action='store_true',
                        help='Enable test debugging')

    args = parser.parse_args()

    # Start sniffing on recvif
    sniffer = Sniffer(args, check_icmp6_error)

    ########################################################################
    #
    # A single start fragment with zero length IPv6 header (jumbo).
    # Make sure we do hit the Fragment case, which is tricky as the
    # jumbogram needs to be > 64k.
    #
    # A:  Jumbo-Fragment not allowed.
    # R:  ICMPv6 param problem.
    #
    #data = "6" * (65536 - 2 - 6 - 8 - 8)
    data = "6" * 65512
    ip6f01 = sp.Ether() / \
     sp.IPv6(src=args.src[0], dst=args.to[0], plen=0) / \
     sp.IPv6ExtHdrHopByHop(options=sp.Jumbo(jumboplen=65536)) / \
     sp.IPv6ExtHdrFragment(offset=0, m=1, id=6) / \
     sp.UDP(dport=3456, sport=6543) / \
     data
    if args.debug:
        ip6f01.display()
    sp.sendp(ip6f01, iface=args.sendif[0], verbose=False)

    # We should only need to sleep 0.10 but it seems scapy
    # takes time for this one.
    sleep(75)
    sniffer.setEnd()
    sniffer.join()
    if not sniffer.foundCorrectPacket:
        sys.exit(1)

    sys.exit(0)
예제 #33
0
def main():
	parser = argparse.ArgumentParser("CVE-2019-icmp.py",
		description="CVE-2019-icmp test tool")
	parser.add_argument('--sendif', nargs=1,
		required=True,
		help='The interface through which the packet will be sent')
	parser.add_argument('--recvif', nargs=1,
		required=True,
		help='The interface on which to check for the packet')
	parser.add_argument('--src', nargs=1,
		required=True,
		help='The source IP address')
	parser.add_argument('--to', nargs=1,
		required=True,
		help='The destination IP address')

	args = parser.parse_args()

        # Send the allowed packet to establish state
        udp = sp.Ether() / \
            sp.IP(src=args.src[0], dst=args.to[0]) / \
            sp.UDP(dport=53, sport=1234)
        sp.sendp(udp, iface=args.sendif[0], verbose=False)

	# Start sniffing on recvif
	sniffer = Sniffer(args, check_icmp_error)

	# Send the bad error packet
	icmp_reachable = sp.Ether() / \
            sp.IP(src=args.src[0], dst=args.to[0]) / \
	    sp.ICMP(type=3, code=3) / \
	    sp.IP(src=args.src[0], dst=args.to[0]) / \
	    sp.UDP(dport=53, sport=1234)
	sp.sendp(icmp_reachable, iface=args.sendif[0], verbose=False)

	sniffer.join()
	if sniffer.foundCorrectPacket:
		sys.exit(1)

	sys.exit(0)
예제 #34
0
def angiesn():

    #Creamos un Sniffer
    sn = Sniffer()

    #Detectamos interfaces y preguntamos cual
    #Queremos usar hasta que haya una respuesta correcta

    detected_interfaces = sn.detect_ifaces()

    print("AngieSN HA DETECTADO LOS SIGUIENTES INTERFACES: " +
          str(detected_interfaces))
    if_option = input("¿Cual desea usar? -->  ")

    while not if_option in detected_interfaces:
        if_option = input(
            "No existe ese interfaz. Introduzca un interfaz válido:  ")

    #Selecionamos el interfaz y sniffamos
    sn.select_iface(if_option)

    filter_option = input(
        "Escribe un filtro con sintáxis BPF (por defecto ninguno):  ")

    if filter_option == '':
        filter_option = None

    res = sn.begin_sniff(filter_option)
예제 #35
0
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

        config = kwargs.get("config", kwargs)

        # List of device's consoles test can interact with
        self.consoles = [self]

        # Getting unic ID to distinguish devices and network they belong to
        self.unique_id = os.getenv("SUDO_USER", os.getenv("USER", ""))

        self.name = config.get("name", "prplmesh_docker")
        self.docker_name = "-".join(
            (config.get("name", "prplmesh_docker"), self.unique_id))
        self.role = config.get("role", "agent")
        self.cleanup_cmd = config.get("cleanup_cmd", None)
        self.conn_cmd = config.get("conn_cmd", None)
        self.delay = config.get("delay", 7)
        self.docker_network = config.get(
            "docker_network", "prplMesh-net-{}".format(self.unique_id))

        docker_cmd = os.path.join(rootdir, "tools", "docker", "run.sh")
        docker_args = [
            "--verbose", "--detach", "--force", "--name", self.docker_name,
            "--network", self.docker_network, "--expose", "8002"
        ]

        if self.role == "controller":
            # Spawn dockerized controller
            docker_args.append("start-controller-agent")
            self._run_shell_cmd(docker_cmd, docker_args)

            time.sleep(self.delay)
            self.controller_entity = ALEntityDocker(self.docker_name,
                                                    device=self,
                                                    is_controller=True)
        else:
            # Spawn dockerized agent
            docker_args.append("start-agent")
            self._run_shell_cmd(docker_cmd, docker_args)

            time.sleep(self.delay)
            self.agent_entity = ALEntityDocker(self.docker_name,
                                               device=self,
                                               is_controller=False)

        self.wired_sniffer = Sniffer(
            _get_bridge_interface(self.docker_network),
            boardfarm.config.output_dir)
        self.check_status()
예제 #36
0
 def scan_udp_ports(self, ports):
     s = Sniffer()
     s.start()
     self._scan_ports(ports, self.scan_udp_port)
     s.stop.set()
     s.join()
     closed_ports = self.get_closed_udp_ports(s.packets)
     return [Port('UDP', p) for p in ports if p not in closed_ports]
예제 #37
0
파일: client.py 프로젝트: Hainish/cerealbox
class Client:
    @staticmethod
    def usage():
        print "Usage: python ./client.py HOST PORT NET_DEVICE IPADDR PASSWORD [DNS]"

    def __init__(self, host, port, net_device, my_ipaddr, password, dns):
        self.host = host
        self.port = port
        self.net_device = net_device
        self.my_ipaddr = my_ipaddr
        self.password = password
        self.dns = dns

    def new_connection_handler(self, code, lport, rmac, rip, rport, cc, cont):
        push_arr = [str(code), Sniffer.mac_to_hex(rmac), Sniffer.ip_to_hex(rip), Sniffer.port_to_hex(rport), cc, cont]
        push = ",".join(push_arr)
        print push,
        print "(%s:%s <-> %s)" % (rip, rport, lport)
        self._write_to_client(push)

        curr = self.sniffer.numopen - self.sniffer.numclose
        print "close: %s open: %s, current: %s" % (str(self.sniffer.numclose), str(self.sniffer.numopen), str(curr))

    # in case both threads are writing at the same time
    def _write_to_client(self, push):
        try:
            self.client.writeln(push)
        except SSLError:
            time.sleep(0.1)
            self._write_to_client(push)

    def start(self):
        self.client = SSLClientWrapper()
        self.client.start(self.host, self.port, self.password)

        self.sniffer = Sniffer()
        self.sniffer.set_new_connection_handler(self.new_connection_handler)
        self.sniffer.sniff(self.net_device, self.my_ipaddr, self.dns)
예제 #38
0
파일: stp.py 프로젝트: mola/FreeBSD-src
def main():
    parser = argparse.ArgumentParser("stp.py", description="STP test tool")
    parser.add_argument(
        '--sendif',
        nargs=1,
        required=True,
        help='The interface through which the packet(s) will be sent')
    parser.add_argument(
        '--recvif',
        nargs=1,
        help='The interface on which to expect the ICMP echo request')

    args = parser.parse_args()

    sniffer = Sniffer(args, check_stp)

    invalid_stp(args.sendif[0])

    sniffer.join()

    # The 'correct' packet is a corrupt STP packet, so it shouldn't turn up.
    if sniffer.foundCorrectPacket:
        sys.exit(1)
예제 #39
0
def main():

    sniffer = Sniffer(**vars(args))
    logging.info("[*] Start sniffing...")
    sniffer.start()
    try:
        while True:
            sleep(100)
    except KeyboardInterrupt:
        logging.info("[*] Stop sniffing")
        sniffer.join(2.0)

        if sniffer.is_alive():
            sniffer.socket.close()
예제 #40
0
def main():
    global got_pfsync
    global got_ping
    global sent_ping

    parser = argparse.ArgumentParser("pfsync_defer.py",
                                     description="pfsync defer mode test")
    parser.add_argument('--syncdev',
                        nargs=1,
                        required=True,
                        help='The pfsync interface')
    parser.add_argument('--outdev',
                        nargs=1,
                        required=True,
                        help='The interface we will send packets on')
    parser.add_argument('--indev',
                        nargs=1,
                        required=True,
                        help='The interface we will receive packets on')

    args = parser.parse_args()

    syncmon = Sniffer(args, check_pfsync, args.syncdev[0])
    datamon = Sniffer(args, check_reply, args.indev[0])

    # Send traffic on datadev, which should create state and produce a pfsync message
    ping(args.outdev[0])

    syncmon.join()
    datamon.join()

    if not got_pfsync:
        sys.exit(1)

    if not got_ping:
        sys.exit(1)

    if got_pfsync > got_ping:
        sys.exit(1)

    # Deferred packets are delayed up to 20ms (unless the pfsync peer, which we
    # don't have here, acks their state update earlier)
    if (sent_ping + 0.020) > got_ping:
        sys.exit(1)
예제 #41
0
파일: netmo.py 프로젝트: codebox/netmo
class QueueManager:
    def __init__(self):
        self.queues = []

    def subscribe(self, queue):
        self.queues.append(queue)

    def unsubscribe(self, queue):
        self.queues.remove(queue)

    def submit(self, item):
        for queue in self.queues:
            queue.put(item)


if __name__ == '__main__':
    packet_queue = QueueManager()
    dns_queue    = QueueManager()

    file_manager = FileManager('web')
    web_server   = WebServer(file_manager, packet_queue, dns_queue)

    reverse_dns = ReverseDns(dns_queue)

    sniffer = Sniffer(packet_queue, reverse_dns)
    sniffer.start()

    WebServer(file_manager, packet_queue, dns_queue).start('0.0.0.0', 8182)


예제 #42
0
파일: app.py 프로젝트: matheper/sniffer
class App(object):
    """Sniffer Interface
    """

    def __init__(self):
        #carrega o arquivo Glade
        self.appglade = "app.glade"
        #carrega xml
        self.xml = gtk.glade.XML(self.appglade)
        self.xml.signal_autoconnect(self)

        #Campo Tree
        self.lstConsulta = self.xml.get_widget("lstConsulta")
        self.entryFilter = self.xml.get_widget("entry1")
        self.lstConsulta.set_headers_visible(True)
        self.sniffer = Sniffer()
        self.format_grid()
        self.capturing = False

        # carrega botoes
        self.btnIniciar = self.xml.get_widget("btnIniciar")
        self.btnParar = self.xml.get_widget("btnParar")
        self.btnCarregar = self.xml.get_widget("btnCarregar")
        self.btnEstatisticas = self.xml.get_widget("btnEstatisticas")
        self.btnGraficos = self.xml.get_widget("btnGraficos")
        self.btnLimparCaptura = self.xml.get_widget("btnLimparCaptura")
        self.btnFiltrar = self.xml.get_widget("btnFiltrar")
        self.btnLimpar = self.xml.get_widget("btnLimpar")
        self.set_buttons()

    def start(self, widget, data):
        """ Inicia a captura dos pacotes. """
        if not self.capturing:
            self.format_grid()
            self.capturing = True
            self.set_buttons()
            gtk.gdk.threads_init()
            cap = threading.Thread(target=self.capture)
            cap.start()
            

    def format_grid(self):
        #Formata controle lista
        self.ClearColunas()
        self.listbox_types = [str,str,str,str,str,str,str,str,str,str,str]
        self.listbox_data = self.sniffer.capture_list
        self.lstConsulta.set_model(self.get_dados(self.listbox_data, self.listbox_types))

        #Cria colunas da lista
        self.listbox_header = [ ('IP Origem',0), ('Tipo',1), ('IP Destino',2), ('Tipo',3),
                                ('Próximo Cabeçalho',4), ('Hop Limit',5),
                                ('Classe de Tráfego',6), ('',7), ('',8),
                                ('Flowlabel',9), ('Versão',10)
                              ]
        self.CriarColuna(self.listbox_header)

    def stop(self, widget, data):
        """ Para a captura dos pacotes. """
        if self.capturing:
            self.capturing = False
            self.set_buttons()

    def filter(self, widget, data):
        """ Filtra os pacotes. """
        self.listbox_data = self.sniffer.capture_filter(self.entryFilter.get_text())
        self.listbox_update()

    def clear(self, widget, data):
        """Limpa todos os filtros."""
        self.listbox_data = self.sniffer.capture_list
        self.listbox_update()

    def load(self, widget, data):
        """Carrega arquivo capture.cap."""
        self.sniffer.read_file('capture.cap')
        self.listbox_data = self.sniffer.capture_list
        self.listbox_update()

    def statistics(self, widget, data):
        """Abre janela com media de proximos cabecalhos e tabela de fluxo. """
        self.statsglade = "statistics.glade"
        self.statsxml = gtk.glade.XML(self.statsglade)
        self.lstStats = self.statsxml.get_widget("lstStatistics")

        for coluna in range(4):
            titulo = ""
            id = coluna
            renderer = gtk.CellRendererText()
            column = gtk.TreeViewColumn(titulo, renderer, text = id)
            column.set_resizable(False)
            self.lstStats.append_column(column)

        self.listStats_types = [str,str,str,str]
        self.listStats_data = self.sniffer.get_statistics()
        self.lstStats.set_model(self.get_dados(self.listStats_data, self.listStats_types))
        print "teste"

    def graphcs(self, widget, data):
        """Dispara acao que abre nova janela com graficos. """
        self.open_graphs()

    def captureClear(self, widget, data):
        """Limpa listas de captura do sniffer. """
        self.sniffer.clearAll()
        self.listbox_data = self.sniffer.capture_list
        self.listbox_update()

    def quitMainWindow(self, widget, data):
        """ Sai do loop principal de eventos, finalizando o programa. """
        gtk.main_quit()

    def CriarColuna(self, colunas):
        """ Cria coluna da lista
        """
        for coluna in colunas:
            titulo = coluna[0]
            id = coluna[1]
            renderer = gtk.CellRendererText()
            column = gtk.TreeViewColumn(titulo, renderer, text = id)
            column.set_resizable(False)
            self.lstConsulta.append_column(column)

    def ClearColunas(self):
        """ Limpa colunas da lista. """
        for coluna in self.lstConsulta.get_columns():
            self.lstConsulta.remove_column(coluna)

    def listbox_update(self):
        """Atualiza dados da listbox. """
        self.lstConsulta.set_model(self.get_dados(self.listbox_data, self.listbox_types))

    def get_dados(self,dados,types):
        """ Adiciona as linhas nas respectivas colunas da listbox."""
        retorno = gtk.ListStore(*types)
        for dado in dados:
            retorno.append(dado)
        return retorno

    def capture(self):
        """ Captura pacotes da rede. """
        while self.capturing:
            self.sniffer.get_packet()
            self.listbox_data = self.sniffer.capture_list
            self.listbox_update()

    def open_graphs(self):
        """ Carrega graficos gerados pelo sniffer em uma nova janela. """
        self.sniffer.create_graphs()
        self.graphsglade = "graphs.glade"
        self.graphsxml = gtk.glade.XML(self.graphsglade)
        address = self.graphsxml.get_widget("addressType")
        address.set_from_file('addressType.svg')
        traffic = self.graphsxml.get_widget("trafficClass")
        traffic.set_from_file('trafficClass.svg')
        icmpv6 = self.graphsxml.get_widget("lenNextHeader")
        icmpv6.set_from_file('lenNextHeader.svg')
        nextHeader = self.graphsxml.get_widget("nextHeader")
        nextHeader.set_from_file('nextHeader.svg')

    def set_buttons(self):
        """Ativa ou desativo os botoes de captura e filtro. """
        if self.capturing:
            self.btnIniciar.set_state(gtk.STATE_INSENSITIVE)
            self.btnParar.set_sensitive(True)
            self.btnCarregar.set_state(gtk.STATE_INSENSITIVE)
            self.btnEstatisticas.set_state(gtk.STATE_INSENSITIVE)
            self.btnGraficos.set_state(gtk.STATE_INSENSITIVE)
            self.btnLimparCaptura.set_state(gtk.STATE_INSENSITIVE)
            self.btnFiltrar.set_state(gtk.STATE_INSENSITIVE)
            self.btnLimpar.set_state(gtk.STATE_INSENSITIVE)
        else:
            self.btnIniciar.set_sensitive(True)
            self.btnParar.set_state(gtk.STATE_INSENSITIVE)
            self.btnCarregar.set_sensitive(True)
            self.btnEstatisticas.set_sensitive(True)
            self.btnGraficos.set_sensitive(True)
            self.btnLimparCaptura.set_sensitive(True)
            self.btnFiltrar.set_sensitive(True)
            self.btnLimpar.set_sensitive(True)
예제 #43
0
def main():
    proxyips = Crawler.run()
    logger.info('Crawler finish, total ip: %s', len(proxyips))
    sniffer = Sniffer()
    sniffer.run(proxyips)