Controller.py 14 KB

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