DDoSAttack.py 13 KB

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