Пример #1
0
def parsePcapFile(pcapFileName, pcapIndex):
    # open the pcap file for reading
    pcap_file_f = open(path + "/" + pcapFileName)
    capfile = savefile.load_savefile(pcap_file_f, verbose=True)

    for pkt in capfile.packets:
        eth_frame = ethernet.Ethernet(pkt.raw())
        eth_type = eth_frame.type
        if (eth_type == 2048):
            ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
            # foundIPs[pcapFileName][ip_packet.dst] = ip_packet.dst	# push ip into table
            foundIPs[pcapIndex][ip_packet.dst] = 1  # push ip into table
    pcap_file_f.close()  # close file descriptor
Пример #2
0
def index(request):
                answer = []
                for packet in capfile.packets:
                    try:
                        udp_packet = None
                        ptype = " "
                        mac_packet = ethernet.Ethernet(packet.raw());
                        if mac_packet.type == 2048:
                            ip_packet = ip.IP(binascii.unhexlify(ethernet.Ethernet(packet.raw()).payload))
                            ptype = "IPv4"
                            if ip_packet.p == 17:
                                udp_packet = udp.UDP(binascii.unhexlify(ethernet.Ethernet(packet.raw()).payload))
                                ptype = "UDP"
                        else:
                                ptype = "unknown"
                        answer.extend([

                             str(packet.timestamp),   #timestamp
                             str(mac_packet.src),   #Sender Mac Address
                             str(mac_packet.dst),   #Receiver Mac Address
                             str(ip_packet.src),    #Sender IP
                             str(ip_packet.dst),    #Receiver IP
                             str(ip_packet.len)+ " " +"byte",    #Payload lenght with IP header
                           #  str(ip_packet),        #Print whole packet information

                             str(mac_packet.type),  #Protocol Type


                             str(len(capfile.packets)) + " " + "Packets",  # Lenght of Pcacp file
                             str(ptype),
                            ])

                        if udp_packet is not None:
                            answer.extend([
                                str(udp_packet.dst_port),
                                str(udp_packet.src_port)
                            ])
                        else:
                            answer.extend([
                                str(ptype)   #add port details of TCP packets
                            ])

                        answer.append("")

                    except:
                        import traceback
                        traceback.print_exc()

                return HttpResponse("<br>" . join(answer))
Пример #3
0
def my_pcap_reader(filename):
    testcap = open('../Samples/' + filename + ".pcap", 'rb')
    capfile = savefile.load_savefile(testcap, verbose=True)
    f = open('Results/Traces/' + filename + ".txt", 'w')

    # eth_frame = ethernet.Ethernet(capfile.packets[0].raw())
    # print eth_frame

    # ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
    # print ip_packet

    for i in range(len(capfile.packets)):
        eth_frame = ethernet.Ethernet(capfile.packets[i].raw())
        try:
            ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
        except Exception as e:
            print e.message
            continue

        packet = capfile.packets[i]

        packet_type = ""
        if ip_packet.p == 6:
            packet_type = "TCP"
        elif ip_packet.p == 17:
            packet_type = "UDP"
        else:
            packet_type = "Unknown_type"

        milisecond = str(packet.timestamp_ms)
        while len(milisecond) < 6:
            milisecond = "0" + milisecond
        t1 = float(str(packet.timestamp % 100000) + "." + milisecond)
        t2 = float(
            str(capfile.packets[0].timestamp % 100000) + "." +
            str(capfile.packets[0].timestamp_ms))
        t3 = t1 - t2
        t3 = "{0:.6f}".format(t3)

        row = str(i + 1) + " " + str(
            t3
        ) + " " + ip_packet.src + " " + ip_packet.dst + " " + packet_type + " " + str(
            packet.packet_len)
        print(row)
        f.write(row + "\n")
        print("------------------------------------------------")
    f.close()
