Controller.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import os
  2. import sys
  3. import readline
  4. from ID2TLib.AttackController import AttackController
  5. from ID2TLib.LabelManager import LabelManager
  6. from ID2TLib.PcapFile import PcapFile
  7. from ID2TLib.Statistics import Statistics
  8. class Controller:
  9. def __init__(self, pcap_file_path: str, do_extra_tests: bool):
  10. """
  11. Creates a new Controller, acting as a central coordinator for the whole application.
  12. :param pcap_file_path:
  13. """
  14. # Fields
  15. self.pcap_src_path = pcap_file_path.strip()
  16. self.pcap_dest_path = ''
  17. self.written_pcaps = []
  18. self.do_extra_tests = do_extra_tests
  19. # Initialize class instances
  20. print("Input file: %s" % self.pcap_src_path)
  21. self.pcap_file = PcapFile(self.pcap_src_path)
  22. self.label_manager = LabelManager(self.pcap_src_path)
  23. self.statistics = Statistics(self.pcap_file)
  24. self.statistics.do_extra_tests = self.do_extra_tests
  25. self.statisticsDB = self.statistics.get_statistics_database()
  26. self.attack_controller = AttackController(self.pcap_file, self.statistics, self.label_manager)
  27. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  28. """
  29. Loads the PCAP statistics either from the database, if the statistics were calculated earlier, or calculates
  30. the statistics and creates a new database.
  31. :param flag_write_file: Writes the statistics to a file.
  32. :param flag_recalculate_stats: Forces the recalculation of statistics.
  33. :param flag_print_statistics: Prints the statistics on the terminal.
  34. :return: None
  35. """
  36. self.statistics.load_pcap_statistics(flag_write_file, flag_recalculate_stats, flag_print_statistics)
  37. def process_attacks(self, attacks_config: list):
  38. """
  39. Creates the attack based on the attack name and the attack parameters given in the attacks_config. The
  40. attacks_config is a list of attacks, e.g.
  41. [['PortscanAttack', 'ip.src="192.168.178.2",'dst.port=80'],['PortscanAttack', 'ip.src="10.10.10.2"]].
  42. Merges the individual temporary attack pcaps into one single pcap and merges this single pcap with the
  43. input dataset.
  44. :param attacks_config: A list of attacks with their attack parameters.
  45. """
  46. # load attacks sequentially
  47. for attack in attacks_config:
  48. temp_attack_pcap = self.attack_controller.process_attack(attack[0], attack[1:])
  49. self.written_pcaps.append(temp_attack_pcap)
  50. # merge attack pcaps to get single attack pcap
  51. if len(self.written_pcaps) > 1:
  52. print("\nMerging temporary attack pcaps into single pcap file...", end=" ")
  53. sys.stdout.flush() # force python to print text immediately
  54. for i in range(0, len(self.written_pcaps) - 1):
  55. attacks_pcap = PcapFile(self.written_pcaps[i])
  56. attacks_pcap_path = attacks_pcap.merge_attack(self.written_pcaps[i + 1])
  57. os.remove(self.written_pcaps[i + 1]) # remove merged pcap
  58. self.written_pcaps[i + 1] = attacks_pcap_path
  59. print("done.")
  60. else:
  61. attacks_pcap_path = self.written_pcaps[0]
  62. # merge single attack pcap with all attacks into base pcap
  63. print("Merging base pcap with single attack pcap...", end=" ")
  64. sys.stdout.flush() # force python to print text immediately
  65. self.pcap_dest_path = self.pcap_file.merge_attack(attacks_pcap_path)
  66. print("done.")
  67. # delete intermediate PCAP files
  68. print('Deleting intermediate attack pcap...', end=" ")
  69. sys.stdout.flush() # force python to print text immediately
  70. os.remove(attacks_pcap_path)
  71. print("done.")
  72. # write label file with attacks
  73. self.label_manager.write_label_file(self.pcap_dest_path)
  74. # print status message
  75. print('\nOutput files created: \n', self.pcap_dest_path, '\n', self.label_manager.label_file_path)
  76. def process_db_queries(self, query, print_results=False):
  77. """
  78. Processes a statistics database query. This can be a standard SQL query or a named query.
  79. :param query: The query as a string or multiple queries as a list of strings.
  80. :param print_results: Must be True if the results should be printed to terminal.
  81. :return: The query's result
  82. """
  83. print("Processing database query/queries...")
  84. if isinstance(query, list) or isinstance(query, tuple):
  85. for q in query:
  86. self.statisticsDB.process_db_query(q, print_results)
  87. else:
  88. self.statisticsDB.process_db_query(query, print_results)
  89. def enter_query_mode(self):
  90. """
  91. Enters into the query mode. This is a read-eval-print-loop, where the user can input named queries or SQL
  92. queries and the results are printed.
  93. """
  94. print("Entering into query mode...")
  95. print("Enter statement ending by ';' and press ENTER to send query. Exit by sending an empty query..")
  96. buffer = ""
  97. while True:
  98. line = input("> ")
  99. if line == "":
  100. break
  101. buffer += line
  102. import sqlite3
  103. if sqlite3.complete_statement(buffer):
  104. try:
  105. buffer = buffer.strip()
  106. self.statisticsDB.process_db_query(buffer, True)
  107. except sqlite3.Error as e:
  108. print("An error occurred:", e.args[0])
  109. buffer = ""
  110. def create_statistics_plot(self, params: str):
  111. """
  112. Plots the statistics to a file by using the given customization parameters.
  113. """
  114. if params is not None and params[0] is not None:
  115. params_dict = dict([z.split("=") for z in params])
  116. self.statistics.plot_statistics(format=params_dict['format'])
  117. else:
  118. self.statistics.plot_statistics()