3
0

Controller.py 20 KB

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