Пример #4
0
    def generate_graph(self, filename):
        # Open the .pcap file
        capture = open(filename, "rb")
        self.packets = savefile.load_savefile(capture, verbose=True).packets

        # Process the packets and generate the adjacency list based on the graph
        for p in self.packets:
            try:
                eth_frame = ethernet.Ethernet(p.raw())
                ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
                source = ip_packet.src
                destination = ip_packet.dst
                packet_length = ip_packet.len
                protocol = constants.PROTOCOLS[ip_packet.p]

                #if source not in _infected_ips and source not in _normal_ips:
                #    u = ("WAN", protocol)
                #else:
                infected = True if source in _infected_ips else False
                u = (source, protocol, infected)

                #if destination not in _infected_ips and destination not in _normal_ips:
                #    v = ("WAN", protocol)
                #else:
                infected = True if destination in _infected_ips else False
                v = (destination, protocol, infected)

                if self.graph.has_edge(u, v):
                    self.graph[u][v]['weight'] += packet_length
                else:
                    self.graph.add_edge(u, v, weight=packet_length)

                self.statistics["total_packets"] += 1
                self.statistics["largest_packet"] = max(
                    packet_length, self.statistics["largest_packet"])

                if settings.VERBOSE:
                    if self.statistics["total_packets"] % 50000 == 0:
                        print("Processed " +
                              str(self.statistics["total_packets"]) +
                              " packets")

            except Exception, e:
                self.statistics["non_ip_packets"] += 1
Пример #5
0
def get_all_flows(capdata):
    #input capdata
    flows = []
    timestamps = []
    for pkt in capdata.packets:
        eth_frame = ethernet.Ethernet(pkt.raw())
        try:
            ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
            tcp_packet = tcp.TCP(binascii.unhexlify(eth_frame.payload))
        except:
            continue
        flows.append([
            ip_packet.src.decode("utf-8"),
            ip_packet.dst.decode("utf-8"),
            str(tcp_packet.src_port),
            str(tcp_packet.dst_port),
            str(ip_packet.p)
        ])
        timestamps.append(normalized_timestamp(pkt.timestamp))
    return np.unique(flows, axis=0), flows, timestamps
Пример #6
0
def get_all_flows_2(cap, attackers, write_to_file):
    #input file object and a file to write the flows in formation
    flow_file = open(write_to_file, 'a')
    flows = []
    timestamps = []
    for pkt in savefile.load_savefile(cap, lazy=True).packets:
        eth_frame = ethernet.Ethernet(pkt.raw())
        try:
            ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
            tcp_packet = tcp.TCP(binascii.unhexlify(eth_frame.payload))
        except:
            continue
        if ip_packet.src.decode("utf-8") in attackers:
            flow_file.write('{},{},{},{},{},{}\n'.format(
                ip_packet.src.decode("utf-8"), ip_packet.dst.decode("utf-8"),
                str(tcp_packet.src_port), str(tcp_packet.dst_port),
                str(ip_packet.p), normalized_timestamp(pkt.timestamp)))
        else:
            continue
    flow_file.close()
Пример #7
0
    def run(self):

        for time, buf in pcap.pcap(promisc=True, immediate=True):

            eth_frame = ethernet.Ethernet(buf)
            try:
                ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
            except AssertionError:
                continue  # ignore this packet

            self.queue.put({
                #'vhl': ip_packet.vhl,
                'tos': ip_packet.tos,
                'len': ip_packet.len,
                'id': ip_packet.id,
                'off': ip_packet.off,
                'ttl': ip_packet.ttl,
                'p': ip_packet.p,
                'sum': ip_packet.sum,
                'src': ip_packet.src,
                'dst': ip_packet.dst
            })
Пример #8
0
def main(args):
    for file in get_pcaps_list(args.input):
        with open(file, 'rb') as file:
            sf = savefile.load_savefile(file)
            for packet in sf.packets:
                eth_frame = ethernet.Ethernet(packet.raw())
                ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
                ip_addr = ip_packet.src.decode("utf-8")
                if args.e:
                    if ip_addr not in args.e:
                        add_packet(ip_addr, ip_packet)
        # print(results.items())
        newlist = sorted(results.values(),
                         key=lambda x: x.total_packets,
                         reverse=True)
    if args.l:
        if len(newlist) > int(args.l):
            print_list(newlist[:int(args.l)])
        else:
            print_list(newlist)
    else:
        print_list(newlist)
