Controller.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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()
  128. print("Additional information is available with 'help [KEYWORD];'")
  129. print("To get a list of examples, type 'help examples;'")
  130. print()
  131. return
  132. param = params[0].lower()
  133. if param == "most_used":
  134. print("most_used can be used as a selector for the following attributes:")
  135. print("ipAddress | macAddress | portNumber | protocolName | ttlValue | mssValue | winSize | ipClass")
  136. print()
  137. elif param == "least_used":
  138. print("least_used can be used as a selector for the following attributes:")
  139. print("ipAddress | macAddress | portNumber | protocolName | ttlValue")
  140. print()
  141. elif param == "avg":
  142. print("avg can be used as a selector for the following attributes:")
  143. print("pktsReceived | pktsSent | kbytesSent | kbytesReceived | ttlValue | mss")
  144. print()
  145. elif param == "all":
  146. print("all can be used as a selector for the following attributes:")
  147. print("ipAddress | ttlValue | mss | macAddress | portNumber | protocolName")
  148. print()
  149. elif param in ["random", "first", "last"]:
  150. print("No additional info available for this keyword.")
  151. print()
  152. elif param == "ipaddress":
  153. print("ipAddress is a parameterized selector which fetches IP addresses based on (a list of) conditions.")
  154. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  155. print("The following parameters can be specified:")
  156. print("pktsReceived | pktsSent | kbytesReceived | kbytesSent | maxPktRate | minPktRate | ipClass\n"
  157. "macAddress | ttlValue | ttlCount | portDirection | portNumber | portCount | protocolCount\n"
  158. "protocolName")
  159. print()
  160. print("See 'help examples;' for usage examples.")
  161. print()
  162. elif param == "macaddress":
  163. print("macAddress is a parameterized selector which fetches MAC addresses based on (a list of) conditions.")
  164. print("Conditions are of the following form: PARAMETER OPERATOR VALUE")
  165. print("The following parameters can be specified:")
  166. print("ipAddress")
  167. print()
  168. print("See 'help examples;' for usage examples.")
  169. print()
  170. elif param == "examples":
  171. print("Get the average amount of sent packets per IP:")
  172. print("\tavg(pktsSent);")
  173. print("Get a random IP from all addresses occuring in the pcap:")
  174. print("\trandom(all(ipAddress));")
  175. print("Return the MAC address of a specified IP:")
  176. print("\tmacAddress(ipAddress=192.168.178.2);")
  177. print("Get the average TTL-value with SQL:")
  178. print("\tSELECT avg(ttlValue) from ip_ttl;")
  179. print("Get a random IP address from all addresses that sent and received at least 10 packets:")
  180. print("\trandom(ipAddress(pktsSent > 10, pktsReceived > 10));")
  181. print()
  182. else:
  183. print("Unknown keyword '" + param + "', try 'help;' to get a list of allowed keywords'")
  184. print()
  185. def enter_query_mode(self):
  186. """
  187. Enters into the query mode. This is a read-eval-print-loop, where the user can input named queries or SQL
  188. queries and the results are printed.
  189. """
  190. def make_completer(vocabulary):
  191. def custom_template(text, state):
  192. results = [x for x in vocabulary if x.startswith(text)] + [None]
  193. return results[state]
  194. return custom_template
  195. readline.parse_and_bind('tab: complete')
  196. readline.set_completer(make_completer(
  197. self.statisticsDB.get_all_named_query_keywords() + self.statisticsDB.get_all_sql_query_keywords()))
  198. history_file = os.path.join(os.path.expanduser('~'), 'ID2T_data', 'query_history')
  199. try:
  200. readline.read_history_file(history_file)
  201. except IOError:
  202. pass
  203. print("Entering into query mode...")
  204. print("Enter statement ending by ';' and press ENTER to send query. Exit by sending an empty query.")
  205. print("Type 'help;' for information on possible queries.")
  206. buffer = ""
  207. while True:
  208. line = input("> ")
  209. if line == "":
  210. break
  211. buffer += line
  212. import sqlite3
  213. if sqlite3.complete_statement(buffer):
  214. buffer = buffer.strip()
  215. if buffer.lower().startswith('help'):
  216. buffer = buffer.strip(';')
  217. self.process_help(buffer.split(' ')[1:])
  218. elif buffer.lower().strip() == 'labels;':
  219. if not self.label_manager.labels:
  220. print("No labels found.")
  221. else:
  222. print("Attacks listed in the label file:")
  223. print()
  224. for label in self.label_manager.labels:
  225. print("Attack name: " + str(label.attack_name))
  226. print("Attack note: " + str(label.attack_note))
  227. print("Start timestamp: " + str(label.timestamp_start))
  228. print("End timestamp: " + str(label.timestamp_end))
  229. print()
  230. print()
  231. else:
  232. try:
  233. self.statisticsDB.process_db_query(buffer, True)
  234. except sqlite3.Error as e:
  235. print("An error occurred:", e.args[0])
  236. except pp.ParseException as e:
  237. sys.stderr.write("Error in query:\n")
  238. sys.stderr.write(buffer)
  239. sys.stderr.write("\n")
  240. for i in range(1, e.col):
  241. sys.stderr.write(" ")
  242. sys.stderr.write("^\n\n")
  243. buffer = ""
  244. readline.set_history_length(1000)
  245. readline.write_history_file(history_file)
  246. def create_statistics_plot(self, params: str, entropy: bool):
  247. """
  248. Plots the statistics to a file by using the given customization parameters.
  249. """
  250. if params is not None and params[0] is not None:
  251. # FIXME: cleanup
  252. params_dict = dict([z.split("=") for z in params])
  253. self.statistics.plot_statistics(entropy=entropy, file_format=params_dict['format'])
  254. else:
  255. self.statistics.plot_statistics(entropy=entropy)