Controller.py 14 KB

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