AttackController.py 8.1 KB

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