DDoSAttack.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. num_attackers = min(len(ip_source_list), len(mac_source_list))
  86. # Initialize parameters
  87. self.packets = col.deque(maxlen=buffer_size)
  88. # FIXME: why is port_source_list never used?
  89. port_source_list = self.get_param_value(atkParam.Parameter.PORT_SOURCE)
  90. mac_destination = self.get_param_value(atkParam.Parameter.MAC_DESTINATION)
  91. ip_destination = self.get_param_value(atkParam.Parameter.IP_DESTINATION)
  92. most_used_ip_address = self.statistics.get_most_used_ip_address()
  93. pps = self.get_param_value(atkParam.Parameter.PACKETS_PER_SECOND)
  94. if pps == 0:
  95. result = self.statistics.process_db_query(
  96. "SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='" + ip_destination + "';")
  97. if result is not None and not 0:
  98. pps = num_attackers * result
  99. else:
  100. result = self.statistics.process_db_query(
  101. "SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='" + most_used_ip_address + "';")
  102. pps = num_attackers * result
  103. # Calculate complement packet rates of the background traffic for each interval
  104. attacker_pps = pps / num_attackers
  105. complement_interval_attacker_pps = self.statistics.calculate_complement_packet_rates(attacker_pps)
  106. # Check ip.src == ip.dst
  107. self.ip_src_dst_equal_check(ip_source_list, ip_destination)
  108. port_destination = self.get_param_value(atkParam.Parameter.PORT_DESTINATION)
  109. if not port_destination: # user did not define port_dest
  110. port_destination = self.statistics.process_db_query(
  111. "SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination +
  112. "' AND portCount==(SELECT MAX(portCount) FROM ip_ports WHERE portDirection='in' AND ipAddress='" +
  113. ip_destination + "');")
  114. if not port_destination: # no port was retrieved
  115. port_destination = self.statistics.process_db_query(
  116. "SELECT portNumber FROM (SELECT portNumber, SUM(portCount) as occ FROM ip_ports WHERE "
  117. "portDirection='in' GROUP BY portNumber ORDER BY occ DESC) WHERE occ=(SELECT SUM(portCount) "
  118. "FROM ip_ports WHERE portDirection='in' GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT 1);")
  119. if not port_destination:
  120. port_destination = max(1, int(inet.RandShort()))
  121. port_destination = Util.handle_most_used_outputs(port_destination)
  122. self.path_attack_pcap = None
  123. min_delay, max_delay = self.get_reply_delay(ip_destination)
  124. victim_buffer = self.get_param_value(atkParam.Parameter.VICTIM_BUFFER)
  125. attack_duration = self.get_param_value(atkParam.Parameter.ATTACK_DURATION)
  126. pkts_num = int(pps * attack_duration)
  127. source_win_sizes = self.statistics.get_rnd_win_size(pkts_num)
  128. destination_win_dist = self.statistics.get_win_distribution(ip_destination)
  129. if len(destination_win_dist) > 0:
  130. destination_win_prob_dict = lea.Lea.fromValFreqsDict(destination_win_dist)
  131. destination_win_value = destination_win_prob_dict.random()
  132. else:
  133. destination_win_value = self.statistics.process_db_query("most_used(winSize)")
  134. destination_win_value = Util.handle_most_used_outputs(destination_win_value)
  135. # MSS that was used by IP destination in background traffic
  136. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  137. if mss_dst is None:
  138. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  139. mss_dst = Util.handle_most_used_outputs(mss_dst)
  140. timestamps_tuples = []
  141. previous_attacker_port = []
  142. replies_count = 0
  143. self.total_pkt_num = 0
  144. # For each attacker, generate his own packets, then merge all packets
  145. for attacker in range(num_attackers):
  146. previous_attacker_port.append([])
  147. # Timestamp
  148. timestamp_next_pkt = self.get_param_value(atkParam.Parameter.INJECT_AT_TIMESTAMP)
  149. attack_ends_time = timestamp_next_pkt + attack_duration
  150. timestamp_next_pkt = rnd.uniform(timestamp_next_pkt, Util.update_timestamp(timestamp_next_pkt, attacker_pps))
  151. attacker_pkts_num = int(pkts_num / num_attackers) + rnd.randint(0, 100)
  152. timestamp_prv_reply = 0
  153. for pkt_num in range(attacker_pkts_num):
  154. # Stop the attack when it exceeds the duration
  155. if timestamp_next_pkt > attack_ends_time:
  156. break
  157. timestamps_tuples.append((timestamp_next_pkt, attacker+1, 0))
  158. timestamp_reply = Util.update_timestamp(timestamp_next_pkt, attacker_pps, min_delay)
  159. while timestamp_reply <= timestamp_prv_reply:
  160. timestamp_reply = Util.update_timestamp(timestamp_prv_reply, attacker_pps, min_delay)
  161. timestamp_prv_reply = timestamp_reply
  162. timestamps_tuples.append((timestamp_reply, 0, attacker+1))
  163. attacker_pps = max(Util.get_interval_pps(complement_interval_attacker_pps, timestamp_next_pkt),
  164. (pps / num_attackers) / 2)
  165. timestamp_next_pkt = Util.update_timestamp(timestamp_next_pkt, attacker_pps)
  166. timestamps_tuples.sort()
  167. self.attack_start_utime = timestamps_tuples[0][0]
  168. for timestamp in timestamps_tuples:
  169. if timestamp[1] != 0:
  170. attacker_id = timestamp[1]-1
  171. # Build request package
  172. # Select one IP address and its corresponding MAC address
  173. ip_source = ip_source_list[attacker_id]
  174. mac_source = mac_source_list[attacker_id]
  175. # Determine source port
  176. (port_source, ttl_value) = Util.get_attacker_config(ip_source_list, ip_source)
  177. previous_attacker_port[attacker_id].insert(0, port_source)
  178. request_ether = inet.Ether(dst=mac_destination, src=mac_source)
  179. request_ip = inet.IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  180. # Random win size for each packet
  181. source_win_size = rnd.choice(source_win_sizes)
  182. request_tcp = inet.TCP(sport=port_source, dport=port_destination, flags='S', ack=0,
  183. window=source_win_size)
  184. request = (request_ether / request_ip / request_tcp)
  185. request.time = timestamp[0]
  186. # Append request
  187. self.packets.append(request)
  188. self.total_pkt_num += 1
  189. else:
  190. # Build reply package
  191. if replies_count <= victim_buffer:
  192. attacker_id = timestamp[2]-1
  193. reply_ether = inet.Ether(src=mac_destination, dst=mac_source_list[attacker_id])
  194. reply_ip = inet.IP(src=ip_destination, dst=ip_source_list[attacker_id], flags='DF')
  195. reply_tcp = inet.TCP(sport=port_destination, dport=previous_attacker_port[attacker_id].pop(), seq=0,
  196. ack=1, flags='SA', window=destination_win_value, options=[('MSS', mss_dst)])
  197. reply = (reply_ether / reply_ip / reply_tcp)
  198. reply.time = timestamp[0]
  199. self.packets.append(reply)
  200. replies_count += 1
  201. self.total_pkt_num += 1
  202. # every 1000 packets write them to the pcap file (append)
  203. if (self.total_pkt_num > 0) and (self.total_pkt_num % buffer_size == 0) and (len(self.packets) > 0):
  204. self.last_packet = self.packets[-1]
  205. self.attack_end_utime = self.last_packet.time
  206. self.packets = sorted(self.packets, key=lambda pkt: pkt.time)
  207. self.path_attack_pcap = self.write_attack_pcap(self.packets, True, self.path_attack_pcap)
  208. self.packets = []
  209. def generate_attack_pcap(self):
  210. if len(self.packets) > 0:
  211. self.packets = sorted(self.packets, key=lambda pkt: pkt.time)
  212. self.path_attack_pcap = self.write_attack_pcap(self.packets, True, self.path_attack_pcap)
  213. self.last_packet = self.packets[-1]
  214. # Store timestamp of last packet
  215. self.attack_end_utime = self.last_packet.time
  216. # Return packets sorted by packet time_sec_start
  217. # pkt_num+1: because pkt_num starts at 0
  218. return self.total_pkt_num, self.path_attack_pcap