Controller.py 16 KB

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