Пример #1
0
    def generate_attack_pcap(self):
        """
        Creates a pcap containing the attack packets.

        :return: The location of the generated pcap file.
        """

        # write attack packets to pcap
        if self.readwrite != 'sequence': # sequence mode automatically writes to pcap
            self.attack_start_utime = self.packets[0].time
            self.attack_end_utime = self.packets[-1].time

            self.path_attack_pcap = self.write_attack_pcap(self.packets)

        # export statistics for generated attack pcap
        generated_attack_statistics = Statistics.Statistics(PcapFile.PcapFile(self.path_attack_pcap))
        generated_attack_statistics.load_pcap_statistics(False, True, False, False, [], False, None)
        if self.export_filetype == 'xlsx':
            Testing.exportSQLite3_toXLSX(Testing.connection_SQLite3_fromStatistics
                , generated_attack_statistics
                , 'semi_labeled_e_' + self.output_name
                , self.output_path)
        elif self.export_filetype == 'csv':
            output_path = os.path.join(self.output_path, 'CSV_generated_attack')
            if not os.path.exists(output_path):
                os.makedirs(output_path)
            Testing.exportSQLite3_toCSV(Testing.connection_SQLite3_fromStatistics
                , self.attack_statistics
                , self.output_path)

        # return packets sorted by packet time_sec_start
        return self.pkt_num, self.path_attack_pcap
Пример #2
0
def build_rewrapper(attack, param_dict):
    """
    Fill dictinaries with data from config.

    :param attack: Mix attack.
    :param param_dict: parsed config
    :return: rewrapper
    """
    if param_dict['atk.file'] != 'default':  ## default attack is hydra-1_tasks
        attack.attack_file = param_dict['atk.file']

    ## generate statistics for attack pcap
    attack.attack_statistics = Statistics.Statistics(
        PcapFile.PcapFile(attack.attack_file))
    attack.attack_statistics.load_pcap_statistics(False, True, False, False,
                                                  [], False, False)

    ## statistics stored in global dict under the keys
    global_dict = TMdict.GlobalRWdict(
        statistics=attack.statistics,
        attack_statistics=attack.attack_statistics)
    packet_dict = TMdict.PacketDataRWdict()
    conversation_dict = TMdict.ConversationRWdict()

    global_dict.add_recalculation_function(RecalTMdict.recalculate_mss)
    global_dict.add_recalculation_function(RecalTMdict.recalculate_ttl)
    global_dict.add_recalculation_function(RecalTMdict.recalculate_win_size)
    ## dicts stored in a dict under param data_dict under keys from TMdef
    rewrap = ReWrapper.ReWrapper(attack.statistics, global_dict,
                                 conversation_dict, packet_dict,
                                 scapy.NoPayload)

    return rewrap
Пример #3
0
def get_botnet_pcap_db():
    """
    Reads a botnet resource pcap, calculates statistics for it and returns the DB path.

    :return: the database path for the botnet resource pcap statistics DB
    """
    import Core.Statistics
    import ID2TLib.PcapFile as PcapFile

    bot_pcap = PcapFile.PcapFile(BOTNET_PCAP)
    bot_stats = Core.Statistics.Statistics(bot_pcap)
    bot_stats.do_extra_tests = True
    bot_stats.load_pcap_statistics(False, False, True, True, [], False, False)

    return bot_pcap.get_db_path()
Пример #4
0
    def __init__(self,
                 pcap_file_path: str,
                 do_extra_tests: bool,
                 non_verbose: bool = True,
                 pcap_out_path: str = None,
                 debug: bool = False):
        """
        Creates a new Controller, acting as a central coordinator for the whole application.

        :param pcap_file_path:
        """
        # Fields
        self.pcap_src_path = pcap_file_path.strip()
        self.pcap_dest_path = ''
        self.pcap_out_path = pcap_out_path
        self.written_pcaps = []
        self.do_extra_tests = do_extra_tests
        self.non_verbose = non_verbose
        self.seed = None
        self.durations = []
        self.added_packets = 0
        self.created_files = []
        self.debug = debug

        # Initialize class instances
        print("Input file: %s" % self.pcap_src_path)
        self.pcap_file = PcapFile.PcapFile(self.pcap_src_path)
        self.label_manager = LabelManager.LabelManager(self.pcap_src_path)
        self.statistics = Statistics.Statistics(self.pcap_file)
        self.statistics.do_extra_tests = self.do_extra_tests
        self.statisticsDB = self.statistics.get_statistics_database()
        self.attack_controller = atkCtrl.AttackController(
            self.pcap_file, self.statistics, self.label_manager)

        # Set output directory and create it (if necessary)
        if pcap_out_path is not None:
            out_dir = os.path.dirname(pcap_out_path)
            if not out_dir:  # if out_dir is cwd
                out_dir = "."
            Util.OUT_DIR = out_dir + os.sep
        else:
            Util.OUT_DIR = os.path.join(os.path.dirname(pcap_file_path),
                                        "id2t_results") + os.sep
        os.makedirs(Util.OUT_DIR, exist_ok=True)
