def listen(self, sniff_sni=False, sniff_cn=False, sniff_san=False, packet_count: int = None, debug: bool = False) -> Iterator[TLSHandshakeMessage]: # Workaround for pyshark, because SIGINT handling does not work properly original_sigint_handler = signal.getsignal(signal.SIGINT) if original_sigint_handler == signal.default_int_handler: signal.signal(signal.SIGINT, lambda *args: os._exit(0)) try: # Currently only IPv4 is supported for BPF tcp data access. Manpage says: "this will be fixed in the future" for IPv6. # Until then, only the 'tcp' filter is applied # bpf_filter = 'tcp[((tcp[12:1] & 0xf0) >> 2):1] = 22' bpf_filter = 'tcp' display_filter = f'(ssl.record.content_type == 22 && ssl.handshake.type)' if self.bpf_filter != '': bpf_filter += f' && {self.bpf_filter.strip()}' if self.display_filter != '': display_filter += f' && {self.display_filter.strip()}' if packet_count is not None and packet_count <= 0: packet_count = None if self.input_file is not None: packet_iterator = FileCapture( input_file=self.input_file, display_filter=display_filter, keep_packets=False, debug=debug ) elif not sys.stdin.isatty(): packet_iterator = PipeCapture( pipe=sys.stdin.buffer, display_filter=display_filter, debug=debug ) else: capture = LiveCapture( interface=self.interface, bpf_filter=bpf_filter, display_filter=display_filter, debug=debug ) packet_iterator = capture.sniff_continuously() if not (sniff_sni or sniff_cn or sniff_san): sniff_sni = True sniff_cn = True sniff_san = True for packet in packet_iterator: handshake_message = self._get_handshake_message( packet, sniff_sni=sniff_sni, sniff_cn=sniff_cn, sniff_san=sniff_san ) if handshake_message is not None: yield handshake_message if packet_count is not None: packet_count -= 1 if packet_count <= 0: break except Exception: pass # Restore original SIGINT handler signal.signal(signal.SIGINT, original_sigint_handler) return
def get_data(): #interface = "イーサネットのインターフェイス" #cap = LiveCapture(interface="\\Device\\NPF_{7C999537-85AB-4220-B1F9-21D7B6EDA43F}") # itoh cap = LiveCapture( interface="\\Device\\NPF_{70B7AD93-4936-429F-9CD3-481AB236A4C0}" ) # itoh #cap = LiveCapture(interface="\\Device\\NPF_{B4C621AF-E6E9-4870-BA69-291B0CB317C5}") # genta # フィルタ cap._display_filter = "ip.dst == 192.168.11.4 && websocket" #itoh #cap._display_filter = "ip.dst == 192.168.1.4 && websocket" # genta #cap._display_filter = "ip.src == 160.16.234.177 || ip.src == 160.16.100.237 || ip.src == 160.16.123.55 || ip.src == 160.16.146.234 || ip.src == 160.16.102.148 || ip.src == 160.16.235.36 && ip.dst == 192.168.11.4 && websocket" # リアルタイムスニッフィング cap.apply_on_packets(callback, None, None)
def run(self): self.db.drop_collection('packet') self._packet = self.db.packet self._cap = LiveCapture(self.interface, only_summaries=True) count_per_sniff = 30 if self.count < count_per_sniff: count_per_sniff = self.count while self.count > 0: import sys print(self.count, file=sys.stderr) packets = self._cap.sniff_continuously( packet_count=count_per_sniff) self.count -= count_per_sniff self.process_packet(packets)
def start_capture(interface='eth0', packet_count=10): capture = LiveCapture(interface) traffic_list = [] for packet in capture.sniff_continuously(packet_count): try: traffic_list.append({ 'protocol': packet.transport_layer, 'src': packet.ip.src, 'dest': packet.ip.dst }) except Exception: continue remove_duplicates(traffic_list)
def sniff(): print("_________________________________\n") print("Network Sniffer") print("Press CTRL+C at any time to exit\n") time.sleep(0.5) with sqlite3.connect("info.sqlite3") as db: cursor = db.cursor() #This creates a connection to the database try: wireTap = LiveCapture(interface='eth0') for packet in wireTap.sniff_continuously(): if packet.highest_layer == "URLENCODED-FORM": #For html web form getHTTPinfo(packet, cursor, db, str(packet['urlencoded-form'])) print(packet['urlencoded-form']) elif packet.highest_layer == "HTTP": #For get requests try: if packet.http.request_method == "GET": getHTTPinfo(packet, cursor, db) except AttributeError: pass #Not a get request elif packet.highest_layer == "DATA-TEXT-LINES": #For recieving html print("Protocol", packet.http._ws_expert_message) print(packet['DATA-TEXT-LINES']) HTTPdb([ packet.http._ws_expert_message, str(packet['DATA-TEXT-LINES']) ], cursor, db) elif packet.highest_layer == "DNS": try: if packet.dns.resp_name: print("DNS Response from", packet.ip.src, "for", packet.dns.resp_name) DNSdb( [packet.ip.src, "response", packet.dns.resp_name], cursor, db) except AttributeError: print("DNS Request from", packet.ip.src, "for", packet.dns.qry_name) DNSdb([packet.ip.src, "request", packet.dns.qry_name], cursor, db) except (KeyboardInterrupt): db.close() pass
def sniff(): cap = LiveCapture(interface='enp7s0') total_pkts = 0 amount_of_data = 0 for pkt in cap.sniff_continuously(packet_count=n): try: protocol = str(pkt.transport_layer) src_addr = str(pkt.ip.src) dst_addr = str(pkt.ip.dst) src_port = str(pkt[pkt.transport_layer].srcport) dst_port = str(pkt[pkt.transport_layer].dstport) payload_length = int(pkt.data.len) flow = (src_addr, src_port, dst_addr, dst_port) flow_dict[flow] += payload_length src_addr_dict[src_addr] += 1 dst_addr_dict[dst_addr] += 1 except AttributeError: pass
def dashboard(): capture = LiveCapture(interface=app.config['NETWORK_INTERFACE']) capture.sniff(packet_count=1000) packet_protocols = {} packets = [] packet_sizes = [] for packet in capture: try: assert packet.ip packets.append(packet) packet_protocols[packet.highest_layer] = packet_protocols.get( packet.highest_layer, 0) + 1 packet_sizes.append(int(packet.length)) except: pass packet_size_bin = [0, 100, 250, 500, 1000] packet_sizes = np.array(packet_sizes) packet_size_bins = np.array(packet_size_bin) packet_sizes_indexes = np.digitize(packet_sizes, packet_size_bins) packet_size_bin.append('1000+') colors = ["#552586", "#6A359C", "#804FB3", "#9969C7", "#B589D6"] packet_size_counts = {} unique, counts = np.unique(packet_sizes_indexes, return_counts=True) packet_bin_counts = dict(zip(unique, counts)) packet_sizes_final = [] for index, count in enumerate(packet_bin_counts): packet_sizes_final.append({ 'label': f'{packet_size_bin[count-1]}-{packet_size_bin[count]} bytes', 'value': int(packet_bin_counts[count]), 'color': colors[index] }) #print(packet_sizes, packet_sizes_final) min_time = int(packets[0].sniff_timestamp.split('.')[0]) max_time = int(packets[-1].sniff_timestamp.split('.')[0]) + 1 run_time_seconds = max_time - min_time time_based_array = [{ 'count': x, 'value': 0 } for x in range(run_time_seconds)] ip_based_array = [set() for x in range(run_time_seconds)] for packet in packets: try: packet_time = int(packet.sniff_timestamp.split('.')[0]) seconds_delta = packet_time - min_time time_based_array[seconds_delta]['value'] += 1 ip_based_array[seconds_delta].add(packet.ip.dst) except: pass ip_based_array = [{ 'count': x, 'value': len(a) } for x, a in enumerate(ip_based_array)] #print(ip_based_array) #print(time_based_array) protocols = [] for protocol in packet_protocols: protocols.append({ 'protocol': protocol, 'value': packet_protocols[protocol] }) #print(protocols) #print(packet_sizes_final) return render_template('dashboard.html', data=[], protocols=json.dumps(protocols), time_based_array=json.dumps(time_based_array), ip_based_array=json.dumps(ip_based_array), packet_sizes=json.dumps(packet_sizes_final), packets=packets)