Controller.py 17 KB

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