def example_capture(): """example_capture An example capture script Change the network interface by ``export CAP_DEVICE=eth0`` """ dev = ev("CAP_DEVICE", "lo") """ Ignore ports for forwarding to consolidators: Redis Internal VM: 6379, 16379 RabbitMQ Internal VM: 5672, 15672, 25672 """ # http://biot.com/capstats/bpf.html custom_filter = ("(udp and portrange 10000-17001) " "or (tcp and portrange 80) " "or arp " "or icmp") log.info(("starting device={} filter={}").format(dev, custom_filter)) kamene.sniff(filter=custom_filter, prn=handle_packets) log.info("done")
def capture_packets(rpis): """ This function uses kamene to sniff packets for our MAC addresses and updates the alarm state when packets are detected. """ logging.getLogger("kamene.runtime").setLevel(logging.ERROR) def update_time(packet): packet_mac = set(rpis.mac_addresses) & set([packet[0].addr2, packet[0].addr3]) packet_mac_str = list(packet_mac)[0] rpis.state.update_last_mac(packet_mac_str) logger.debug('Packet detected from {0}'.format(packet_mac_str)) def calculate_filter(mac_addresses): mac_string = ' or '.join(mac_addresses) filter_text = ( '((wlan addr2 ({0}) or wlan addr3 ({0})) ' 'and type mgt subtype probe-req) ' 'or (wlan addr1 {1} ' 'and wlan addr3 ({0}))' ) return filter_text.format(mac_string, rpis.my_mac_address) while True: logger.info("thread running") try: sniff(iface=rpis.network_interface, store=0, prn=update_time, filter=calculate_filter(rpis.mac_addresses)) except Exception as e: logger.error('kamene failed to sniff packets with error {0}'.format(repr(e))) _thread.interrupt_main()
def capture_tcp_packets_over_telnet(): """capture_tcp_packets_over_telnet Capture ``TCP`` packets over telnet and call the ``handle_packets`` method Change the network interface by ``export CAP_DEVICE=eth0`` """ dev = ev("CAP_DEVICE", "lo") """ Ignore ports for forwarding to consolidators: Redis VM: 6379, 16379 RabbitMQ VM: 5672, 15672, 25672 """ # http://biot.com/capstats/bpf.html default_filter = ("tcp and ( port 23 )") custom_filter = ev("NETWORK_FILTER", default_filter) log.info(("starting device={} filter={}").format(dev, custom_filter)) kamene.sniff(filter=custom_filter, prn=handle_packets) log.info("done")
def run(self): print( f"CaptureThread: starting capture: iface={self.interface}, filter={self.capture_filter}" ) sniff( iface=self.interface, filter=self.capture_filter, timeout=180, prn=self.process_packet, ) print(f"\n\n-----> CaptureThread: competed capture")
from kamene.all import sniff, conf def find_google(pkt): if pkt.haslayer(Raw): payload = pkt.getlayer(Raw).load if 'GET' in payload and 'google' in payload: r = re.findall(r'(?i)&q=(.*?)&', payload) if r: search = r[0].split('&')[0] search = search.replace('q=', '').replace('+', ' ').replace('%20', ' ') print(f'[+] Searched for: {search}') if __name__ == '__main__': parser = argparse.ArgumentParser(usage='python3 google_sniff.py INTERFACE') parser.add_argument('iface', type=str, metavar='INTERFACE', help='specify the interface to listen on') args = parser.parse_args() conf.iface = args.iface try: print('[*] Starting Google Sniffer.') sniff(filter='tcp port 80', prn=find_google) except KeyboardInterrupt: exit(0)
from kamene.all import sniff, conf def fire_catcher(pkt): cookie_table = {} raw = pkt.sprintf('%Raw.load%') r = re.findall(r'wordpress_[0-9a-fA-F]{32}', raw) if r and 'Set' not in raw: if r[0] not in list(cookie_table.keys()): cookie_table[r[0]] = pkt.getlayer(IP).src print('[+] Detected and indexed cookie.') elif cookie_table[r[0]] != pkt.getlayer(IP).src: print(f'[*] Detected Conflict for {r[0]}') print(f'Victim = {cookie_table[r[0]]}') print(f'Attacker = {pkt.getlayer(IP).src}') if __name__ == '__main__': parser = argparse.ArgumentParser(usage='python3 fire_catcher.py INTERFACE') parser.add_argument('iface', type=str, metavar='INTERFACE', help='specify the interface to listen on') args = parser.parse_args() conf.iface = args.iface try: sniff(filter='tcp port 80', prn=fire_catcher) except KeyboardInterrupt: exit(0)
def ret_bt_addr(addr): bt_addr = str(hex(int(addr.replace(':', ''), 16) + 1))[2:] return f'{bt_addr[:2]}:{bt_addr[2:4]}:{bt_addr[4:6]}:{bt_addr[6:8]}' \ f':{bt_addr[8:10]}:{bt_addr[10:12]}' def check_bluetooth(bt_addr): bt_name = lookup_name(bt_addr) if bt_name: print(f'[+] Detected Bluetooth Device: {bt_name}') else: print(f'{"":>3}[-] Failed to Detect Bluetooth Device') def wifi_print(pkt): iphone_oui = 'd0:23:db' if pkt.haslayer(Dot11): wifi_mac = pkt.getlayer(Dot11).addr2 if iphone_oui == wifi_mac[:8]: print(f'[*] Detected iPhone MAC: {wifi_mac}') bt_addr = ret_bt_addr(wifi_mac) print(f'[+] Testing Bluetooth MAC: {bt_addr}') check_bluetooth(bt_addr) if __name__ == '__main__': conf.iface = 'mon0' sniff(prn=wifi_print)
#!/usr/bin/env python # Wireless AP can hide it's BSSID by a blank value in BSSID field # We just need to get all the APs that have blank BSSID # The probe request will contains the SSID name from kamene.all import sniff from kamene.layers.dot11 import Dot11, Dot11ProbeReq, Dot11Beacon def sniff_dot11(pkt): if pkt.haslayer(Dot11ProbeReq): addr2 = pkt.getlayer(Dot11).addr2 if (addr2 in hidden_nets) & (addr2 not in unhidden_nets): net_name = pkt.getlayer(Dot11ProbeReq).info print(f'[+] De-cloaked Hidden SSID: {net_name} for MAC: {addr2}') unhidden_nets.add(addr2) if pkt.haslayer(Dot11Beacon): if pkt.getlayer(Dot11Beacon).info == '': addr2 = pkt.getlayer(Dot11).addr2 if addr2 not in hidden_nets: print(f'[-] Detected Hidden SSID with MAC: {addr2}') hidden_nets.add(addr2) if __name__ == '__main__': hidden_nets = set() unhidden_nets = set() sniff(iface='mon0', prn=sniff_dot11)
from kamene.all import sniff, conf from kamene.layers.dot11 import Dot11Beacon, Dot11ProbeReq from kamene.layers.inet import TCP from kamene.layers.dns import DNS def pkt_print(pkt): if pkt.haslayer(Dot11Beacon): print('[+] Detected 802.11 Beacon Frame') elif pkt.haslayer(Dot11ProbeReq): print('[+] Detected 802.11 Probe Request Frame') elif pkt.haslayer(TCP): print('[+] Detected a TCP Packet') elif pkt.haslayer(DNS): print('[+] Detected a DNS Packet') if __name__ == '__main__': conf.iface = 'mon0' sniff(prn=pkt_print)
def run(self): sniff(prn=self.intercept_pkt, filter='udp port 5556')
def ftp_sniff(pkt): dest = pkt.getlayer(IP).dst raw = pkt.sprintf('%Raw.load%') user = re.findall(r'(?i)USER (.*)', raw) passwd = re.findall(r'(?i)PASS (.*)', raw) if user: print(f'[*] Detected FTP Login to {str(dest)}') print(f'[+] User account: {str(user[0])}') if passwd: print(f'[*] Detected FTP Login to {str(dest)}') print(f'[+] Password: {str(passwd[0])}') if __name__ == '__main__': parser = argparse.ArgumentParser(usage='python3 ftp_sniff.py INTERFACE') parser.add_argument('iface', type=str, metavar='INTERFACE', help='specify the interface to listen on') args = parser.parse_args() conf.iface = args.iface try: sniff(filter='tcp port 21', prn=ftp_sniff) except KeyboardInterrupt: exit(0)
if abs(int(ttl) - int(ttl_values[ipsrc])) > THRESH: print(f'\n[!] Detected Possible Spoofed Packet From: {ipsrc}') print(f'[!] TTL: {ttl}, Actual TTL: {str(ttl_values[ipsrc])}') def test_TTL(pkt): try: if pkt.haslayer(IP): ipsrc = pkt.getlayer(IP).src ttl = str(pkt.ttl) check_TTL(ipsrc, ttl) except Exception as e: print(f'{"":>3}[-] Exception: {e.__class__.__name__}') pass if __name__ == '__main__': parser = argparse.ArgumentParser( usage='python3 spoof_detect.py [-i INTERFACE] [-t THRESHOLD]') parser.add_argument('-i', type=str, metavar='INTERFACE', default='eth0', help='specify the network interface') parser.add_argument('-t', type=int, metavar='THRESHOLD', default=5, help='specify the threshold count') args = parser.parse_args() conf.iface = args.i THRESH = args.t sniff(prn=test_TTL, store=0)
def find_credit_card(pkt): raw = pkt.sprintf('%Raw.load%') america_re = re.findall(r'3[47][0-9]{13}', raw) master_re = re.findall(r'5[1-5][0-9]{14}', raw) visa_re = re.findall(r'4[0-9]{12}(?:[0-9]{3})?', raw) if america_re: print(f'[+] Found American Express Card: {america_re[0]}') if master_re: print(f'[+] Found Master Card: {visa_re[0]}') if visa_re: print(f'[+] Found Visa Card: {visa_re[0]}') if __name__ == '__main__': parser = argparse.ArgumentParser(usage='python3 credit_sniff.py INTERFACE') parser.add_argument('iface', type=str, metavar='INTERFACE', help='specify the interface to listen on') args = parser.parse_args() conf.iface = args.iface try: print('[*] Starting Credit Card Sniffer.') sniff(filter='tcp', prn=find_credit_card, store=0) except KeyboardInterrupt: exit
#!/usr/bin/env python # Wireless devices usually probe for networks that it has # successfully connected before. from kamene.all import sniff from kamene.layers.dot11 import Dot11ProbeReq def sniff_probe(pkt): if pkt.haslayer(Dot11ProbeReq): net_name = pkt.getlayer(Dot11ProbeReq).info if net_name not in probe_reqs: probe_reqs.add(net_name) print(f'[+] Detected New Probe Request: {net_name}') if __name__ == '__main__': probe_reqs = set() sniff(iface='mon0', prn=sniff_probe)
nonlocal payload, last_ack if pkt[IP].ack == last_ack: payload = payload + pkt[Raw].load.decode('utf-8', 'ignore') else: payload = pkt[Raw].load.decode('utf-8', 'ignore') last_ack = pkt[IP].ack # find request url and log it if found url = find_url_from_headers( extract_headers_from_request_payload(payload)) if url: log(url) writeLog(url) return parse_http_request if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() # get args from cli parser.add_argument('--iface', default='en0', type=str) parser.add_argument('--port', default=80, type=int) args = parser.parse_args() log('sniffing http requests on port {port} using network interface {iface}' .format(port=args.port, iface=args.iface)) sniff( prn=http_parser(), iface=args.iface, filter='tcp and port {port}'.format(port=args.port), )
import re import argparse from kamene.all import sniff, conf def find_guest(pkt): raw = pkt.sprintf('%Raw.load%') name = re.findall('(?i)LAST_NAME=(.*)&', raw) room = re.findall("(?i)ROOM_NUMBER=(.*)'", raw) if name: print(f'[+] Found Hotel Guest {str(name[0])}, Room # {str(room[0])}') if __name__ == '__main__': parser = argparse.ArgumentParser(usage='python3 hotel_sniff.py INTERFACE') parser.add_argument('iface', type=str, metavar='INTERFACE', help='specify the interface to listen on') args = parser.parse_args() conf.iface = args.iface try: print('[*] Starting Hotel Guest Sniffer.') sniff(filter='tcp', prn=find_guest, store=0) except KeyboardInterrupt: exit(0)