def inter_packet_correcto(): test_pass = False sn = Sniffer() sn.inter() test_pass = (self.count == 1)
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()
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)
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)
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
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)
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)
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())
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
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]
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)
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. # # A: Waiting for more data. # R: Timeout / Expiry. # data = "6" * 1280 ip6f01 = sp.Ether() / \ sp.IPv6(src=args.src[0], dst=args.to[0]) / \ sp.IPv6ExtHdrFragment(offset=0, m=1, id=3) / \ sp.UDP(dport=3456, sport=6543) / \ data if args.debug: ip6f01.display() sp.sendp(ip6f01, iface=args.sendif[0], verbose=False) # Wait for ICMPv6 error generation on timeout. sleep(75) sniffer.setEnd() sniffer.join() if not sniffer.foundCorrectPacket: sys.exit(1) sys.exit(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()
def test_se_detectan_interfaces(): test_pass = False sn = Sniffer() res = [] res = sn.detect_ifaces() if res: test_pass = True assert test_pass
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)
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."
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()
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()
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) ######################################################################## # # Atomic fragment. # # A: Nothing listening on UDP port. # R: ICMPv6 dst unreach, unreach port. # ip6f01 = sp.Ether() / \ sp.IPv6(src=args.src[0], dst=args.to[0]) / \ sp.IPv6ExtHdrFragment(offset=0, m=0, id=3) / \ sp.UDP(dport=3456, sport=6543) if args.debug: ip6f01.display() sp.sendp(ip6f01, iface=args.sendif[0], verbose=False) sleep(0.10) sniffer.setEnd() sniffer.join() if not sniffer.foundCorrectPacket: sys.exit(1) sys.exit(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()
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.setEnd() sniffer.join() if not sniffer.foundCorrectPacket: sys.exit(1) sys.exit(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()
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)
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
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"
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)
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)
def start(): ''' Take the victim's IP, the hostname of the endpoint that is being attacked, the device interface and the source port of the endpoint and set a sniffer on all TLS connections between them. Arguments: source_ip -- the local network IP of the victim, e.g. 192.168.1.66 destination_host -- the hostname of the attacked endpoint, e.g. dimkarakostas.com interface -- the device interface to use sniff on, e.g. wlan0 destination_port -- the port of the endpoint e.g. 443 Status code for the request: 409: a sniffer on the same source_ip and destination host already exists 400: parameters were not properly set 201: a new sniffer for those arguments has been created ''' data = request.get_json() source_ip = data['source_ip'] destination_host = data['destination_host'] interface = data['interface'] destination_port = data['destination_port'] # Check if a same sniffer already exists if (source_ip, destination_host) in sniffers: err = '409 - Sniffer (source_ip: {}, destination_host: {}) already exists.'.format( source_ip, destination_host) logger.warning(err) return str(err), 409 params = { 'source_ip': source_ip, 'destination_host': destination_host, 'interface': interface, 'destination_port': destination_port } # Check if parameters are invalid try: sniffer = Sniffer(params) except ValueError, err: logger.warning(err) return str(err), 400
def __createSniffer(self, name, target, outputFile): """Creates a sniffer between 'name' and 'target'. Information its shown in standard output and specified 'outputFile.'""" # print("{Sniffer} %s <-> %s [Output '%s']" % # (name, target, outputFile)) f = open(outputFile, 'w') self.snifferFiles.append(f) # 'pair' receives one of the two lists for pair in [[name, target], [target, name]]: # Here, 'pair' is a list with two values sniffer = Sniffer(pair[0], pair[1], f, self.startTime) checkRouter = self.__isRouter(pair[0]) if checkRouter is not None: router = self.routers[checkRouter[0]] router.setSniffer(int(checkRouter[1]), sniffer) else: host = self.hosts[pair[0]] host.setSniffer(sniffer)
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)