Controller.py 19 KB

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