Ejemplo n.º 1
0
    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
Ejemplo n.º 2
0
def monitor_wifi(capture: pyshark.LiveCapture, dictionary):
    capture.sniff(packet_count=1)
    for packet in capture.sniff_continuously():
        address = packet.layers[2].ta_resolved
        signal_strength = int(packet.radiotap.dbm_antsignal)
        frequency = int(packet.radiotap.channel_freq)

        if address in dictionary.keys():
            dictionary[address].update_strength(signal_strength)

            if len(
                    np.where(
                        np.asarray(dictionary[address].distance) > MAX_DIST)
            ) > 2:
                del dictionary[address]

        else:
            device = Device(signal_strength=signal_strength,
                            frequency=frequency,
                            address=address)

            if not device.distance[-1] > MAX_DIST:
                dictionary[address] = device
                print(f'NEW DEVICE WITHIN RANGE: ADDRESS:       {address}')
                print(
                    f'                         DISTANCE:      {device.distance[-1]}'
                )
                print(
                    f'                         DISTANCES:     {device.distance}'
                )

        keys_to_del = []
        for k, v in dictionary.items():
            since_last_seen = time.time() - v.time_last_seen
            if since_last_seen > TIME_OUT:
                print(
                    f'Device {k} was last seen {since_last_seen} s ago, REMOVING FROM LIST'
                )
                keys_to_del.append(k)

        for k in keys_to_del:
            del dictionary[k]

        num_devices = len(dictionary.keys())

        print(f'TOTAL NUMBER OF DEVICES WITHIN RANGE:   {num_devices}')

        if num_devices == 0:
            adjust_light(devices_within_range, 0, MAX_DIST, lamp, intensity=0)
        else:
            adjust_light(devices_within_range,
                         min=0,
                         max=MAX_DIST,
                         arduino=lamp)
Ejemplo n.º 3
0
 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)
Ejemplo n.º 4
0
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 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)
Ejemplo n.º 6
0
def gen_arp_communications_matrix(data: LiveCapture):
    arp_communications_matrix = {}

    while True:
        try:
            pkt = data.next_packet()

            pkt_key = pkt.arp.src_proto_ipv4 + "." + pkt.arp.dst_proto_ipv4
            if pkt_key in arp_communications_matrix:
                old_rec = arp_communications_matrix[pkt_key]
                arp_communications_matrix[pkt_key] = (old_rec[0], old_rec[1],
                                                      old_rec[2] + 1,
                                                      int(old_rec[3]) +
                                                      int(pkt.length))
            else:
                arp_communications_matrix[pkt_key] = (pkt.arp.src_proto_ipv4,
                                                      pkt.arp.dst_proto_ipv4,
                                                      1, pkt.length)

        except StopIteration:
            break

    def get_key(p):
        return p[2]

    return sorted(arp_communications_matrix.values(),
                  key=get_key,
                  reverse=True)
Ejemplo n.º 7
0
class Monitor(threading.Thread):
    def __init__(self, interface, count):
        super(Monitor, self).__init__()
        self.interface = interface
        self.count = count
        self.client = MongoClient()
        self.db = self.client.ids
        self._packet = self.db.packet
        self.packet_id = 0

    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 process_packet(self, packets):
        temp = []
        for packet in packets:
            # print(packet)
            item = {
                "id": self.packet_id,
                "src": packet.source,
                "dst": packet.destination,
                "time": packet.time,
                "protocol": packet.protocol,
                "info": packet.info,
                "length": packet.length
            }
            self.packet_id += 1
            temp.append(item)
        self._packet.insert(temp)

    def __del__(self):
        self._cap.clear()
        self._cap.close()
        self.client.close()
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
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)