Controller.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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, pcap_out_path: str, do_extra_tests: bool, non_verbose: bool):
  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, time_value: 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 time_value: 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:], time_value)
  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. else:
  96. attacks_pcap_path = self.written_pcaps[0]
  97. if inject_empty:
  98. # copy the attack pcap to the directory of the base PCAP instead of merging them
  99. print("Copying single attack pcap to location of base pcap...", end=" ")
  100. sys.stdout.flush() # force python to print text immediately
  101. timestamp = '_' + time.strftime("%Y%m%d") + '-' + time.strftime("%X").replace(':', '')
  102. self.pcap_dest_path = self.pcap_src_path.replace(".pcap", timestamp + '.pcap')
  103. shutil.copy(attacks_pcap_path, self.pcap_dest_path)
  104. else:
  105. # merge single attack pcap with all attacks into base pcap
  106. print("Merging base pcap with single attack pcap...", end=" ")
  107. sys.stdout.flush() # force python to print text immediately
  108. self.pcap_dest_path = self.pcap_file.merge_attack(attacks_pcap_path)
  109. if self.pcap_out_path:
  110. if not self.pcap_out_path.endswith(".pcap"):
  111. self.pcap_out_path += ".pcap"
  112. result_path = self.pcap_out_path
  113. else:
  114. tmp_path_tuple = self.pcap_dest_path.rpartition("/")
  115. result_path = Util.OUT_DIR + tmp_path_tuple[2]
  116. os.rename(self.pcap_dest_path, result_path)
  117. self.pcap_dest_path = result_path
  118. created_files = [self.pcap_dest_path]
  119. # process/move other created files
  120. pcap_root = os.path.splitext(self.pcap_dest_path)[0]
  121. for k, v in Util.MISC_OUT_FILES.items():
  122. if v is None:
  123. created_files.append(k)
  124. else:
  125. outpath = pcap_root + "_" + k
  126. os.rename(v, outpath)
  127. created_files.append(outpath)
  128. print("done.")
  129. # delete intermediate PCAP files
  130. print('Deleting intermediate attack pcap...', end=" ")
  131. sys.stdout.flush() # force python to print text immediately
  132. os.remove(attacks_pcap_path)
  133. print("done.")
  134. # write label file with attacks
  135. self.label_manager.write_label_file(self.pcap_dest_path)
  136. created_files.insert(1, self.label_manager.label_file_path)
  137. # print status message
  138. print('\nOutput files created:')
  139. for filepath in created_files:
  140. print(filepath)
  141. # print summary statistics
  142. if not self.non_verbose:
  143. self.statistics.stats_summary_post_attack(self.added_packets)
  144. def process_db_queries(self, query, print_results=False):
  145. """
  146. Processes a statistics database query. This can be a standard SQL query or a named query.
  147. :param query: The query as a string or multiple queries as a list of strings.
  148. :param print_results: Must be True if the results should be printed to terminal.
  149. :return: The query's result
  150. """
  151. print("Processing database query/queries...")
  152. if isinstance(query, list) or isinstance(query, tuple):
  153. for q in query:
  154. self.statisticsDB.process_db_query(q, print_results)
  155. else:
  156. self.statisticsDB.process_db_query(query, print_results)
  157. @staticmethod
  158. def process_help(params):
  159. if not params:
  160. print("Query mode allows you to enter SQL-queries as well as named queries.")
  161. print()
  162. print("Named queries:")
  163. print("\tSelectors:")
  164. print("\t\tmost_used(...) -> Returns the most occurring element in all elements")
  165. print("\t\tleast_used(...) -> Returns the least occurring element in all elements")
  166. print("\t\tavg(...) -> Returns the average of all elements")
  167. print("\t\tall(...) -> Returns all elements")
  168. print("\tExtractors:")
  169. print("\t\trandom(...) -> Returns a random element from a list")
  170. print("\t\tfirst(...) -> Returns the first element from a list")
  171. print("\t\tlast(...) -> Returns the last element from a list")
  172. print("\tParameterized selectors:")
  173. print("\t\tipAddress(...) -> Returns all IP addresses fulfilling the specified conditions")
  174. print("\t\tmacAddress(...) -> Returns all MAC addresses fulfilling the specified conditions")
  175. print()
  176. print("Miscellaneous:")
  177. print("\tlabels -> List all attacks listed in the label file, if any")
  178. print("\ttables -> List all tables from database")
  179. print("\tcolumns TABLE -> List column names and types from specified table")
  180. print()
  181. print("Additional information is available with 'help [KEYWORD];'")
  182. print("To get a list of examples, type 'help examples;'")
  183. print()
  184. return
  185. param = params[0].lower()
  186. if param == "most_used":
  187. print("most_used can be used as a selector for the following attributes:")
  188. print("ipAddress | macAddress | portNumber | protocolName | ttlValue | mssValue | winSize | ipClass")
  189. print()
  190. elif param == "least_used":
  191. print("least_used can be used as a selector for the following attributes:")
  192. print("ipAddress | macAddress | portNumber | protocolName | ttlValue")
  193. print()
  194. elif param == "avg":
  195. print("avg can be used as a selector for the following attributes:")
  196. print("pktsReceived | pktsSent | kbytesSent | kbytesReceived | ttlValue | mss")
  197. print()
  198. elif param == "all":
  199. print("all can be used as a selector for the following attributes:")
  200. print("ipAddress | ttlValue | mss | macAddress | portNumber | protocolName")
  201. print()
  202. elif param in ["random", "first", "last"]:
  203. print("No additional info available for this keyword.")
  204. print()
  205. elif param == "ipaddress":
  206. print("ipAddress is a parameterized selector which fetches IP addresses based on (a list of) conditions.")
  207. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  208. print("The following parameters can be specified:")
  209. print("pktsReceived | pktsSent | kbytesReceived | kbytesSent | maxPktRate | minPktRate | ipClass\n"
  210. "macAddress | ttlValue | ttlCount | portDirection | portNumber | portCount | protocolCount\n"
  211. "protocolName")
  212. print()
  213. print("See 'help examples;' for usage examples.")
  214. print()
  215. elif param == "macaddress":
  216. print("macAddress is a parameterized selector which fetches MAC addresses based on (a list of) conditions.")
  217. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  218. print("The following parameters can be specified:")
  219. print("ipAddress")
  220. print()
  221. print("See 'help examples;' for usage examples.")
  222. print()
  223. elif param == "examples":
  224. print("Get the average amount of sent packets per IP:")
  225. print("\tavg(pktsSent);")
  226. print("Get a random IP from all addresses occuring in the pcap:")
  227. print("\trandom(all(ipAddress));")
  228. print("Return the MAC address of a specified IP:")
  229. print("\tmacAddress(ipAddress=192.168.178.2);")
  230. print("Get the average TTL-value with SQL:")
  231. print("\tSELECT avg(ttlValue) from ip_ttl;")
  232. print("Get a random IP address from all addresses that sent and received at least 10 packets:")
  233. print("\trandom(ipAddress(pktsSent > 10, pktsReceived > 10));")
  234. print()
  235. else:
  236. print("Unknown keyword '" + param + "', try 'help;' to get a list of allowed keywords'")
  237. print()
  238. def enter_query_mode(self):
  239. """
  240. Enters into the query mode. This is a read-eval-print-loop, where the user can input named queries or SQL
  241. queries and the results are printed.
  242. """
  243. def make_completer(vocabulary):
  244. def custom_template(text, state):
  245. results = [x for x in vocabulary if x.startswith(text)] + [None]
  246. return results[state]
  247. return custom_template
  248. readline.parse_and_bind('tab: complete')
  249. readline.set_completer(make_completer(
  250. self.statisticsDB.get_all_named_query_keywords() + self.statisticsDB.get_all_sql_query_keywords()))
  251. history_file = os.path.join(Util.CACHE_DIR, 'query_history')
  252. try:
  253. readline.read_history_file(history_file)
  254. except IOError:
  255. pass
  256. print("Entering into query mode...")
  257. print("Enter statement ending by ';' and press ENTER to send query. Exit by sending an empty query.")
  258. print("Type 'help;' for information on possible queries.")
  259. buffer = ""
  260. while True:
  261. line = input("> ")
  262. if line == "":
  263. break
  264. buffer += line
  265. import sqlite3
  266. if sqlite3.complete_statement(buffer):
  267. buffer = buffer.strip()
  268. if buffer.lower().startswith('help'):
  269. buffer = buffer.strip(';')
  270. self.process_help(buffer.split(' ')[1:])
  271. elif buffer.lower().strip() == 'labels;':
  272. if not self.label_manager.labels:
  273. print("No labels found.")
  274. else:
  275. print("Attacks listed in the label file:")
  276. print()
  277. for label in self.label_manager.labels:
  278. print("Attack name: " + str(label.attack_name))
  279. print("Attack note: " + str(label.attack_note))
  280. print("Start timestamp: " + str(label.timestamp_start))
  281. print("End timestamp: " + str(label.timestamp_end))
  282. print()
  283. print()
  284. elif buffer.lower().strip() == 'tables;':
  285. self.statisticsDB.process_db_query("SELECT name FROM sqlite_master WHERE type='table';", True)
  286. elif buffer.lower().strip().startswith('columns '):
  287. self.statisticsDB.process_db_query("SELECT * FROM " + buffer.lower()[8:], False)
  288. columns = self.statisticsDB.get_field_types(buffer.lower()[8:].strip(";"))
  289. for column in columns:
  290. print(column + ": " + columns[column])
  291. else:
  292. try:
  293. self.statisticsDB.process_db_query(buffer, True)
  294. except sqlite3.Error as e:
  295. print("An error occurred:", e.args[0])
  296. except pp.ParseException as e:
  297. sys.stderr.write("Error in query:\n")
  298. sys.stderr.write(buffer)
  299. sys.stderr.write("\n")
  300. for i in range(1, e.col):
  301. sys.stderr.write(" ")
  302. sys.stderr.write("^\n\n")
  303. buffer = ""
  304. readline.set_history_length(1000)
  305. readline.write_history_file(history_file)
  306. def create_statistics_plot(self, params: str, entropy: bool):
  307. """
  308. Plots the statistics to a file by using the given customization parameters.
  309. """
  310. if params is not None and params[0] is not None:
  311. # FIXME: cleanup
  312. params_dict = dict([z.split("=") for z in params])
  313. self.statistics.plot_statistics(entropy=entropy, file_format=params_dict['format'])
  314. else:
  315. self.statistics.plot_statistics(entropy=entropy)