Controller.py 19 KB

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