Exemplo n.º 1
0
def get_packets_from_capture(capture):

    packets = list()
    for packet in capture:
        packet_dict = to_dict(packet, strict=True)
        if "Raw" in packet_dict:
            del packet_dict["Raw"]
        packet_dict["hexdump"] = scapy.hexdump(packet, dump=True)
        packet_dict_no_bytes = bytes_to_string(packet_dict)
        packets.append(packet_dict_no_bytes)

        pprint(packet_dict_no_bytes)

    return packets
Exemplo n.º 2
0
    def process_packet(self, packet):

        print(f"CaptureThread: processing packet: {packet}")
        packet_dict = to_dict(packet, strict=True)
        if "Raw" in packet_dict:
            del packet_dict["Raw"]
        packet_dict["hexdump"] = hexdump(packet, dump=True)
        packet_dict_no_bytes = bytes_to_string(packet_dict)

        pprint(packet_dict_no_bytes)

        print(f"CaptureThread: sending capture: {packet_dict_no_bytes}")
        status_code = send_capture(gethostname(), self.destination,
                                   str(datetime.now())[:-1],
                                   [packet_dict_no_bytes], self.snoop)
        print(f"CaptureThread: capture sent, result={status_code}\n")
Exemplo n.º 3
0
def info():
    """return network information including interfaces, ..."""

    try:
        packet_list = rdpcap('example.pcap')
        packets = [dict(scapy2dict.to_dict(packet)) for packet in packet_list][:2]

        return jsonpickle.encode({
            'ok': True,
            'interfaces': [iface[1] for iface in socket.if_nameindex()]
        })

    except error as Exception:
        return jsonpickle.encode({
            'ok': False,
            'error': error
        })
Exemplo n.º 4
0
def analyse():
    """analyse a pcap file and returns the a list of analysed packets"""

    # pcap_file = request.files["pcap_file"]

    try:
        packet_list = rdpcap('example.pcap')
        packets = [dict(scapy2dict.to_dict(packet)) for packet in packet_list][:2]

        return jsonpickle.encode({
            'ok': True,
            'data': packets
        })

    except error as Exception:
        return jsonpickle.encode({
            'ok': False,
            'error': error
        })
Exemplo n.º 5
0
def custom_action(packet):
    data = {
        'InterfaceLayer': "None",
        'InternetLayer': "None",
        'TransportLayer': "None",
        'ApplicationLayer': "None"
    }

    d = to_dict(packet, strict=False)
    #dunno why but need to iterate over d.maps which is a [], otherwise the order is f****d up
    ip = d["IP"]["src"]
    time = datetime.now()
    user_agent = None
    try:
        if ip not in unique_ips:
            unique_ips.append(ip)
    except:
        None

    if "Raw" in d and d["Raw"]["load"].startswith(b"GET"):
        try:
            headers = parse_it(d["Raw"]["load"])
            user_agent = headers.user_agent
        except:
            print("Exception!!!!!")

    for layer, key in zip(d.maps, data):
        x = next(iter(layer.items()))  #tuple
        data[key] = str(x[0]) + " " + str(x[1])

    client.execute(f'INSERT INTO {db_name}.{data_table} VALUES', [data])
    if user_agent:
        client.execute(f'INSERT INTO {db_name}.{metrics_table} VALUES',
                       [{
                           "Time": str(time),
                           "Ip": ip,
                           "UserAgent": str(user_agent)
                       }])
    print(f"Unique IP addresses: {unique_ips}, packets: {next(counter) + 1}",
          end='\r')
    return None
Exemplo n.º 6
0
    def process_packets(self, packet):
        """process and analyse receiving packet and send the result over socket to all clients"""

        packet = dict(scapy2dict.to_dict(packet))

        # TODO : fix the try-except statements
        try:
            del packet['IP']['options']
        except:
            pass

        try:
            del packet['TCP']['options']
        except:
            pass

        from random import randint
        if randint(1, 100) == 100:
            print(packet)
            socketio.emit('new_packet', " {'packet': packet}", broadcast=True)
            socketio.send(" {'packet': packet}", broadcast=True)
Exemplo n.º 7
0
def main():

    # Read pcap file
    in_file = argv[1]
    if not os.path.isfile(in_file):
        raise Exception("file_name is not there")

    packets = rdpcap(in_file)

    dataset = len(packets)
    res = np.empty((1, dataset), dtype=object)

    # Iterate over packets
    for idx, pkt in enumerate(packets):
        data = dict(to_dict(pkt))
        clearedData = remove_none(data)
        clearedData.update({"time": pkt.time})
        npRes = np.array(clearedData)
        res[0, idx] = npRes

    # Output to file
    out_file = os.path.splitext(in_file)[0]
    print('Writing to ' + out_file + '.mat')
    scipy.io.savemat(out_file, {"res": res})
Exemplo n.º 8
0
def process_packets(packet):
        """process and analyse receiving packet and stores the result"""

        globals()['last_packet'] = dict(scapy2dict.to_dict(packet))
Exemplo n.º 9
0
def frameToDict(frame):
    data = to_dict(frame)
    # pprint(data)
    return data