Пример #5
0
    def process_attacks(self,
                        attacks_config: list,
                        seeds=None,
                        measure_time: bool = False,
                        inject_empty: bool = False):
        """
        Creates the attack based on the attack name and the attack parameters given in the attacks_config. The
        attacks_config is a list of attacks.
        e.g. [['PortscanAttack', 'ip.src="192.168.178.2",'dst.port=80'],['PortscanAttack', 'ip.src="10.10.10.2"]].
        Merges the individual temporary attack pcaps into one single pcap and merges this single pcap with the
        input dataset if desired.

        :param attacks_config: A list of attacks with their attack parameters.
        :param seeds: A list of random seeds for the given attacks.
        :param measure_time: Measure time for packet generation.
        :param inject_empty: if flag is set, Attack PCAPs will not be merged with the base PCAP, ie. Attacks are injected into an empty PCAP
        """

        # load attacks sequentially
        i = 0
        for attack in attacks_config:
            if seeds is not None and len(seeds) > i:
                rng_seed = seeds[i][0]
            else:
                rng_seed = int.from_bytes(os.urandom(16), sys.byteorder)
            self.attack_controller.set_seed(seed=rng_seed)
            temp_attack_pcap, duration = self.attack_controller.process_attack(
                attack[0], attack[1:], measure_time)
            self.durations.append(duration)
            self.added_packets += self.attack_controller.total_packets
            if not self.non_verbose:
                self.statistics.stats_summary_post_attack(self.added_packets)
            self.written_pcaps.append(temp_attack_pcap)
            i += 1

        attacks_pcap_path = None

        # merge attack pcaps to get single attack pcap
        if len(self.written_pcaps) > 1:
            print("\nMerging temporary attack pcaps into single pcap file...",
                  end=" ")
            sys.stdout.flush()  # force python to print text immediately
            for i in range(0, len(self.written_pcaps) - 1):
                attacks_pcap = PcapFile.PcapFile(self.written_pcaps[i])
                attacks_pcap_path = attacks_pcap.merge_attack(
                    self.written_pcaps[i + 1])
                os.remove(self.written_pcaps[i + 1])  # remove merged pcap
                self.written_pcaps[i + 1] = attacks_pcap_path
            print("done.")
        elif len(self.written_pcaps) == 1:
            attacks_pcap_path = self.written_pcaps[0]

        if attacks_pcap_path:
            if inject_empty:
                # copy the attack pcap to the directory of the base PCAP instead of merging them
                print("Copying single attack pcap to location of base pcap...",
                      end=" ")
                sys.stdout.flush()  # force python to print text immediately

                timestamp = '_' + time.strftime(
                    "%Y%m%d") + '-' + time.strftime("%X").replace(':', '')
                self.pcap_dest_path = self.pcap_src_path.replace(
                    ".pcap", timestamp + '.pcap')
                shutil.copy(attacks_pcap_path, self.pcap_dest_path)
            else:
                # merge single attack pcap with all attacks into base pcap
                print("Merging base pcap with single attack pcap...", end=" ")
                sys.stdout.flush()  # force python to print text immediately
                self.pcap_dest_path = self.pcap_file.merge_attack(
                    attacks_pcap_path)

            if self.pcap_out_path:
                if not self.pcap_out_path.endswith(".pcap"):
                    self.pcap_out_path += ".pcap"
                result_path = self.pcap_out_path
            else:
                tmp_path_tuple = self.pcap_dest_path.rpartition("/")
                result_path = Util.OUT_DIR + tmp_path_tuple[2]

            os.rename(self.pcap_dest_path, result_path)
            self.pcap_dest_path = result_path
            self.created_files = [self.pcap_dest_path]

            # process/move other created files
            pcap_basename = os.path.splitext(self.pcap_dest_path)[0]
            for x in self.attack_controller.additional_files:
                outpath = pcap_basename + "_" + x
                os.rename(x, outpath)
                self.created_files.append(outpath)

            print("done.")

            # delete intermediate PCAP files
            if self.debug:
                print(
                    'NOT deleting intermediate attack pcap while in debug mode.'
                )
            else:
                print('Deleting intermediate attack pcap...', end=" ")
                sys.stdout.flush()  # force python to print text immediately
                os.remove(attacks_pcap_path)
                print("done.")

            # write label file with attacks
            self.label_manager.write_label_file(self.pcap_dest_path)
            self.created_files.insert(1, self.label_manager.label_file_path)

            # print status message
            print('\nOutput files created:')
            for filepath in self.created_files:
                print(filepath)
        else:
            print("done.")
            print('\nOutput files created:')
            print(
                "--> No packets were injected. Therefore no output files were created."
            )

        # print summary statistics
        if not self.non_verbose and len(attacks_config) is not 1:
            self.statistics.stats_summary_post_attack(self.added_packets)