DDoSAttack.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import logging
  2. from random import randint, uniform
  3. from lea import Lea
  4. from scipy.stats import gamma
  5. from Attack import BaseAttack
  6. from Attack.AttackParameters import Parameter as Param
  7. from Attack.AttackParameters import ParameterTypes
  8. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  9. # noinspection PyPep8
  10. from scapy.layers.inet import IP, Ether, TCP, RandShort
  11. from collections import deque
  12. class DDoSAttack(BaseAttack.BaseAttack):
  13. def __init__(self, statistics, pcap_file_path):
  14. """
  15. Creates a new instance of the DDoS attack.
  16. :param statistics: A reference to the statistics class.
  17. """
  18. # Initialize attack
  19. super(DDoSAttack, self).__init__(statistics, "DDoS Attack", "Injects a DDoS attack'",
  20. "Resource Exhaustion")
  21. # Define allowed parameters and their type
  22. self.supported_params = {
  23. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  24. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  25. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  26. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  27. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  28. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  29. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  30. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  31. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  32. Param.PACKETS_LIMIT: ParameterTypes.TYPE_INTEGER_POSITIVE,
  33. Param.NUMBER_ATTACKERS: ParameterTypes.TYPE_INTEGER_POSITIVE
  34. }
  35. # PARAMETERS: initialize with default values
  36. # (values are overwritten if user specifies them)
  37. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  38. # attacker configuration
  39. num_attackers = randint(1, 16)
  40. self.add_param_value(Param.IP_SOURCE, self.generate_random_ipv4_address(num_attackers))
  41. self.add_param_value(Param.MAC_SOURCE, self.generate_random_mac_address(num_attackers))
  42. self.add_param_value(Param.PORT_SOURCE, str(RandShort()))
  43. self.add_param_value(Param.PACKETS_PER_SECOND, randint(1, 64))
  44. # victim configuration
  45. random_ip_address = self.statistics.get_random_ip_address()
  46. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  47. destination_mac = self.statistics.get_mac_address(random_ip_address)
  48. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  49. destination_mac = self.generate_random_mac_address()
  50. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  51. port_destination = self.statistics.process_db_query(
  52. "SELECT portNumber FROM ip_ports WHERE portDirection='in' ORDER BY RANDOM() LIMIT 1;")
  53. if port_destination is None:
  54. port_destination = str(RandShort())
  55. self.add_param_value(Param.PORT_DESTINATION, port_destination)
  56. self.add_param_value(Param.PACKETS_LIMIT, randint(1000, 5000))
  57. def generate_attack_pcap(self):
  58. def update_timestamp(timestamp, pps, maxdelay):
  59. """
  60. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  61. :return: Timestamp to be used for the next packet.
  62. """
  63. return timestamp + uniform(0.1 / pps, maxdelay)
  64. def get_nth_random_element(*element_list):
  65. """
  66. Returns the n-th element of every list from an arbitrary number of given lists.
  67. For example, list1 contains IP addresses, list 2 contains MAC addresses. Use of this function ensures that
  68. the n-th IP address uses always the n-th MAC address.
  69. :param element_list: An arbitrary number of lists.
  70. :return: A tuple of the n-th element of every list.
  71. """
  72. range_max = min([len(x) for x in element_list])
  73. if range_max > 0: range_max -= 1
  74. n = randint(0, range_max)
  75. return tuple(x[n] for x in element_list)
  76. def index_increment(number: int, max: int):
  77. if number + 1 < max:
  78. return number + 1
  79. else:
  80. return 0
  81. def get_attacker_config(ipAddress: str):
  82. """
  83. Returns the attacker configuration depending on the IP address, this includes the port for the next
  84. attacking packet and the previously used (fixed) TTL value.
  85. :param ipAddress: The IP address of the attacker
  86. :return: A tuple consisting of (port, ttlValue)
  87. """
  88. # Determine port
  89. port = attacker_port_mapping.get(ipAddress)
  90. if port is not None: # use next port
  91. next_port = attacker_port_mapping.get(ipAddress) + 1
  92. if next_port > (2 ** 16 - 1):
  93. next_port = 1
  94. else: # generate starting port
  95. next_port = RandShort()
  96. attacker_port_mapping[ipAddress] = next_port
  97. # Determine TTL value
  98. ttl = attacker_ttl_mapping.get(ipAddress)
  99. if ttl is None: # determine TTL value
  100. is_invalid = True
  101. pos = ip_source_list.index(ipAddress)
  102. pos_max = len(gd)
  103. while is_invalid:
  104. ttl = int(round(gd[pos]))
  105. if 0 < ttl < 256: # validity check
  106. is_invalid = False
  107. else:
  108. pos = index_increment(pos, pos_max)
  109. attacker_ttl_mapping[ipAddress] = ttl
  110. # return port and TTL
  111. return next_port, ttl
  112. BUFFER_SIZE = 1000
  113. # Determine source IP and MAC address
  114. num_attackers = self.get_param_value(Param.NUMBER_ATTACKERS)
  115. if num_attackers is not None: # user supplied Param.NUMBER_ATTACKERS
  116. # Create random attackers based on user input Param.NUMBER_ATTACKERS
  117. ip_source_list = self.generate_random_ipv4_address(num_attackers)
  118. mac_source_list = self.generate_random_mac_address(num_attackers)
  119. else: # user did not supply Param.NUMBER_ATTACKS
  120. # use default values for IP_SOURCE/MAC_SOURCE or overwritten values
  121. # if user supplied any values for those params
  122. ip_source_list = self.get_param_value(Param.IP_SOURCE)
  123. mac_source_list = self.get_param_value(Param.MAC_SOURCE)
  124. # Timestamp
  125. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  126. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  127. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 30, 5 / pps: 15, 10 / pps: 3})
  128. # Initialize parameters
  129. packets = deque(maxlen=BUFFER_SIZE)
  130. port_source_list = self.get_param_value(Param.PORT_SOURCE)
  131. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  132. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  133. port_destination = self.get_param_value(Param.PORT_DESTINATION)
  134. attacker_port_mapping = {}
  135. attacker_ttl_mapping = {}
  136. # Gamma distribution parameters derived from MAWI 13.8G dataset
  137. alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
  138. gd = gamma.rvs(alpha, loc=loc, scale=beta, size=len(ip_source_list))
  139. path_attack_pcap = None
  140. for pkt_num in range(self.get_param_value(Param.PACKETS_LIMIT)):
  141. # Select one IP address and its corresponding MAC address
  142. (ip_source, mac_source) = get_nth_random_element(ip_source_list, mac_source_list)
  143. # Determine source port
  144. (port_source, ttl_value) = get_attacker_config(ip_source)
  145. maxdelay = randomdelay.random()
  146. request_ether = Ether(dst=mac_destination, src=mac_source)
  147. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  148. request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0)
  149. request = (request_ether / request_ip / request_tcp)
  150. request.time = timestamp_next_pkt
  151. packets.append(request)
  152. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  153. # Store timestamp of first packet (for attack label)
  154. if pkt_num == 1:
  155. self.attack_start_utime = packets[0].time
  156. elif pkt_num % BUFFER_SIZE == 0:
  157. last_packet = packets[-1]
  158. packets = sorted(packets, key=lambda pkt: pkt.time)
  159. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  160. packets = []
  161. if len(packets) > 0:
  162. packets = sorted(packets, key=lambda pkt: pkt.time)
  163. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  164. # Store timestamp of last packet
  165. self.attack_end_utime = last_packet.time
  166. # return packets sorted by packet time_sec_start
  167. # pkt_num+1: because pkt_num starts at 0
  168. return pkt_num + 1, path_attack_pcap