3
0

DDoSAttack.py 15 KB

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