Controller.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. """
  124. TODO: FILL ME
  125. :param params:
  126. :return:
  127. """
  128. if not params:
  129. print("Query mode allows you to enter SQL-queries as well as named queries.")
  130. print()
  131. print("Named queries:")
  132. print("\tSelectors:")
  133. print("\t\tmost_used(...) -> Returns the most occurring element in all elements")
  134. print("\t\tleast_used(...) -> Returns the least occurring element in all elements")
  135. print("\t\tavg(...) -> Returns the average of all elements")
  136. print("\t\tall(...) -> Returns all elements")
  137. print("\tExtractors:")
  138. print("\t\trandom(...) -> Returns a random element from a list")
  139. print("\t\tfirst(...) -> Returns the first element from a list")
  140. print("\t\tlast(...) -> Returns the last element from a list")
  141. print("\tParameterized selectors:")
  142. print("\t\tipAddress(...) -> Returns all IP addresses fulfilling the specified conditions")
  143. print("\t\tmacAddress(...) -> Returns all MAC addresses fulfilling the specified conditions")
  144. print()
  145. print("Miscellaneous:")
  146. print("\tlabels -> List all attacks listed in the label file, if any")
  147. print("\ttables -> List all tables from database")
  148. print("\tcolumns TABLE -> List column names and types from specified table")
  149. print()
  150. print("Additional information is available with 'help [KEYWORD];'")
  151. print("To get a list of examples, type 'help examples;'")
  152. print()
  153. return
  154. param = params[0].lower()
  155. if param == "most_used":
  156. print("most_used can be used as a selector for the following attributes:")
  157. print("ipAddress | macAddress | portNumber | protocolName | ttlValue | mssValue | winSize | ipClass")
  158. print()
  159. elif param == "least_used":
  160. print("least_used can be used as a selector for the following attributes:")
  161. print("ipAddress | macAddress | portNumber | protocolName | ttlValue | mssValue | winSize | ipClass")
  162. print()
  163. elif param == "avg":
  164. print("avg can be used as a selector for the following attributes:")
  165. print("pktsReceived | pktsSent | kbytesSent | kbytesReceived | ttlValue | mss")
  166. print()
  167. elif param == "all":
  168. print("all can be used as a selector for the following attributes:")
  169. print("ipAddress | ttlValue | mss | macAddress | portNumber | protocolName | winSize | ipClass")
  170. print()
  171. elif param in ["random", "first", "last"]:
  172. print("No additional info available for this keyword.")
  173. print()
  174. elif param == "ipaddress":
  175. print("ipAddress is a parameterized selector which fetches IP 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("pktsReceived | pktsSent | kbytesReceived | kbytesSent | maxPktRate | minPktRate | ipClass\n"
  179. "macAddress | ttlValue | ttlCount | portDirection | portNumber | portCount | protocolCount\n"
  180. "protocolName")
  181. print()
  182. print("The following operators can be used:")
  183. print("<= | < | = | >= | > | in")
  184. print()
  185. print("A value can either be a simple values, a list of simple values separated by commas and enclosed "
  186. "in [] brackets, or another query.")
  187. print()
  188. print("When VALUE is a list (or a query returning a list), the usage of the 'in' operator is mandatory!")
  189. print()
  190. print("See 'help examples;' for usage examples.")
  191. print()
  192. elif param == "macaddress":
  193. print("macAddress is a parameterized selector which fetches MAC addresses based on (a list of) conditions.")
  194. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  195. print("The following parameters can be specified:")
  196. print("ipAddress")
  197. print()
  198. print("See 'help ipAddress' for information on valid operators and values.")
  199. print()
  200. print("See 'help examples;' for usage examples.")
  201. print()
  202. elif param == "examples":
  203. print("Get the average amount of sent packets per IP:")
  204. print("\tavg(pktsSent);")
  205. print("Get a random IP from all addresses occuring in the pcap:")
  206. print("\trandom(all(ipAddress));")
  207. print("Return the MAC address of a specified IP:")
  208. print("\tmacAddress(ipAddress=192.168.178.2);")
  209. print("Get the average TTL-value with SQL:")
  210. print("\tSELECT avg(ttlValue) from ip_ttl;")
  211. print("Get a random IP address from all addresses that sent and received at least 10 packets:")
  212. print("\trandom(ipAddress(pktsSent > 10, pktsReceived > 10));")
  213. print("Get the IP addresses used with one of the MAC addresses in a list:")
  214. print("\tipAddress(macAddress in [08:00:27:a3:83:43, 52:54:00:12:35:02]);")
  215. print()
  216. else:
  217. print("Unknown keyword '" + param + "', try 'help;' to get a list of allowed keywords'")
  218. print()
  219. def enter_query_mode(self):
  220. """
  221. Enters into the query mode. This is a read-eval-print-loop, where the user can input named queries or SQL
  222. queries and the results are printed.
  223. """
  224. def make_completer(vocabulary):
  225. """
  226. TODO: FILL ME
  227. :param vocabulary:
  228. :return:
  229. """
  230. def custom_template(text, state):
  231. """
  232. TODO: FILL ME
  233. :param text:
  234. :param state:
  235. :return:
  236. """
  237. results = [x for x in vocabulary if x.startswith(text)] + [None]
  238. return results[state]
  239. return custom_template
  240. readline.parse_and_bind('tab: complete')
  241. readline.set_completer(make_completer(
  242. self.statisticsDB.get_all_named_query_keywords() + self.statisticsDB.get_all_sql_query_keywords()))
  243. history_file = os.path.join(Util.CACHE_DIR, 'query_history')
  244. try:
  245. readline.read_history_file(history_file)
  246. except IOError:
  247. pass
  248. print("Entering into query mode...")
  249. print("Enter statement ending by ';' and press ENTER to send query. Exit by sending an empty query.")
  250. print("Type 'help;' for information on possible queries.")
  251. buffer = ""
  252. while True:
  253. line = input("> ")
  254. if line == "":
  255. break
  256. buffer += line
  257. import sqlite3
  258. if sqlite3.complete_statement(buffer):
  259. buffer = buffer.strip()
  260. if buffer.lower().startswith('help'):
  261. buffer = buffer.strip(';')
  262. self.process_help(buffer.split(' ')[1:])
  263. elif buffer.lower().strip() == 'labels;':
  264. if not self.label_manager.labels:
  265. print("No labels found.")
  266. else:
  267. print("Attacks listed in the label file:")
  268. print()
  269. for label in self.label_manager.labels:
  270. print("Attack name: " + str(label.attack_name))
  271. print("Attack note: " + str(label.attack_note))
  272. print("Start timestamp: " + str(label.timestamp_start))
  273. print("End timestamp: " + str(label.timestamp_end))
  274. print()
  275. print()
  276. elif buffer.lower().strip() == 'tables;':
  277. self.statisticsDB.process_db_query("SELECT name FROM sqlite_master WHERE type='table';", True)
  278. elif buffer.lower().strip().startswith('columns '):
  279. self.statisticsDB.process_db_query("SELECT * FROM " + buffer.lower()[8:], False)
  280. columns = self.statisticsDB.get_field_types(buffer.lower()[8:].strip(";"))
  281. for column in columns:
  282. print(column + ": " + columns[column])
  283. else:
  284. try:
  285. self.statisticsDB.process_db_query(buffer, True)
  286. except sqlite3.Error as e:
  287. print("An error occurred:", e.args[0])
  288. except pp.ParseException as e:
  289. sys.stderr.write("Error in query:\n")
  290. sys.stderr.write(buffer)
  291. sys.stderr.write("\n")
  292. for i in range(1, e.col):
  293. sys.stderr.write(" ")
  294. sys.stderr.write("^\n\n")
  295. except StatsDB.QueryExecutionException as e:
  296. sys.stderr.write("An error occured: ")
  297. sys.stderr.write(e.args[0] + "\n")
  298. buffer = ""
  299. readline.set_history_length(1000)
  300. readline.write_history_file(history_file)
  301. def create_statistics_plot(self, params: str, entropy: bool):
  302. """
  303. Plots the statistics to a file by using the given customization parameters.
  304. """
  305. if params is not None and params[0] is not None:
  306. # FIXME: cleanup
  307. params_dict = dict([z.split("=") for z in params])
  308. self.statistics.plot_statistics(entropy=entropy, file_format=params_dict['format'])
  309. else:
  310. self.statistics.plot_statistics(entropy=entropy)