3
0

AttackController.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import importlib
  2. import sys
  3. import Attack.AttackParameters as atkParam
  4. import Core.LabelManager as LabelManager
  5. import Core.Statistics as Statistics
  6. import ID2TLib.Label as Label
  7. import ID2TLib.PcapFile as PcapFile
  8. class AttackController:
  9. def __init__(self, pcap_file: PcapFile.PcapFile, statistics_class: Statistics, label_manager: LabelManager):
  10. """
  11. Creates a new AttackController. The controller manages the attack injection, including the PCAP writing.
  12. :param pcap_file: The source .pcap file to run the attack on.
  13. :param statistics_class: A Statistics Object.
  14. :param label_manager: A LabelManager Object.
  15. """
  16. self.statistics = statistics_class
  17. self.pcap_file = pcap_file
  18. self.label_mgr = label_manager
  19. self.current_attack = None
  20. self.added_attacks = []
  21. self.seed = None
  22. self.total_packets = 0
  23. def set_seed(self, seed: int):
  24. """
  25. Sets global seed.
  26. :param seed: random seed
  27. """
  28. self.seed = seed
  29. def create_attack(self, attack_name: str, seed=None):
  30. """
  31. Creates dynamically a new class instance based on the given attack_name.
  32. :param attack_name: The name of the attack, must correspond to the attack's class name.
  33. :param seed: random seed for param generation
  34. :return: None
  35. """
  36. print("\nCreating attack instance of \033[1m" + attack_name + "\033[0m")
  37. # Load attack class
  38. attack_module = importlib.import_module("Attack." + attack_name)
  39. attack_class = getattr(attack_module, attack_name)
  40. # Instantiate the desired attack
  41. self.current_attack = attack_class()
  42. # Initialize the parameters of the attack with defaults or user supplied values.
  43. self.current_attack.set_statistics(self.statistics)
  44. if seed is not None:
  45. self.current_attack.set_seed(seed=seed)
  46. self.current_attack.init_params()
  47. # Record the attack
  48. self.added_attacks.append(self.current_attack)
  49. def process_attack(self, attack: str, params: str, time=False):
  50. """
  51. Takes as input the name of an attack (classname) and the attack parameters as string. Parses the string of
  52. attack parameters, creates the attack by writing the attack packets and returns the path of the written pcap.
  53. :param attack: The classname of the attack to injecect.
  54. :param params: The parameters for attack customization, see attack class for supported params.
  55. :param time: Measure packet generation time or not.
  56. :return: The file path to the created pcap file.
  57. """
  58. self.create_attack(attack, self.seed)
  59. print("Validating and adding attack parameters.")
  60. # Add attack parameters if provided
  61. params_dict = []
  62. if isinstance(params, list) and params:
  63. # Convert attack param list into dictionary
  64. for entry in params:
  65. params_dict.append(entry.split('='))
  66. params_dict = dict(params_dict)
  67. # Check if Parameter.INJECT_AT_TIMESTAMP and Parameter.INJECT_AFTER_PACKET are provided at the same time
  68. # if TRUE: delete Paramter.INJECT_AT_TIMESTAMP (lower priority) and use Parameter.INJECT_AFTER_PACKET
  69. if (atkParam.Parameter.INJECT_AFTER_PACKET.value in params_dict) and (
  70. atkParam.Parameter.INJECT_AT_TIMESTAMP.value in params_dict):
  71. print("CONFLICT: Parameters", atkParam.Parameter.INJECT_AT_TIMESTAMP.value, "and",
  72. atkParam.Parameter.INJECT_AFTER_PACKET.value,
  73. "given at the same time. Ignoring", atkParam.Parameter.INJECT_AT_TIMESTAMP.value, "and using",
  74. atkParam.Parameter.INJECT_AFTER_PACKET.value, "instead to derive the timestamp.")
  75. del params_dict[atkParam.Parameter.INJECT_AT_TIMESTAMP.value]
  76. # Extract attack_note parameter, if not provided returns an empty string
  77. key_attack_note = "attack.note"
  78. attack_note = params_dict.get(key_attack_note, "")
  79. params_dict.pop(key_attack_note, None) # delete entry if found, otherwise return an empty string
  80. # Pass paramters to attack controller
  81. self.set_params(params_dict)
  82. else:
  83. attack_note = "This attack used only (random) default parameters."
  84. # Write attack into pcap file
  85. print("Generating attack packets...", end=" ")
  86. sys.stdout.flush() # force python to print text immediately
  87. if time:
  88. self.current_attack.set_start_time()
  89. self.current_attack.generate_attack_packets()
  90. if time:
  91. self.current_attack.set_finish_time()
  92. duration = self.current_attack.get_packet_generation_time()
  93. self.total_packets, temp_attack_pcap_path = self.current_attack.generate_attack_pcap()
  94. print("done. (total: " + str(self.total_packets) + " pkts", end="")
  95. if time:
  96. print(" in ", duration, " seconds", end="")
  97. print(".)")
  98. # Store label into LabelManager
  99. label = Label.Label(attack, self.get_attack_start_utime(),
  100. self.get_attack_end_utime(), attack_note)
  101. self.label_mgr.add_labels(label)
  102. return temp_attack_pcap_path, duration
  103. def get_attack_start_utime(self):
  104. """
  105. :return: The start time (timestamp of first packet) of the attack as unix timestamp.
  106. """
  107. return self.current_attack.attack_start_utime
  108. def get_attack_end_utime(self):
  109. """
  110. :return: The end time (timestamp of last packet) of the attack as unix timestamp.
  111. """
  112. return self.current_attack.attack_end_utime
  113. def set_params(self, params: dict):
  114. """
  115. Sets the attack's parameters.
  116. :param params: The parameters in a dictionary: {parameter_name: parameter_value}
  117. :return: None
  118. """
  119. for param_key, param_value in params.items():
  120. self.current_attack.add_param_value(param_key, param_value)