DDoSAttack.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 = {
  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 = self.statistics.process_db_query("most_used(ipClass)")
  52. if isinstance(most_used_ip_class, list):
  53. most_used_ip_class.sort()
  54. most_used_ip_class = most_used_ip_class[0]
  55. self.add_param_value(Param.IP_SOURCE, self.generate_random_ipv4_address(most_used_ip_class, num_attackers))
  56. self.add_param_value(Param.MAC_SOURCE, self.generate_random_mac_address(num_attackers))
  57. self.add_param_value(Param.PORT_SOURCE, str(RandShort()))
  58. self.add_param_value(Param.PACKETS_PER_SECOND, 0)
  59. self.add_param_value(Param.ATTACK_DURATION, randint(5,30))
  60. # victim configuration
  61. random_ip_address = self.statistics.get_random_ip_address()
  62. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  63. destination_mac = self.statistics.get_mac_address(random_ip_address)
  64. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  65. destination_mac = self.generate_random_mac_address()
  66. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  67. self.add_param_value(Param.VICTIM_BUFFER, randint(1000,10000))
  68. def generate_attack_pcap(self):
  69. BUFFER_SIZE = 1000
  70. # Determine source IP and MAC address
  71. num_attackers = self.get_param_value(Param.NUMBER_ATTACKERS)
  72. if num_attackers is not None: # user supplied Param.NUMBER_ATTACKERS
  73. # The most used IP class in background traffic
  74. most_used_ip_class = handle_most_used_outputs(self.statistics.process_db_query("most_used(ipClass)"))
  75. # Create random attackers based on user input Param.NUMBER_ATTACKERS
  76. ip_source_list = self.generate_random_ipv4_address(most_used_ip_class, num_attackers)
  77. mac_source_list = self.generate_random_mac_address(num_attackers)
  78. else: # user did not supply Param.NUMBER_ATTACKS
  79. # use default values for IP_SOURCE/MAC_SOURCE or overwritten values
  80. # if user supplied any values for those params
  81. ip_source_list = self.get_param_value(Param.IP_SOURCE)
  82. mac_source_list = self.get_param_value(Param.MAC_SOURCE)
  83. num_attackers = len(ip_source_list)
  84. # Initialize parameters
  85. packets = deque(maxlen=BUFFER_SIZE)
  86. port_source_list = self.get_param_value(Param.PORT_SOURCE)
  87. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  88. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  89. most_used_ip_address = self.statistics.get_most_used_ip_address()
  90. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  91. if pps == 0:
  92. result = self.statistics.process_db_query("SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='"+ip_destination+"';")
  93. if result is not None and not 0:
  94. pps = num_attackers * result
  95. else:
  96. result = self.statistics.process_db_query("SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='"+most_used_ip_address+"';")
  97. pps = num_attackers * result
  98. # Calculate complement packet rates of the background traffic for each interval
  99. attacker_pps = pps / num_attackers
  100. complement_interval_attacker_pps = self.statistics.calculate_complement_packet_rates(attacker_pps)
  101. # Check ip.src == ip.dst
  102. self.ip_src_dst_equal_check(ip_source_list, ip_destination)
  103. port_destination = self.get_param_value(Param.PORT_DESTINATION)
  104. if not port_destination: # user did not define port_dest
  105. port_destination = self.statistics.process_db_query(
  106. "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 + "');")
  107. if not port_destination: # no port was retrieved
  108. port_destination = self.statistics.process_db_query(
  109. "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);")
  110. if not port_destination:
  111. port_destination = max(1, str(RandShort()))
  112. port_destination = handle_most_used_outputs(port_destination)
  113. attacker_port_mapping = {}
  114. attacker_ttl_mapping = {}
  115. # Gamma distribution parameters derived from MAWI 13.8G dataset
  116. alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
  117. gd = gamma.rvs(alpha, loc=loc, scale=beta, size=len(ip_source_list))
  118. path_attack_pcap = None
  119. timestamp_prv_reply, timestamp_confirm = 0, 0
  120. minDelay, maxDelay = self.get_reply_delay(ip_destination)
  121. victim_buffer = self.get_param_value(Param.VICTIM_BUFFER)
  122. attack_duration = self.get_param_value(Param.ATTACK_DURATION)
  123. pkts_num = int(pps * attack_duration)
  124. source_win_sizes = self.statistics.get_rnd_win_size(pkts_num)
  125. destination_win_dist = self.statistics.get_win_distribution(ip_destination)
  126. if len(destination_win_dist) > 0:
  127. destination_win_prob_dict = Lea.fromValFreqsDict(destination_win_dist)
  128. destination_win_value = destination_win_prob_dict.random()
  129. else:
  130. destination_win_value = self.statistics.process_db_query("most_used(winSize)")
  131. destination_win_value = handle_most_used_outputs(destination_win_value)
  132. # MSS that was used by IP destination in background traffic
  133. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  134. if mss_dst is None:
  135. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  136. mss_dst = handle_most_used_outputs(mss_dst)
  137. replies_count = 0
  138. total_pkt_num = 0
  139. # For each attacker, generate his own packets, then merge all packets
  140. for attacker in range(num_attackers):
  141. # Timestamp
  142. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  143. attack_ends_time = timestamp_next_pkt + attack_duration
  144. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, attacker_pps)
  145. attacker_pkts_num = int(pkts_num / num_attackers) + randint(0,100)
  146. for pkt_num in range(attacker_pkts_num):
  147. # Stop the attack when it exceeds the duration
  148. if timestamp_next_pkt > attack_ends_time:
  149. break
  150. # Build request package
  151. # Select one IP address and its corresponding MAC address
  152. (ip_source, mac_source) = get_nth_random_element(ip_source_list, mac_source_list)
  153. # Determine source port
  154. (port_source, ttl_value) = get_attacker_config(ip_source_list ,ip_source)
  155. request_ether = Ether(dst=mac_destination, src=mac_source)
  156. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  157. # Random win size for each packet
  158. source_win_size = choice(source_win_sizes)
  159. request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0, window=source_win_size)
  160. request = (request_ether / request_ip / request_tcp)
  161. request.time = timestamp_next_pkt
  162. # Append request
  163. packets.append(request)
  164. total_pkt_num +=1
  165. # Build reply package
  166. if replies_count <= victim_buffer:
  167. reply_ether = Ether(src=mac_destination, dst=mac_source)
  168. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  169. reply_tcp = TCP(sport=port_destination, dport=port_source, seq=0, ack=1, flags='SA', window=destination_win_value,options=[('MSS', mss_dst)])
  170. reply = (reply_ether / reply_ip / reply_tcp)
  171. timestamp_reply = update_timestamp(timestamp_next_pkt, attacker_pps, minDelay)
  172. while (timestamp_reply <= timestamp_prv_reply):
  173. timestamp_reply = update_timestamp(timestamp_prv_reply, attacker_pps, minDelay)
  174. timestamp_prv_reply = timestamp_reply
  175. reply.time = timestamp_reply
  176. packets.append(reply)
  177. replies_count+=1
  178. total_pkt_num += 1
  179. attacker_pps = max(get_interval_pps(complement_interval_attacker_pps, timestamp_next_pkt), (pps / num_attackers) / 2)
  180. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, attacker_pps)
  181. # Store timestamp of first packet (for attack label)
  182. if total_pkt_num <= 2 :
  183. self.attack_start_utime = packets[0].time
  184. elif pkt_num % BUFFER_SIZE == 0: # every 1000 packets write them to the pcap file (append)
  185. last_packet = packets[-1]
  186. packets = sorted(packets, key=lambda pkt: pkt.time)
  187. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  188. packets = []
  189. if len(packets) > 0:
  190. packets = sorted(packets, key=lambda pkt: pkt.time)
  191. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  192. # Store timestamp of last packet
  193. self.attack_end_utime = last_packet.time
  194. # Return packets sorted by packet time_sec_start
  195. # pkt_num+1: because pkt_num starts at 0
  196. return total_pkt_num , path_attack_pcap