示例#1
0
文件: defrag.py 项目: zerkms/ipfrag
def main():
    parser = argparse.ArgumentParser(
        description='Defragments the IPv4 packets in the given PCAP file '
        'and writes the results to another file.')
    parser.add_argument('input_file')
    parser.add_argument('output_file')

    args = parser.parse_args()

    fragments = []
    reader = RawPcapReader(args.input_file)
    writer = PcapWriter(args.output_file, append=False, sync=True)
    for pkt_data in reader:
        p = Ether(pkt_data[0])
        if not isinstance(p[1], IP):
            writer.write(p)
            continue

        if p[IP].flags & 1 == 0 and p[IP].frag == 0:
            writer.write(p)
            continue

        fragments += p
        fragments = defragment(fragments)
        defragged = []
        for f in fragments:
            if f[IP].flags & 1 == 0 and f[IP].frag == 0:
                defragged.append(f)
        fragments = [f for f in fragments if f not in defragged]
        for df in defragged:
            print 'Defragmented packet.'
            writer.write(df)
示例#2
0
    def trace_pcap(self, pcap_file):
        self.fragments = []
        reader = RawPcapReader(pcap_file)
        i = 1
        for pkt_data in reader:
            self.logger.info('{}'.format(i))
            i += 1
            p = Ether(pkt_data[0])

            if not isinstance(p[1], IP):
                continue

            if p[IP].flags & 1 == 1 or p[IP].frag > 0:
                self.logger.debug('Fragmented IPv4 packet encountered.')
                self.fragments += p
                self.fragments = defragment(self.fragments)
                defragged = []
                for f in self.fragments:
                    if f[IP].flags & 1 == 0 and f[IP].frag == 0:
                        defragged.append(f)
                self.fragments = [
                    f for f in self.fragments if f not in defragged
                ]
                for df in defragged:
                    self.logger.debug('Defragmented packet.')
                    if isinstance(df[2], TCP):
                        tracer.trace(df)

            elif isinstance(p[2], TCP):
                tracer.trace(p)
示例#3
0
def main():
    parser = argparse.ArgumentParser(
        description='Fragments the IPv4 packets in the given PCAP file '
        'and writes the results to another file.')
    parser.add_argument('input_file')
    parser.add_argument('output_file')
    parser.add_argument(
        '--fragment-size',
        '-s',
        type=int,
        default=500,
        help='Fragment size. Packets larger than this are fragmented '
        'if their df flag is not set. Defaults to 500.')

    args = parser.parse_args()

    reader = RawPcapReader(args.input_file)
    writer = PcapWriter(args.output_file, append=False, sync=True)
    for pkt_data in reader:
        p = Ether(pkt_data[0])
        if isinstance(
                p[1],
                IP) and len(p[2]) > args.fragment_size and p[1].flags & 2 != 0:
            p = fragment(p, args.fragment_size)
            print 'Fragmented packet into {} fragments.'.format(len(p))

        writer.write(p)
示例#4
0
def loadpcaps(folder, namedict):
    filenames = os.listdir(folder)  #read al filenames in folder
    pcapdict = {}

    for filename in filenames:
        packetdict = {}

        with RawPcapReader(folder + filename) as sub_pcap_reader:
            for sub_raw_pkt in sub_pcap_reader:
                sub_pkt = sub_raw_pkt[0]

                l3pkt = findpayloadtlv(4, sub_pkt, filename,
                                       namedict)  #first 4B can be skipped
                l3pkthash = hashlib.sha512(l3pkt[0]).hexdigest()

                if l3pkt[
                        1] == 0:  #necessary because subdumps sometimes contain duplicate packets w. ID=0
                    if l3pkthash in packetdict:
                        continue
                packetdict[l3pkthash] = l3pkt[1]

        pcapdict[filename] = packetdict

    return (filenames, pcapdict)
