Controller.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. self.seed = None
  20. # Initialize class instances
  21. print("Input file: %s" % self.pcap_src_path)
  22. self.pcap_file = PcapFile(self.pcap_src_path)
  23. self.label_manager = LabelManager(self.pcap_src_path)
  24. self.statistics = Statistics(self.pcap_file)
  25. self.statistics.do_extra_tests = self.do_extra_tests
  26. self.statisticsDB = self.statistics.get_statistics_database()
  27. self.attack_controller = AttackController(self.pcap_file, self.statistics, self.label_manager)
  28. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  29. """
  30. Loads the PCAP statistics either from the database, if the statistics were calculated earlier, or calculates
  31. the statistics and creates a new database.
  32. :param flag_write_file: Writes the statistics to a file.
  33. :param flag_recalculate_stats: Forces the recalculation of statistics.
  34. :param flag_print_statistics: Prints the statistics on the terminal.
  35. :return: None
  36. """
  37. self.statistics.load_pcap_statistics(flag_write_file, flag_recalculate_stats, flag_print_statistics)
  38. def process_attacks(self, attacks_config: list, seeds=[], time=False):
  39. """
  40. Creates the attack based on the attack name and the attack parameters given in the attacks_config. The
  41. attacks_config is a list of attacks, e.g.
  42. [['PortscanAttack', 'ip.src="192.168.178.2",'dst.port=80'],['PortscanAttack', 'ip.src="10.10.10.2"]].
  43. Merges the individual temporary attack pcaps into one single pcap and merges this single pcap with the
  44. input dataset.
  45. :param attacks_config: A list of attacks with their attack parameters.
  46. :param seeds: A list of random seeds for the given attacks.
  47. :param time: Measure time for packet generation.
  48. """
  49. # load attacks sequentially
  50. self.durations = []
  51. i = 0
  52. for attack in attacks_config:
  53. if len(seeds) > i:
  54. self.attack_controller.set_seed(seed=seeds[i][0])
  55. temp_attack_pcap, duration = self.attack_controller.process_attack(attack[0], attack[1:], time)
  56. self.durations.append(duration)
  57. self.written_pcaps.append(temp_attack_pcap)
  58. i += 1
  59. # merge attack pcaps to get single attack pcap
  60. if len(self.written_pcaps) > 1:
  61. print("\nMerging temporary attack pcaps into single pcap file...", end=" ")
  62. sys.stdout.flush() # force python to print text immediately
  63. for i in range(0, len(self.written_pcaps) - 1):
  64. attacks_pcap = PcapFile(self.written_pcaps[i])
  65. attacks_pcap_path = attacks_pcap.merge_attack(self.written_pcaps[i + 1])
  66. os.remove(self.written_pcaps[i + 1]) # remove merged pcap
  67. self.written_pcaps[i + 1] = attacks_pcap_path
  68. print("done.")
  69. else:
  70. attacks_pcap_path = self.written_pcaps[0]
  71. # merge single attack pcap with all attacks into base pcap
  72. print("Merging base pcap with single attack pcap...", end=" ")
  73. sys.stdout.flush() # force python to print text immediately
  74. self.pcap_dest_path = self.pcap_file.merge_attack(attacks_pcap_path)
  75. tmp_path_tuple = self.pcap_dest_path.rpartition("/")
  76. result_dir = tmp_path_tuple[0] + tmp_path_tuple[1] + "ID2T_results/"
  77. result_path = result_dir + tmp_path_tuple[2]
  78. os.makedirs(result_dir, exist_ok=True)
  79. os.rename(self.pcap_dest_path, result_path)
  80. self.pcap_dest_path = result_path
  81. print("done.")
  82. # delete intermediate PCAP files
  83. print('Deleting intermediate attack pcap...', end=" ")
  84. sys.stdout.flush() # force python to print text immediately
  85. os.remove(attacks_pcap_path)
  86. print("done.")
  87. # write label file with attacks
  88. self.label_manager.write_label_file(self.pcap_dest_path)
  89. # print status message
  90. print('\nOutput files created: \n', self.pcap_dest_path, '\n', self.label_manager.label_file_path)
  91. def process_db_queries(self, query, print_results=False):
  92. """
  93. Processes a statistics database query. This can be a standard SQL query or a named query.
  94. :param query: The query as a string or multiple queries as a list of strings.
  95. :param print_results: Must be True if the results should be printed to terminal.
  96. :return: The query's result
  97. """
  98. print("Processing database query/queries...")
  99. if isinstance(query, list) or isinstance(query, tuple):
  100. for q in query:
  101. self.statisticsDB.process_db_query(q, print_results)
  102. else:
  103. self.statisticsDB.process_db_query(query, print_results)
  104. @staticmethod
  105. def process_help(params):
  106. if not params:
  107. print("Query mode allows you to enter SQL-queries as well as named queries.")
  108. print()
  109. print("Named queries:")
  110. print("\tSelectors:")
  111. print("\t\tmost_used(...) -> Returns the most occurring element in all elements")
  112. print("\t\tleast_used(...) -> Returns the least occurring element in all elements")
  113. print("\t\tavg(...) -> Returns the average of all elements")
  114. print("\t\tall(...) -> Returns all elements")
  115. print("\tExtractors:")
  116. print("\t\trandom(...) -> Returns a random element from a list")
  117. print("\t\tfirst(...) -> Returns the first element from a list")
  118. print("\t\tlast(...) -> Returns the last element from a list")
  119. print("\tParameterized selectors:")
  120. print("\t\tipAddress(...) -> Returns all IP addresses fulfilling the specified conditions")
  121. print("\t\tmacAddress(...) -> Returns all MAC addresses fulfilling the specified conditions")
  122. print()
  123. print("Miscellaneous:")
  124. print("\tlabels -> List all attacks listed in the label file, if any")
  125. print()
  126. print("Additional information is available with 'help [KEYWORD];'")
  127. print("To get a list of examples, type 'help examples;'")
  128. print()
  129. return
  130. param = params[0].lower()
  131. if param == "most_used":
  132. print("most_used can be used as a selector for the following attributes:")
  133. print("ipAddress | macAddress | portNumber | protocolName | ttlValue | mssValue | winSize | ipClass")
  134. print()
  135. elif param == "least_used":
  136. print("least_used can be used as a selector for the following attributes:")
  137. print("ipAddress | macAddress | portNumber | protocolName | ttlValue")
  138. print()
  139. elif param == "avg":
  140. print("avg can be used as a selector for the following attributes:")
  141. print("pktsReceived | pktsSent | kbytesSent | kbytesReceived | ttlValue | mss")
  142. print()
  143. elif param == "all":
  144. print("all can be used as a selector for the following attributes:")
  145. print("ipAddress | ttlValue | mss | macAddress | portNumber | protocolName")
  146. print()
  147. elif param in ["random", "first", "last"]:
  148. print("No additional info available for this keyword.")
  149. print()
  150. elif param == "ipaddress":
  151. print("ipAddress is a parameterized selector which fetches IP addresses based on (a list of) conditions.")
  152. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  153. print("The following parameters can be specified:")
  154. print("pktsReceived | pktsSent | kbytesReceived | kbytesSent | maxPktRate | minPktRate | ipClass\n"
  155. "macAddress | ttlValue | ttlCount | portDirection | portNumber | portCount | protocolCount\n"
  156. "protocolName")
  157. print()
  158. print("See 'help examples;' for usage examples.")
  159. print()
  160. elif param == "macaddress":
  161. print("macAddress is a parameterized selector which fetches MAC addresses based on (a list of) conditions.")
  162. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  163. print("The following parameters can be specified:")
  164. print("ipAddress")
  165. print()
  166. print("See 'help examples;' for usage examples.")
  167. print()
  168. elif param == "examples":
  169. print("Get the average amount of sent packets per IP:")
  170. print("\tavg(pktsSent);")
  171. print("Get a random IP from all addresses occuring in the pcap:")
  172. print("\trandom(all(ipAddress));")
  173. print("Return the MAC address of a specified IP:")
  174. print("\tmacAddress(ipAddress=192.168.178.2);")
  175. print("Get the average TTL-value with SQL:")
  176. print("\tSELECT avg(ttlValue) from ip_ttl;")
  177. print("Get a random IP address from all addresses that sent and received at least 10 packets:")
  178. print("\trandom(ipAddress(pktsSent > 10, pktsReceived > 10));")
  179. print()
  180. else:
  181. print("Unknown keyword '" + param + "', try 'help;' to get a list of allowed keywords'")
  182. print()
  183. def enter_query_mode(self):
  184. """
  185. Enters into the query mode. This is a read-eval-print-loop, where the user can input named queries or SQL
  186. queries and the results are printed.
  187. """
  188. def make_completer(vocabulary):
  189. def custom_template(text, state):
  190. results = [x for x in vocabulary if x.startswith(text)] + [None]
  191. return results[state]
  192. return custom_template
  193. readline.parse_and_bind('tab: complete')
  194. readline.set_completer(make_completer(self.statisticsDB.get_all_named_query_keywords()+self.statisticsDB.get_all_sql_query_keywords()))
  195. history_file = os.path.join(os.path.expanduser('~'), 'ID2T_data', 'query_history')
  196. try:
  197. readline.read_history_file(history_file)
  198. except IOError:
  199. pass
  200. print("Entering into query mode...")
  201. print("Enter statement ending by ';' and press ENTER to send query. Exit by sending an empty query.")
  202. print("Type 'help;' for information on possible queries.")
  203. buffer = ""
  204. while True:
  205. line = input("> ")
  206. if line == "":
  207. break
  208. buffer += line
  209. import sqlite3
  210. if sqlite3.complete_statement(buffer):
  211. try:
  212. buffer = buffer.strip()
  213. if buffer.lower().startswith('help'):
  214. buffer = buffer.strip(';')
  215. self.process_help(buffer.split(' ')[1:])
  216. elif buffer.lower().strip() == 'labels;':
  217. if not self.label_manager.labels:
  218. print("No labels found.")
  219. else:
  220. print("Attacks listed in the label file:")
  221. print()
  222. for label in self.label_manager.labels:
  223. print("Attack name: " + str(label.attack_name))
  224. print("Attack note: " + str(label.attack_note))
  225. print("Start timestamp: " + str(label.timestamp_start))
  226. print("End timestamp: " + str(label.timestamp_end))
  227. print()
  228. print()
  229. else:
  230. self.statisticsDB.process_db_query(buffer, True)
  231. except sqlite3.Error as e:
  232. print("An error occurred:", e.args[0])
  233. buffer = ""
  234. readline.set_history_length(1000)
  235. readline.write_history_file(history_file)
  236. def create_statistics_plot(self, params: str, entropy: bool):
  237. """
  238. Plots the statistics to a file by using the given customization parameters.
  239. """
  240. if params is not None and params[0] is not None:
  241. params_dict = dict([z.split("=") for z in params])
  242. self.statistics.plot_statistics(entropy = entropy, format=params_dict['format'])
  243. else:
  244. self.statistics.plot_statistics(entropy = entropy)