Esempio n. 1
0
def merge_cap_files(pcap_file_list, out_filename, delete_src=False):

    out_pkts = []
    if not all([os.path.exists(f) for f in pcap_file_list]):
        print "failed to merge cap file list...\nnot all files exist\n"
        return

    # read all packets to a list
    for src in pcap_file_list:
        f = open(src, 'r')
        reader = pcap.Reader(f)
        pkts = reader.readpkts()
        out_pkts += pkts
        f.close()
        if delete_src:
            os.unlink(src)

    # sort by the timestamp
    out_pkts = sorted(out_pkts, key=itemgetter(0))

    out = open(out_filename, 'w')
    out_writer = pcap.Writer(out)

    for ts, pkt in out_pkts:
        out_writer.writepkt(pkt, ts)

    out.close()
Esempio n. 2
0
    def execute(self):
        capture = open(self.inputFile)
        output = open(self.outputFile, "w")
        reader = PppPacketReader(capture)
        writer = pcap.Writer(output)
        state = PppStateManager(self.nthash)
        count = 0

        for packet in reader:
            decryptedPacket = state.addPacket(packet)

            if decryptedPacket:
                writer.writepkt(decryptedPacket)
                count += 1

        print "Wrote %d packets." % count
Esempio n. 3
0
    def create(self, path=None):
        """
        Initialize App
        """
        # pylint: disable=attribute-defined-outside-init

        if path:
            try:
                self.pcap = pcap.Writer(open(path, "wb"))
                _LOG.info("Pcap Start. %s", path)

            except OSError as ex:
                _LOG.exception(ex)

        else:
            self.pcap = None
            _LOG.info("Pcap diabled.")
Esempio n. 4
0
class ether_hdr(ctypes.Structure):
    _fields_ = [('h_dest',ctypes.c_ubyte*6),
    ('h_source',ctypes.c_ubyte*6),
    ('h_proto',ctypes.c_ushort)]

pfd = select.poll()
READ_ONLY = select.POLLIN | select.POLLERR
pfd.register(sock,READ_ONLY)
i = 0

# bdesc = block_desc.from_buffer_copy(mm)
TP_STATUS_USER = 1 << 0 
TP_STATUS_KERNEL = 0
fpcap = open("./tmp.pcap",'wb')
fwrite = dpcap.Writer(fpcap)

def display(bdesc:object,length:int):
    pkt_nums = bdesc.num_pkts
    tmp = bdesc.offset_to_first_pkt + length
    th3 = tpacket3_hdr.from_buffer(mm,tmp)
    for i in range(pkt_nums):
        eth = ether_hdr.from_buffer(mm,tmp+th3.tp_mac)
        one = socket.ntohs(eth.h_proto)
        print(eth.h_dest[0],eth.h_dest[1],eth.h_dest[2],eth.h_dest[3],eth.h_dest[4],eth.h_dest[5])
        print(eth.h_source[0],eth.h_source[1],eth.h_source[2],eth.h_source[3],eth.h_source[4],eth.h_source[5])
        pkt_tmp = mm[tmp+th3.tp_mac:tmp+th3.tp_mac+th3.tp_snaplen]
        fwrite.writepkt(pkt_tmp)
        print(one,0x0800)
        tmp = tmp + th3.tp_next_offset
        th3 = tpacket3_hdr.from_buffer(mm,tmp)
    def _filter_pcap(self, output_pcap):
        """Using a provided file with XML flow summaries, create a
        new PCAP file with the flows in the XML file.

        :param output_pcap: Path for the new PCAP file.
        """
        try:
            print("Opening file: {0}".format(self._pcap))
            f = open(self._pcap)
            raw_pcap = pcap.Reader(f)
            pckt_num = 0
            for ts, buf in raw_pcap:
                pckt_num += 1
                if not pckt_num % 1000:
                    # Print every thousandth packets, just to monitor
                    # progress.
                    print("\tProcessing packet #{0}".format(pckt_num))
                # Loop through packets in PCAP file
                eth = ethernet.Ethernet(buf)
                if eth.type != ETH_TYPE_IP:
                    # We are only interested in IP packets
                    continue
                ip = eth.data
                ip_src = socket.inet_ntop(socket.AF_INET, ip.src)
                ip_dst = socket.inet_ntop(socket.AF_INET, ip.dst)
                ip_proto = ip.p
                match = False
                for flow in self._raw_data:
                    # Does this packet match a flow in the raw data?
                    if ((ip_src == flow["source"]
                         and ip_dst == flow["destination"])
                            or (ip_src == flow["destination"]
                                and ip_dst == flow["source"])):
                        if ip_proto == IP_PROTO_TCP and flow[
                                "protocolName"] == "tcp_ip":
                            tcp = ip.data
                            if self._check_port_num(tcp.sport, tcp.dport,
                                                    flow["sourcePort"],
                                                    flow["destinationPort"]):
                                if self._check_timestamp(
                                        ts, flow["startDateTime"],
                                        flow["stopDateTime"]):
                                    # We have found a match, stop looping
                                    match = True
                                    break
                        elif ip_proto == IP_PROTO_UDP and flow[
                                "protocolName"] == "udp_ip":
                            udp = ip.data
                            if self._check_port_num(udp.sport, udp.dport,
                                                    flow["sourcePort"],
                                                    flow["destinationPort"]):
                                if self._check_timestamp(
                                        ts, flow["startDateTime"],
                                        flow["stopDateTime"]):
                                    # We have found a match, stop looping
                                    match = True
                                    break
                        elif ip_proto == IP_PROTO_ICMP and flow[
                                "protocolName"] == "icmp_ip":
                            if self._check_timestamp(ts, flow["startDateTime"],
                                                     flow["stopDateTime"]):
                                # We have found a match, stop looping
                                break
                                match = True
                        elif ip_proto == IP_PROTO_IGMP and flow[
                                "protocolName"] == "igmp":
                            if self._check_timestamp(ts, flow["startDateTime"],
                                                     flow["stopDateTime"]):
                                # We have found a match, stop looping
                                match = True
                                break
                if match:
                    # The packet matches the flow. Append the packet data
                    # to the new PCAP file and move onto the next packet.
                    try:
                        print(
                            "\tWrting packet to file: {0}".format(output_pcap))
                        f_out = open(output_pcap, "ab")
                        pcap_out = pcap.Writer(f_out)
                        pcap_out.writepkt(buf, ts=ts)
                    except:
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        print("ERROR writing to file: {0}.\n\t"
                              "Exception: {1}, {2}, {3}".format(
                                  output_pcap, exc_type, exc_value,
                                  exc_traceback))
                        sys.exit(1)
                    finally:
                        f_out.close
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            print("ERROR reading from file: {0}.\n\tException: {1}, "
                  "{2}, {3}".format(self._pcap, exc_type, exc_value,
                                    exc_traceback))
            sys.exit(1)
        finally:
            f.close()