示例#5
0
    def analyze(self):
        pcap = RawPcapReader(self.file_name).read_all()
        if not pcap:
            self.fail('Empty pcap {0}'.format(self.file_name))

        l4_type = None
        for index, (raw_pkt, _) in enumerate(pcap):
            scapy_pkt = Ether(raw_pkt)

            # l3
            ipv4 = scapy_pkt.getlayer('IP')
            ipv6 = scapy_pkt.getlayer('IPv6')
            if ipv4 and ipv6:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap has both IPv4 and IPv6!' % index)

            if ipv4:
                l3 = ipv4
            elif ipv6:
                l3 = ipv6
            else:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap is not IPv4/6.' % index)

            # first packet
            if self.c_ip is None:
                self.c_ip = l3.src
                self.s_ip = l3.dst
                direction = "c"
            else:
                if self.c_ip == l3.src and self.s_ip == l3.dst:
                    direction = "c"
                elif self.s_ip == l3.src and self.c_ip == l3.dst:
                    direction = "s"
                else:
                    self.fail(
                        'Only one session is allowed in a file. Packet {0} is from different session'
                        .format(index))

            # l4
            tcp = scapy_pkt.getlayer('TCP')
            udp = scapy_pkt.getlayer('UDP')
            if tcp and udp:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap has both TCP and UDP' % index)

            elif tcp:
                l4 = tcp
                # SYN
                if l4.flags & 0x02:
                    # SYN + ACK
                    if l4.flags & 0x10:
                        self.s_tcp_win = tcp.window
                        if self.state == _CPcapReader_help.states["init"]:
                            self.fail(
                                'Packet #%s is SYN+ACK, but there was no SYN yet, or '
                                % index)
                        else:
                            if self.state != _CPcapReader_help.states["syn"]:
                                self.fail(
                                    'Packet #%s is SYN+ACK, but there was already SYN+ACK in cap file'
                                    % index)
                        self.state = _CPcapReader_help.states["syn+ack"]
                    # SYN - no ACK. Should be first packet client->server
                    else:
                        self.c_tcp_win = tcp.window
                        # allowing syn retransmission because cap2/https.pcap contains this
                        if self.state > _CPcapReader_help.states["syn"]:
                            self.fail(
                                'Packet #%s is TCP SYN, but there was already TCP SYN in cap file'
                                % index)
                        else:
                            self.state = _CPcapReader_help.states["syn"]
                else:
                    if self.state != _CPcapReader_help.states["syn+ack"]:
                        self.fail(
                            'Cap file must start with syn, syn+ack sequence')
                if l4_type not in (None, 'TCP'):
                    self.fail(
                        'PCAP contains both TCP and %s. This is not supported currently.'
                        % l4_type)
                l4_type = 'TCP'
            elif udp:
                self.fail(
                    'CAP file contains UDP packets. This is not supported yet')
                #l4 = udp
                #if l4_type not in (None, 'UDP'):
                #    self.fail('PCAP contains both UDP and %s. This is not supported currently.' % l4_type)
                #l4_type = 'UDP'
            else:
                scapy_pkt.show2()
                self.fail('Packet #%s in pcap is not TCP or UDP.' % index)

            if self.s_port == -1:
                self.s_port = l4.sport
                self.d_port = l4.dport

            padding = scapy_pkt.getlayer('Padding')
            if padding is not None:
                pad_len = len(padding)
            else:
                pad_len = 0
            l4_payload_len = len(l4.payload) - pad_len
            self.total_payload_len += l4_payload_len
            self._pkts.append(
                CPacketData(direction,
                            bytes(l4.payload)[0:l4_payload_len]))
示例#6
0
def process_pcap():
    count = 0
    for (pkt_data, pkt_metadata,) in RawPcapReader("sw20"):
        count += 1
        print(pkt_data)
    print("There are that many packets: " + str(count))
示例#7
0
def main():

    start = timer()
    try:  #if len groesser, -h for help, pcap ng - Fehlerbehandlung bei Fehleingaben
        dump = sys.argv[1]
        folder = sys.argv[2]
        idfolder = sys.argv[3]
        outpath = "keyfile"  #set default value
    except:
        print("keyfile creation failed, check params")
        sys.exit(0)

    try:
        outpath = sys.argv[4]
        target = open(outpath, 'w')
        print("writing key entries to: " + str(outpath))
    except:
        try:
            target = open("keyfile", 'w')
            print("writing key entries to: " + str(outpath))
        except:
            print("keyfile creation failed, check params")
            sys.exit(0)

    if os.path.exists(dump) and os.path.exists(folder) and os.path.exists(
            folder):
        print("Input valid")
    else:
        print("Check file paths")
        sys.exit(0)

    namedict = createiddict(
        idfolder
    )  #namedict[filename] = corresponding idfile as iddict[cgroupID] = values)

    framecounter = 0
    pktnbr = -1

    ldpcapstart = timer()

    loadedpcaps = loadpcaps(
        folder, namedict
    )  #gives dict with key:filename, value:(dict wihth key:l3pkt, value:cgroupID)
    filenames = loadedpcaps[0]
    pcapdict = loadedpcaps[1]

    ldpcapend = timer()
    labstart = timer()

    with RawPcapReader(dump) as pcap_reader:
        for raw_pkt in pcap_reader:
            framecounter += 1
            pktnbr = framecounter
            pkt = raw_pkt[0]

            if pkt[12:14] == b'\x08\x00' or pkt[12:14] == b'\x86\xdd':

                gefunden = False
                gefunden = searchpcap(pkt, filenames, pcapdict, framecounter,
                                      namedict, target)

                if gefunden is False:  #if packet not found write the following to keyfile
                    target.write(str(framecounter) + ";" + "-1" + ";" + "\n")
            else:
                target.write(
                    str(framecounter) + ";" + "-1" + ";" + "noL3" + ";" +
                    "noL3" + ";" + "\n")
                continue

    labend = timer()
    target.close()
    end = timer()

    print("Time to load Pcaps to dict: " + str(ldpcapend - ldpcapstart))
    print("Time to label: " + str(labend - labstart))

    duration = float(end - start)
    print("Time per packet: " + str(duration / pktnbr))
    print("Packets per second: " + str(1 / (duration / pktnbr)))
    print("Total packets: " + str(pktnbr))
    print("Execution time: " + str(duration))
def readPcap(fileName):

    packets = RawPcapReader(fileName)

    return packets