3
0

AttackController.py 8.3 KB

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