3
0

Controller.py 15 KB

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