AttackController.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import importlib
  2. import os
  3. import tempfile
  4. from scapy.utils import PcapWriter
  5. from Attack.AttackParameters import Parameter
  6. from ID2TLib import LabelManager
  7. from ID2TLib import Statistics
  8. from ID2TLib.Label import Label
  9. from ID2TLib.PcapFile import PcapFile
  10. class AttackController:
  11. def __init__(self, pcap_file: 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 statistics_class:
  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. # The PCAP where the attack should be injected into
  22. self.base_pcap = self.statistics.pcap_filepath
  23. def write_attack_pcap(self):
  24. """
  25. Writes the attack's packets into a PCAP file with a temporary filename.
  26. :return: The path of the written PCAP file.
  27. """
  28. packets = self.current_attack.get_packets()
  29. # Write packets into pcap file
  30. temp_pcap = tempfile.NamedTemporaryFile(delete=False)
  31. pktdump = PcapWriter(temp_pcap.name)
  32. pktdump.write(packets)
  33. # Store pcap path and close file objects
  34. pcap_path = temp_pcap.name
  35. pktdump.close()
  36. temp_pcap.close()
  37. return pcap_path
  38. def create_attack(self, attack_name: str):
  39. """
  40. Creates dynamically a new class instance based on the given attack_name.
  41. :param attack_name: The name of the attack, must correspond to the attack's class name.
  42. :return: None
  43. """
  44. print("\nCreating attack instance of \033[1m" + attack_name + "\033[0m")
  45. # Load attack class
  46. attack_module = importlib.import_module("Attack." + attack_name)
  47. attack_class = getattr(attack_module, attack_name)
  48. # Set current attack
  49. self.current_attack = attack_class(self.statistics, self.base_pcap)
  50. self.added_attacks.append(self.current_attack)
  51. def process_attack(self, attack: str, params: str):
  52. """
  53. Takes as input the name of an attack (classname) and the attack parameters as string. Parses the string of
  54. attack parameters, creates the attack by writing the attack packets, merges these packets into the existing
  55. dataset and stores the label file of the injected attacks.
  56. :param attack: The classname of the attack to injecect.
  57. :param params: The parameters for attack customization, see attack class for supported params.
  58. :return: The file path to the created pcap file.
  59. """
  60. self.create_attack(attack)
  61. # Add attack parameters if provided
  62. print("Validating and adding attack parameters.")
  63. params_dict = []
  64. if params is not None:
  65. # Convert attack param list into dictionary
  66. for entry in params:
  67. params_dict.append(entry.split('='))
  68. params_dict = dict(params_dict)
  69. # Check if Parameter.INJECT_AT_TIMESTAMP and Parameter.INJECT_AFTER_PACKET are provided at the same time
  70. # if TRUE: delete Paramter.INJECT_AT_TIMESTAMP (lower priority) and use Parameter.INJECT_AFTER_PACKET
  71. if (Parameter.INJECT_AFTER_PACKET.value in params_dict) and (
  72. Parameter.INJECT_AT_TIMESTAMP.value in params_dict):
  73. print("CONFLICT: Parameters", Parameter.INJECT_AT_TIMESTAMP.value, "and",
  74. Parameter.INJECT_AFTER_PACKET.value,
  75. "given at the same time. Ignoring", Parameter.INJECT_AT_TIMESTAMP.value, "and using",
  76. Parameter.INJECT_AFTER_PACKET.value, "instead to derive the timestamp.")
  77. del params_dict[Parameter.INJECT_AT_TIMESTAMP.value]
  78. # Extract attack_note parameter, if not provided returns an empty string
  79. key_attack_note = "attack.note"
  80. attack_note = params_dict.get(key_attack_note, "")
  81. params_dict.pop(key_attack_note, None) # delete entry if found, otherwise return an empty string
  82. # Pass paramters to attack controller
  83. self.set_params(params_dict)
  84. else:
  85. attack_note = ""
  86. # Write attack into pcap file
  87. temp_attack_pcap_path = self.write_attack_pcap()
  88. # Merge attack with existing pcap
  89. pcap_dest_path = self.pcap_file.merge_attack(temp_attack_pcap_path)
  90. # Delete temporary attack pcap
  91. os.remove(temp_attack_pcap_path)
  92. # Store label into LabelManager
  93. l = Label(attack, self.get_attack_start_utime(),
  94. self.get_attack_end_utime(), attack_note)
  95. self.label_mgr.add_labels(l)
  96. return pcap_dest_path
  97. def get_attack_start_utime(self):
  98. """
  99. :return: The start time (timestamp of first packet) of the attack as unix timestamp.
  100. """
  101. return self.current_attack.attack_start_utime
  102. def get_attack_end_utime(self):
  103. """
  104. :return: The end time (timestamp of last packet) of the attack as unix timestamp.
  105. """
  106. return self.current_attack.attack_end_utime
  107. def set_params(self, params: dict):
  108. """
  109. Sets the attack's parameters.
  110. :param params: The parameters in a dictionary: {parameter_name: parameter_value}
  111. :return: None
  112. """
  113. for param_key, param_value in params.items():
  114. self.current_attack.add_param_value(param_key, param_value)