Controller.py 15 KB

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