DDoSAttack.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import logging
  2. from random import randint, choice
  3. from lea import Lea
  4. from collections import deque
  5. from scipy.stats import gamma
  6. from scapy.layers.inet import IP, Ether, TCP, RandShort
  7. from Attack import BaseAttack
  8. from Attack.AttackParameters import Parameter as Param
  9. from Attack.AttackParameters import ParameterTypes
  10. from ID2TLib.Utility import update_timestamp, get_interval_pps, get_nth_random_element, index_increment, \
  11. handle_most_used_outputs, get_attacker_config
  12. from ID2TLib.Utility import update_timestamp, get_interval_pps, get_nth_random_element
  13. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  14. # noinspection PyPep8
  15. class DDoSAttack(BaseAttack.BaseAttack):
  16. def __init__(self):
  17. """
  18. Creates a new instance of the DDoS attack.
  19. """
  20. # Initialize attack
  21. super(DDoSAttack, self).__init__("DDoS Attack", "Injects a DDoS attack'",
  22. "Resource Exhaustion")
  23. # Define allowed parameters and their type
  24. self.supported_params.update({
  25. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  26. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  27. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  28. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  29. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  30. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  31. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  32. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  33. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  34. Param.NUMBER_ATTACKERS: ParameterTypes.TYPE_INTEGER_POSITIVE,
  35. Param.ATTACK_DURATION: ParameterTypes.TYPE_INTEGER_POSITIVE,
  36. Param.VICTIM_BUFFER: ParameterTypes.TYPE_INTEGER_POSITIVE
  37. })
  38. def init_params(self):
  39. """
  40. Initialize the parameters of this attack using the user supplied command line parameters.
  41. Use the provided statistics to calculate default parameters and to process user
  42. supplied queries.
  43. :param statistics: Reference to a statistics object.
  44. """
  45. # PARAMETERS: initialize with default values
  46. # (values are overwritten if user specifies them)
  47. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  48. # attacker configuration
  49. num_attackers = randint(1, 16)
  50. # The most used IP class in background traffic
  51. most_used_ip_class = handle_most_used_outputs(self.statistics.process_db_query("most_used(ipClass)"))
  52. self.add_param_value(Param.IP_SOURCE, self.generate_random_ipv4_address(most_used_ip_class, num_attackers))
  53. self.add_param_value(Param.MAC_SOURCE, self.generate_random_mac_address(num_attackers))
  54. self.add_param_value(Param.PORT_SOURCE, str(RandShort()))
  55. self.add_param_value(Param.PACKETS_PER_SECOND, 0)
  56. self.add_param_value(Param.ATTACK_DURATION, randint(5,30))
  57. # victim configuration
  58. random_ip_address = self.statistics.get_random_ip_address()
  59. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  60. destination_mac = self.statistics.get_mac_address(random_ip_address)
  61. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  62. destination_mac = self.generate_random_mac_address()
  63. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  64. self.add_param_value(Param.VICTIM_BUFFER, randint(1000,10000))
  65. def generate_attack_pcap(self):
  66. BUFFER_SIZE = 1000
  67. # Determine source IP and MAC address
  68. num_attackers = self.get_param_value(Param.NUMBER_ATTACKERS)
  69. if num_attackers is not None: # user supplied Param.NUMBER_ATTACKERS
  70. # The most used IP class in background traffic
  71. most_used_ip_class = handle_most_used_outputs(self.statistics.process_db_query("most_used(ipClass)"))
  72. # Create random attackers based on user input Param.NUMBER_ATTACKERS
  73. ip_source_list = self.generate_random_ipv4_address(most_used_ip_class, num_attackers)
  74. mac_source_list = self.generate_random_mac_address(num_attackers)
  75. else: # user did not supply Param.NUMBER_ATTACKS
  76. # use default values for IP_SOURCE/MAC_SOURCE or overwritten values
  77. # if user supplied any values for those params
  78. ip_source_list = self.get_param_value(Param.IP_SOURCE)
  79. mac_source_list = self.get_param_value(Param.MAC_SOURCE)
  80. num_attackers = len(ip_source_list)
  81. # Initialize parameters
  82. packets = deque(maxlen=BUFFER_SIZE)
  83. port_source_list = self.get_param_value(Param.PORT_SOURCE)
  84. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  85. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  86. most_used_ip_address = self.statistics.get_most_used_ip_address()
  87. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  88. if pps == 0:
  89. result = self.statistics.process_db_query("SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='"+ip_destination+"';")
  90. if result is not None and not 0:
  91. pps = num_attackers * result
  92. else:
  93. result = self.statistics.process_db_query("SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='"+most_used_ip_address+"';")
  94. pps = num_attackers * result
  95. # Calculate complement packet rates of the background traffic for each interval
  96. attacker_pps = pps / num_attackers
  97. complement_interval_attacker_pps = self.statistics.calculate_complement_packet_rates(attacker_pps)
  98. # Check ip.src == ip.dst
  99. self.ip_src_dst_equal_check(ip_source_list, ip_destination)
  100. port_destination = self.get_param_value(Param.PORT_DESTINATION)
  101. if not port_destination: # user did not define port_dest
  102. port_destination = self.statistics.process_db_query(
  103. "SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "' AND portCount==(SELECT MAX(portCount) FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "');")
  104. if not port_destination: # no port was retrieved
  105. port_destination = self.statistics.process_db_query(
  106. "SELECT portNumber FROM (SELECT portNumber, SUM(portCount) as occ FROM ip_ports WHERE portDirection='in' GROUP BY portNumber ORDER BY occ DESC) WHERE occ=(SELECT SUM(portCount) FROM ip_ports WHERE portDirection='in' GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT 1);")
  107. if not port_destination:
  108. port_destination = max(1, str(RandShort()))
  109. port_destination = handle_most_used_outputs(port_destination)
  110. attacker_port_mapping = {}
  111. attacker_ttl_mapping = {}
  112. # Gamma distribution parameters derived from MAWI 13.8G dataset
  113. alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
  114. gd = gamma.rvs(alpha, loc=loc, scale=beta, size=len(ip_source_list))
  115. path_attack_pcap = None
  116. timestamp_prv_reply, timestamp_confirm = 0, 0
  117. minDelay, maxDelay = self.get_reply_delay(ip_destination)
  118. victim_buffer = self.get_param_value(Param.VICTIM_BUFFER)
  119. attack_duration = self.get_param_value(Param.ATTACK_DURATION)
  120. pkts_num = int(pps * attack_duration)
  121. source_win_sizes = self.statistics.get_rnd_win_size(pkts_num)
  122. destination_win_dist = self.statistics.get_win_distribution(ip_destination)
  123. if len(destination_win_dist) > 0:
  124. destination_win_prob_dict = Lea.fromValFreqsDict(destination_win_dist)
  125. destination_win_value = destination_win_prob_dict.random()
  126. else:
  127. destination_win_value = self.statistics.process_db_query("most_used(winSize)")
  128. destination_win_value = handle_most_used_outputs(destination_win_value)
  129. # MSS that was used by IP destination in background traffic
  130. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  131. if mss_dst is None:
  132. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  133. mss_dst = handle_most_used_outputs(mss_dst)
  134. replies_count = 0
  135. total_pkt_num = 0
  136. # For each attacker, generate his own packets, then merge all packets
  137. for attacker in range(num_attackers):
  138. # Timestamp
  139. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  140. attack_ends_time = timestamp_next_pkt + attack_duration
  141. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, attacker_pps)
  142. attacker_pkts_num = int(pkts_num / num_attackers) + randint(0,100)
  143. for pkt_num in range(attacker_pkts_num):
  144. # Stop the attack when it exceeds the duration
  145. if timestamp_next_pkt > attack_ends_time:
  146. break
  147. # Build request package
  148. # Select one IP address and its corresponding MAC address
  149. (ip_source, mac_source) = get_nth_random_element(ip_source_list, mac_source_list)
  150. # Determine source port
  151. (port_source, ttl_value) = get_attacker_config(ip_source_list ,ip_source)
  152. request_ether = Ether(dst=mac_destination, src=mac_source)
  153. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  154. # Random win size for each packet
  155. source_win_size = choice(source_win_sizes)
  156. request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0, window=source_win_size)
  157. request = (request_ether / request_ip / request_tcp)
  158. request.time = timestamp_next_pkt
  159. # Append request
  160. packets.append(request)
  161. total_pkt_num +=1
  162. # Build reply package
  163. if replies_count <= victim_buffer:
  164. reply_ether = Ether(src=mac_destination, dst=mac_source)
  165. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  166. reply_tcp = TCP(sport=port_destination, dport=port_source, seq=0, ack=1, flags='SA', window=destination_win_value,options=[('MSS', mss_dst)])
  167. reply = (reply_ether / reply_ip / reply_tcp)
  168. timestamp_reply = update_timestamp(timestamp_next_pkt, attacker_pps, minDelay)
  169. while (timestamp_reply <= timestamp_prv_reply):
  170. timestamp_reply = update_timestamp(timestamp_prv_reply, attacker_pps, minDelay)
  171. timestamp_prv_reply = timestamp_reply
  172. reply.time = timestamp_reply
  173. packets.append(reply)
  174. replies_count+=1
  175. total_pkt_num += 1
  176. attacker_pps = max(get_interval_pps(complement_interval_attacker_pps, timestamp_next_pkt), (pps / num_attackers) / 2)
  177. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, attacker_pps)
  178. # Store timestamp of first packet (for attack label)
  179. if total_pkt_num <= 2 :
  180. self.attack_start_utime = packets[0].time
  181. elif pkt_num % BUFFER_SIZE == 0: # every 1000 packets write them to the pcap file (append)
  182. last_packet = packets[-1]
  183. packets = sorted(packets, key=lambda pkt: pkt.time)
  184. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  185. packets = []
  186. if len(packets) > 0:
  187. packets = sorted(packets, key=lambda pkt: pkt.time)
  188. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  189. # Store timestamp of last packet
  190. self.attack_end_utime = last_packet.time
  191. # Return packets sorted by packet time_sec_start
  192. # pkt_num+1: because pkt_num starts at 0
  193. return total_pkt_num , path_attack_pcap