AttackController.py 5.5 KB

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