DDoSAttack.py 15 KB

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