3
0

AttackController.py 5.7 KB

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