DDoSAttack.py 13 KB

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