3
0

AttackController.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import importlib
  2. import sys
  3. import difflib
  4. import pkgutil
  5. import Attack.AttackParameters as atkParam
  6. import Core.LabelManager as LabelManager
  7. import Core.Statistics as Statistics
  8. import ID2TLib.Label as Label
  9. import ID2TLib.PcapFile as PcapFile
  10. import ID2TLib.Utility as Util
  11. class AttackController:
  12. def __init__(self, pcap_file: PcapFile.PcapFile, statistics_class: Statistics, label_manager: LabelManager):
  13. """
  14. Creates a new AttackController. The controller manages the attack injection, including the PCAP writing.
  15. :param pcap_file: The source .pcap file to run the attack on.
  16. :param statistics_class: A Statistics Object.
  17. :param label_manager: A LabelManager Object.
  18. """
  19. self.statistics = statistics_class
  20. self.pcap_file = pcap_file
  21. self.label_mgr = label_manager
  22. self.current_attack = None
  23. self.added_attacks = []
  24. self.seed = None
  25. self.total_packets = 0
  26. def set_seed(self, seed: int):
  27. """
  28. Sets rng seed.
  29. :param seed: rng seed
  30. """
  31. self.seed = seed
  32. @staticmethod
  33. def choose_attack(input_name):
  34. """"
  35. Finds the attack best matching to input_name
  36. :param input_name: The name of the attack the user put in
  37. :return: The best matching attack in case one was found
  38. """
  39. import Attack
  40. # Find all attacks, exclude some classes
  41. package = Attack
  42. available_attacks = []
  43. for _, name, __ in pkgutil.iter_modules(package.__path__):
  44. if name != 'BaseAttack' and name != 'AttackParameters':
  45. available_attacks.append(name)
  46. highest_sim = 0.0
  47. highest_sim_attack = None
  48. for attack in available_attacks:
  49. # Check if attack name is accurate
  50. if input_name == attack:
  51. return attack
  52. # Compares input with one of the available attacks
  53. # Makes comparison with lowercase version with generic endings removed
  54. # List of generic attack name endings can be found in ID2TLib.Utility
  55. counter_check = attack.lower()
  56. if not any(ending in input_name for ending in Util.generic_attack_names):
  57. counter_check = Util.remove_generic_ending(counter_check)
  58. similarity = difflib.SequenceMatcher(None, input_name.lower(), counter_check).ratio()
  59. # Exact match, return appropriate attack name
  60. if similarity == 1.0:
  61. return attack
  62. # Found more likely match
  63. if similarity > highest_sim:
  64. highest_sim = similarity
  65. highest_sim_attack = attack
  66. # Found no exactly matching attack name, print best match and exit
  67. if highest_sim >= 0.6:
  68. print('Found no attack of name ' + input_name + '. The closest match was ' + highest_sim_attack +
  69. '. Use ./id2t -l for a list of available attacks.')
  70. exit(1)
  71. # Found no reasonably matching attack name, recommend -l and exit
  72. else:
  73. print('Found no attack of name ' + input_name + ' or one similar to it.'
  74. ' Use ./id2t -l for an overview of available attacks.')
  75. exit(1)
  76. def create_attack(self, attack_name: str, seed=None):
  77. """
  78. Creates dynamically a new class instance based on the given attack_name.
  79. :param attack_name: The name of the attack, must correspond to the attack's class name.
  80. :param seed: random seed for param generation
  81. :return: None
  82. """
  83. attack_name = self.choose_attack(attack_name)
  84. print("\nCreating attack instance of \033[1m" + attack_name + "\033[0m")
  85. # Load attack class
  86. attack_module = importlib.import_module("Attack." + attack_name)
  87. attack_class = getattr(attack_module, attack_name)
  88. # Instantiate the desired attack
  89. self.current_attack = attack_class()
  90. # Initialize the parameters of the attack with defaults or user supplied values.
  91. self.current_attack.set_statistics(self.statistics)
  92. if seed is not None:
  93. self.current_attack.set_seed(seed=seed)
  94. self.current_attack.init_params()
  95. # Record the attack
  96. self.added_attacks.append(self.current_attack)
  97. def process_attack(self, attack: str, params: str, time=False):
  98. """
  99. Takes as input the name of an attack (classname) and the attack parameters as string. Parses the string of
  100. attack parameters, creates the attack by writing the attack packets and returns the path of the written pcap.
  101. :param attack: The classname of the attack to injecect.
  102. :param params: The parameters for attack customization, see attack class for supported params.
  103. :param time: Measure packet generation time or not.
  104. :return: The file path to the created pcap file.
  105. """
  106. self.create_attack(attack, self.seed)
  107. print("Validating and adding attack parameters.")
  108. # Add attack parameters if provided
  109. params_dict = []
  110. if isinstance(params, list) and params:
  111. # Convert attack param list into dictionary
  112. for entry in params:
  113. params_dict.append(entry.split('='))
  114. params_dict = dict(params_dict)
  115. # Check if Parameter.INJECT_AT_TIMESTAMP and Parameter.INJECT_AFTER_PACKET are provided at the same time
  116. # if TRUE: delete Paramter.INJECT_AT_TIMESTAMP (lower priority) and use Parameter.INJECT_AFTER_PACKET
  117. if (atkParam.Parameter.INJECT_AFTER_PACKET.value in params_dict) and (
  118. atkParam.Parameter.INJECT_AT_TIMESTAMP.value in params_dict):
  119. print("CONFLICT: Parameters", atkParam.Parameter.INJECT_AT_TIMESTAMP.value, "and",
  120. atkParam.Parameter.INJECT_AFTER_PACKET.value,
  121. "given at the same time. Ignoring", atkParam.Parameter.INJECT_AT_TIMESTAMP.value, "and using",
  122. atkParam.Parameter.INJECT_AFTER_PACKET.value, "instead to derive the timestamp.")
  123. del params_dict[atkParam.Parameter.INJECT_AT_TIMESTAMP.value]
  124. # Extract attack_note parameter, if not provided returns an empty string
  125. key_attack_note = "attack.note"
  126. attack_note = params_dict.get(key_attack_note, "")
  127. params_dict.pop(key_attack_note, None) # delete entry if found, otherwise return an empty string
  128. # Pass paramters to attack controller
  129. self.set_params(params_dict)
  130. else:
  131. attack_note = "This attack used only (random) default parameters."
  132. # Write attack into pcap file
  133. print("Generating attack packets...", end=" ")
  134. sys.stdout.flush() # force python to print text immediately
  135. if time:
  136. self.current_attack.set_start_time()
  137. self.current_attack.generate_attack_packets()
  138. if time:
  139. self.current_attack.set_finish_time()
  140. duration = self.current_attack.get_packet_generation_time()
  141. self.total_packets, temp_attack_pcap_path = self.current_attack.generate_attack_pcap()
  142. print("done. (total: " + str(self.total_packets) + " pkts", end="")
  143. if time:
  144. print(" in ", duration, " seconds", end="")
  145. print(".)")
  146. # Store label into LabelManager
  147. label = Label.Label(attack, self.get_attack_start_utime(),
  148. self.get_attack_end_utime(), attack_note)
  149. self.label_mgr.add_labels(label)
  150. return temp_attack_pcap_path, duration
  151. def get_attack_start_utime(self):
  152. """
  153. :return: The start time (timestamp of first packet) of the attack as unix timestamp.
  154. """
  155. return self.current_attack.attack_start_utime
  156. def get_attack_end_utime(self):
  157. """
  158. :return: The end time (timestamp of last packet) of the attack as unix timestamp.
  159. """
  160. return self.current_attack.attack_end_utime
  161. def set_params(self, params: dict):
  162. """
  163. Sets the attack's parameters.
  164. :param params: The parameters in a dictionary: {parameter_name: parameter_value}
  165. :return: None
  166. """
  167. for param_key, param_value in params.items():
  168. self.current_attack.add_param_value(param_key, param_value)