DDoSAttack.py 14 KB

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