Controller.py 17 KB

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