Пример #9
0
    print("No packets")
    exit(1)

def ts(pkt):
    return pkt.timestamp + pkt.timestamp_ms/1000

first_packet = capfile.packets[0]
first_timestamp = ts(first_packet)

for p in capfile.packets:
    eth_frame = ethernet.Ethernet(p.raw())
    tcp_packet = tcp.TCP(binascii.unhexlify(eth_frame.payload))
    if tcp_packet.seqnum in seqnums:
        continue
    seqnums.add(tcp_packet.seqnum)
    ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
    final_timestamp = ts(p) - first_timestamp
    if (ip_packet.len < 1500):
        packet_lengths[ip_packet.len] = 1
    if (ip_packet.dst == bridge):
        print("{:f}\t{}".format(final_timestamp, 1))
        packet_directions.append(1)
        outgoing_packets += 1
        x_out.append(p.timestamp_ms)
        y_out.append(ip_packet.len)
        outgoing_total_bytes += ip_packet.len
    else:
        print("{:f}\t{}".format(final_timestamp, -1))
        packet_directions.append(-1)
        incoming_packets += 1
        x_in.append(p.timestamp_ms)
Пример #10
0
from pcapfile import savefile
from pcapfile.protocols.linklayer import ethernet
from pcapfile.protocols.network import ip
import binascii
import sys

in_pcap = input ("Enter the file name/path ::")
test_pcap = open(in_pcap,'rb')
capfile = savefile.load_savefile(test_pcap, verbose = True)

#Now capfile file will be traeted as the normal file input for python
# Store data in normal decoded format  
# 2019-12-25-traffic-analysis-exercise.pcap  File to refer 

#(ip.IP(binascii.unhexlify(ethernet.Ethernet (capfile.packets[0].raw()).payload))) This is a payload for raw file 

data = []
for i in range (len(capfile.packets)):
    data.append((ip.IP(binascii.unhexlify(ethernet.Ethernet (capfile.packets[i].raw()).payload))))
    
#Now lets create new file with all logs as strigs 

print ("="*23)
with open('out.txt', 'w') as f:
    for i in range (len(data)):
        print (data[i], file=f)
print ("out.txt is created")
print ("="*23)


Пример #11
0
def get_IP_packet(eth_frame):
    #print('[DEBUG] Starting get_ethernet_frame() method')
    ip_packet = ip.IP(binascii.unhexlify(eth_frame.payload))
    #print('[DEBUG] Returning ethernet frame')
    return ip_packet
Пример #12
0
def parse(packet) -> (ethernet.Ethernet, ip.IP, tcp.TCP):
    eth_frame: ethernet.Ethernet = ethernet.Ethernet(packet.raw())
    ip_packet: ip.IP = ip.IP(binascii.unhexlify(eth_frame.payload))
    tcp_pkt: tcp.TCP = tcp.TCP(binascii.unhexlify(ip_packet.payload))
    return eth_frame, ip_packet, tcp_pkt
Пример #13
0
# File parsing
file = HA0.parse_file("nazir.txt")   
[_nazir_ip, _mix_ip, _num_partners, filename] = list(map(lambda x: x.split(": ")[1], file)) 


nazir = ip_to_int("b'"+_nazir_ip+"'")
mix = ip_to_int("b'"+_mix_ip+"'")  
num_partners = int(_num_partners)
testcap = open(filename, 'rb')
capfile = savefile.load_savefile(testcap, verbose = True)

# Create a list of (sender, reciever) as integer for all packets
adresses = []
for i in range(0, len(capfile.packets)):
    eth_frame = ethernet.Ethernet(capfile.packets[i].raw())
    ip_packet = ip.IP(HA0.hex_to_bytes(str(eth_frame.payload)[2:-1]))
    adresses.append((ip_to_int(ip_packet.src), ip_to_int(ip_packet.dst)))


sets = []
disjoint = []
senders = set({})
recievers = set({})
last_source = -1
# Discovery phase
for t in adresses:
    (src, dst) = t
    if mix == dst and mix == last_source:
        if nazir in senders:
            if (is_disjoint_all(recievers, disjoint)):
                disjoint.append(recievers)