Controller.py 12 KB

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