AttackController.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. input_name = input_name.lower()
  53. highest_sim = 0.0
  54. highest_sim_attack = None
  55. for attack in available_attacks:
  56. # Compares input with one of the available attacks
  57. # Makes comparison with lowercase version with generic 'attack' and 'exploit' ending removed
  58. similarity = difflib.SequenceMatcher(None, input_name,
  59. Util.rchop(attack.lower(), ('attack', 'exploit')))\
  60. .ratio()
  61. # Exact match, return appropriate attack name
  62. if similarity == 1.0:
  63. return attack
  64. # Found more likely match
  65. if similarity > highest_sim:
  66. highest_sim = similarity
  67. highest_sim_attack = attack
  68. # Found no exactly matching attack name, print best match and exit
  69. if highest_sim >= 0.6:
  70. print('Found no attack of name ' + input_name + '. The closest match was ' + highest_sim_attack +
  71. '. Use ./id2t -l for a list of available attacks.')
  72. exit(1)
  73. # Found no reasonably matching attack name, recommend -l and exit
  74. else:
  75. print('Found no attack of name ' + input_name + ' or one similar to it.'
  76. ' Use ./id2t -l for an overview of available attacks.')
  77. exit(1)
  78. attack_name = choose_attack(attack_name)
  79. print("\nCreating attack instance of \033[1m" + attack_name + "\033[0m")
  80. # Load attack class
  81. attack_module = importlib.import_module("Attack." + attack_name)
  82. attack_class = getattr(attack_module, attack_name)
  83. # Instantiate the desired attack
  84. self.current_attack = attack_class()
  85. # Initialize the parameters of the attack with defaults or user supplied values.
  86. self.current_attack.set_statistics(self.statistics)
  87. if seed is not None:
  88. self.current_attack.set_seed(seed=seed)
  89. self.current_attack.init_params()
  90. # Record the attack
  91. self.added_attacks.append(self.current_attack)
  92. def process_attack(self, attack: str, params: str, time=False):
  93. """
  94. Takes as input the name of an attack (classname) and the attack parameters as string. Parses the string of
  95. attack parameters, creates the attack by writing the attack packets and returns the path of the written pcap.
  96. :param attack: The classname of the attack to injecect.
  97. :param params: The parameters for attack customization, see attack class for supported params.
  98. :param time: Measure packet generation time or not.
  99. :return: The file path to the created pcap file.
  100. """
  101. self.create_attack(attack, self.seed)
  102. print("Validating and adding attack parameters.")
  103. # Add attack parameters if provided
  104. params_dict = []
  105. if isinstance(params, list) and params:
  106. # Convert attack param list into dictionary
  107. for entry in params:
  108. params_dict.append(entry.split('='))
  109. params_dict = dict(params_dict)
  110. # Check if Parameter.INJECT_AT_TIMESTAMP and Parameter.INJECT_AFTER_PACKET are provided at the same time
  111. # if TRUE: delete Paramter.INJECT_AT_TIMESTAMP (lower priority) and use Parameter.INJECT_AFTER_PACKET
  112. if (atkParam.Parameter.INJECT_AFTER_PACKET.value in params_dict) and (
  113. atkParam.Parameter.INJECT_AT_TIMESTAMP.value in params_dict):
  114. print("CONFLICT: Parameters", atkParam.Parameter.INJECT_AT_TIMESTAMP.value, "and",
  115. atkParam.Parameter.INJECT_AFTER_PACKET.value,
  116. "given at the same time. Ignoring", atkParam.Parameter.INJECT_AT_TIMESTAMP.value, "and using",
  117. atkParam.Parameter.INJECT_AFTER_PACKET.value, "instead to derive the timestamp.")
  118. del params_dict[atkParam.Parameter.INJECT_AT_TIMESTAMP.value]
  119. # Extract attack_note parameter, if not provided returns an empty string
  120. key_attack_note = "attack.note"
  121. attack_note = params_dict.get(key_attack_note, "")
  122. params_dict.pop(key_attack_note, None) # delete entry if found, otherwise return an empty string
  123. # Pass paramters to attack controller
  124. self.set_params(params_dict)
  125. else:
  126. attack_note = "This attack used only (random) default parameters."
  127. # Write attack into pcap file
  128. print("Generating attack packets...", end=" ")
  129. sys.stdout.flush() # force python to print text immediately
  130. if time:
  131. self.current_attack.set_start_time()
  132. self.current_attack.generate_attack_packets()
  133. if time:
  134. self.current_attack.set_finish_time()
  135. duration = self.current_attack.get_packet_generation_time()
  136. self.total_packets, temp_attack_pcap_path = self.current_attack.generate_attack_pcap()
  137. print("done. (total: " + str(self.total_packets) + " pkts", end="")
  138. if time:
  139. print(" in ", duration, " seconds", end="")
  140. print(".)")
  141. # Store label into LabelManager
  142. label = Label.Label(attack, self.get_attack_start_utime(),
  143. self.get_attack_end_utime(), attack_note)
  144. self.label_mgr.add_labels(label)
  145. return temp_attack_pcap_path, duration
  146. def get_attack_start_utime(self):
  147. """
  148. :return: The start time (timestamp of first packet) of the attack as unix timestamp.
  149. """
  150. return self.current_attack.attack_start_utime
  151. def get_attack_end_utime(self):
  152. """
  153. :return: The end time (timestamp of last packet) of the attack as unix timestamp.
  154. """
  155. return self.current_attack.attack_end_utime
  156. def set_params(self, params: dict):
  157. """
  158. Sets the attack's parameters.
  159. :param params: The parameters in a dictionary: {parameter_name: parameter_value}
  160. :return: None
  161. """
  162. for param_key, param_value in params.items():
  163. self.current_attack.add_param_value(param_key, param_value)