Controller.py 20 KB

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