3
0

Controller.py 13 KB

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