Controller.py 14 KB

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