Controller.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. import Core.StatsDatabase as StatsDB
  11. class Controller:
  12. def __init__(self, pcap_file_path: str, do_extra_tests: bool, non_verbose: bool):
  13. """
  14. Creates a new Controller, acting as a central coordinator for the whole application.
  15. :param pcap_file_path:
  16. """
  17. # Fields
  18. self.pcap_src_path = pcap_file_path.strip()
  19. self.pcap_dest_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. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  35. """
  36. Loads the PCAP statistics either from the database, if the statistics were calculated earlier, or calculates
  37. the statistics and creates a new database.
  38. :param flag_write_file: Writes the statistics to a file.
  39. :param flag_recalculate_stats: Forces the recalculation of statistics.
  40. :param flag_print_statistics: Prints the statistics on the terminal.
  41. :param flag_non_verbose: Reduces terminal clutter.
  42. :return: None
  43. """
  44. self.statistics.load_pcap_statistics(flag_write_file, flag_recalculate_stats, flag_print_statistics,
  45. self.non_verbose)
  46. def process_attacks(self, attacks_config: list, seeds=None, time=False):
  47. """
  48. Creates the attack based on the attack name and the attack parameters given in the attacks_config. The
  49. attacks_config is a list of attacks.
  50. e.g. [['PortscanAttack', 'ip.src="192.168.178.2",'dst.port=80'],['PortscanAttack', 'ip.src="10.10.10.2"]].
  51. Merges the individual temporary attack pcaps into one single pcap and merges this single pcap with the
  52. input dataset.
  53. :param attacks_config: A list of attacks with their attack parameters.
  54. :param seeds: A list of random seeds for the given attacks.
  55. :param time: Measure time for packet generation.
  56. """
  57. # load attacks sequentially
  58. i = 0
  59. for attack in attacks_config:
  60. if seeds is not None and len(seeds) > i:
  61. rng_seed = seeds[i][0]
  62. else:
  63. rng_seed = int.from_bytes(os.urandom(16), sys.byteorder)
  64. self.attack_controller.set_seed(seed=rng_seed)
  65. temp_attack_pcap, duration = self.attack_controller.process_attack(attack[0], attack[1:], time)
  66. self.durations.append(duration)
  67. self.added_packets += self.attack_controller.total_packets
  68. if not self.non_verbose:
  69. self.statistics.stats_summary_post_attack(self.added_packets)
  70. self.written_pcaps.append(temp_attack_pcap)
  71. i += 1
  72. attacks_pcap_path = None
  73. # merge attack pcaps to get single attack pcap
  74. if len(self.written_pcaps) > 1:
  75. print("\nMerging temporary attack pcaps into single pcap file...", end=" ")
  76. sys.stdout.flush() # force python to print text immediately
  77. for i in range(0, len(self.written_pcaps) - 1):
  78. attacks_pcap = PcapFile.PcapFile(self.written_pcaps[i])
  79. attacks_pcap_path = attacks_pcap.merge_attack(self.written_pcaps[i + 1])
  80. os.remove(self.written_pcaps[i + 1]) # remove merged pcap
  81. self.written_pcaps[i + 1] = attacks_pcap_path
  82. print("done.")
  83. else:
  84. attacks_pcap_path = self.written_pcaps[0]
  85. # merge single attack pcap with all attacks into base pcap
  86. print("Merging base pcap with single attack pcap...", end=" ")
  87. sys.stdout.flush() # force python to print text immediately
  88. self.pcap_dest_path = self.pcap_file.merge_attack(attacks_pcap_path)
  89. tmp_path_tuple = self.pcap_dest_path.rpartition("/")
  90. result_dir = tmp_path_tuple[0] + tmp_path_tuple[1] + "ID2T_results/"
  91. result_path = result_dir + tmp_path_tuple[2]
  92. os.makedirs(result_dir, exist_ok=True)
  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 | mssValue | winSize | ipClass")
  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 | winSize | ipClass")
  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("The following operators can be used:")
  178. print("<= | < | = | >= | > | in")
  179. print()
  180. print("A value can either be a simple values, a list of simple values separated by commas and enclosed "
  181. "in [] brackets, or another query.")
  182. print()
  183. print("When VALUE is a list (or a query returning a list), the usage of the 'in' operator is mandatory!")
  184. print()
  185. print("See 'help examples;' for usage examples.")
  186. print()
  187. elif param == "macaddress":
  188. print("macAddress is a parameterized selector which fetches MAC addresses based on (a list of) conditions.")
  189. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  190. print("The following parameters can be specified:")
  191. print("ipAddress")
  192. print()
  193. print("See 'help ipAddress' for information on valid operators and values.")
  194. print()
  195. print("See 'help examples;' for usage examples.")
  196. print()
  197. elif param == "examples":
  198. print("Get the average amount of sent packets per IP:")
  199. print("\tavg(pktsSent);")
  200. print("Get a random IP from all addresses occuring in the pcap:")
  201. print("\trandom(all(ipAddress));")
  202. print("Return the MAC address of a specified IP:")
  203. print("\tmacAddress(ipAddress=192.168.178.2);")
  204. print("Get the average TTL-value with SQL:")
  205. print("\tSELECT avg(ttlValue) from ip_ttl;")
  206. print("Get a random IP address from all addresses that sent and received at least 10 packets:")
  207. print("\trandom(ipAddress(pktsSent > 10, pktsReceived > 10));")
  208. print("Get the IP addresses used with one of the MAC addresses in a list:")
  209. print("\tipAddress(macAddress in [08:00:27:a3:83:43, 52:54:00:12:35:02]);")
  210. print()
  211. else:
  212. print("Unknown keyword '" + param + "', try 'help;' to get a list of allowed keywords'")
  213. print()
  214. def enter_query_mode(self):
  215. """
  216. Enters into the query mode. This is a read-eval-print-loop, where the user can input named queries or SQL
  217. queries and the results are printed.
  218. """
  219. def make_completer(vocabulary):
  220. def custom_template(text, state):
  221. results = [x for x in vocabulary if x.startswith(text)] + [None]
  222. return results[state]
  223. return custom_template
  224. readline.parse_and_bind('tab: complete')
  225. readline.set_completer(make_completer(
  226. self.statisticsDB.get_all_named_query_keywords() + self.statisticsDB.get_all_sql_query_keywords()))
  227. history_file = os.path.join(Util.CACHE_DIR, 'query_history')
  228. try:
  229. readline.read_history_file(history_file)
  230. except IOError:
  231. pass
  232. print("Entering into query mode...")
  233. print("Enter statement ending by ';' and press ENTER to send query. Exit by sending an empty query.")
  234. print("Type 'help;' for information on possible queries.")
  235. buffer = ""
  236. while True:
  237. line = input("> ")
  238. if line == "":
  239. break
  240. buffer += line
  241. import sqlite3
  242. if sqlite3.complete_statement(buffer):
  243. buffer = buffer.strip()
  244. if buffer.lower().startswith('help'):
  245. buffer = buffer.strip(';')
  246. self.process_help(buffer.split(' ')[1:])
  247. elif buffer.lower().strip() == 'labels;':
  248. if not self.label_manager.labels:
  249. print("No labels found.")
  250. else:
  251. print("Attacks listed in the label file:")
  252. print()
  253. for label in self.label_manager.labels:
  254. print("Attack name: " + str(label.attack_name))
  255. print("Attack note: " + str(label.attack_note))
  256. print("Start timestamp: " + str(label.timestamp_start))
  257. print("End timestamp: " + str(label.timestamp_end))
  258. print()
  259. print()
  260. elif buffer.lower().strip() == 'tables;':
  261. self.statisticsDB.process_db_query("SELECT name FROM sqlite_master WHERE type='table';", True)
  262. elif buffer.lower().strip().startswith('columns '):
  263. self.statisticsDB.process_db_query("SELECT * FROM " + buffer.lower()[8:], False)
  264. columns = self.statisticsDB.get_field_types(buffer.lower()[8:].strip(";"))
  265. for column in columns:
  266. print(column + ": " + columns[column])
  267. else:
  268. try:
  269. self.statisticsDB.process_db_query(buffer, True)
  270. except sqlite3.Error as e:
  271. print("An error occurred:", e.args[0])
  272. except pp.ParseException as e:
  273. sys.stderr.write("Error in query:\n")
  274. sys.stderr.write(buffer)
  275. sys.stderr.write("\n")
  276. for i in range(1, e.col):
  277. sys.stderr.write(" ")
  278. sys.stderr.write("^\n\n")
  279. except StatsDB.QueryExecutionException as e:
  280. sys.stderr.write("An error occured: ")
  281. sys.stderr.write(e.args[0] + "\n")
  282. buffer = ""
  283. readline.set_history_length(1000)
  284. readline.write_history_file(history_file)
  285. def create_statistics_plot(self, params: str, entropy: bool):
  286. """
  287. Plots the statistics to a file by using the given customization parameters.
  288. """
  289. if params is not None and params[0] is not None:
  290. # FIXME: cleanup
  291. params_dict = dict([z.split("=") for z in params])
  292. self.statistics.plot_statistics(entropy=entropy, file_format=params_dict['format'])
  293. else:
  294. self.statistics.plot_statistics(entropy=entropy)