DDoSAttack.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import logging
  2. from random import randint, uniform, choice #Aidmar choice
  3. from lea import Lea
  4. from scipy.stats import gamma
  5. from Attack import BaseAttack
  6. from Attack.AttackParameters import Parameter as Param
  7. from Attack.AttackParameters import ParameterTypes
  8. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  9. # noinspection PyPep8
  10. from scapy.layers.inet import IP, Ether, TCP, RandShort
  11. from collections import deque
  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. # Define allowed parameters and their type
  21. self.supported_params = {
  22. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  23. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  24. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  25. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  26. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  27. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  28. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  29. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  30. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  31. Param.PACKETS_LIMIT: ParameterTypes.TYPE_INTEGER_POSITIVE,
  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. self.add_param_value(Param.PACKETS_LIMIT, 0)
  64. def generate_attack_pcap(self):
  65. def update_timestamp(timestamp, pps, delay=0):
  66. """
  67. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  68. :return: Timestamp to be used for the next packet.
  69. """
  70. if delay == 0:
  71. # Calculate the request timestamp
  72. # A distribution to imitate the bursty behavior of traffic
  73. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 20, 5 / pps: 7, 10 / pps: 3})
  74. return timestamp + uniform(1 / pps, randomdelay.random())
  75. else:
  76. # Calculate the reply timestamp
  77. randomdelay = Lea.fromValFreqsDict({2 * delay: 70, 3 * delay: 20, 5 * delay: 7, 10 * delay: 3})
  78. return timestamp + uniform(1 / pps + delay, 1 / pps + randomdelay.random())
  79. def get_nth_random_element(*element_list):
  80. """
  81. Returns the n-th element of every list from an arbitrary number of given lists.
  82. For example, list1 contains IP addresses, list 2 contains MAC addresses. Use of this function ensures that
  83. the n-th IP address uses always the n-th MAC address.
  84. :param element_list: An arbitrary number of lists.
  85. :return: A tuple of the n-th element of every list.
  86. """
  87. range_max = min([len(x) for x in element_list])
  88. if range_max > 0: range_max -= 1
  89. n = randint(0, range_max)
  90. return tuple(x[n] for x in element_list)
  91. def index_increment(number: int, max: int):
  92. if number + 1 < max:
  93. return number + 1
  94. else:
  95. return 0
  96. def getIntervalPPS(complement_interval_pps, timestamp):
  97. """
  98. Gets the packet rate (pps) for a specific time interval.
  99. :param complement_interval_pps: an array of tuples (the last timestamp in the interval, the packet rate in the crresponding interval).
  100. :param timestamp: the timestamp at which the packet rate is required.
  101. :return: the corresponding packet rate (pps) .
  102. """
  103. for row in complement_interval_pps:
  104. if timestamp <= row[0]:
  105. return row[1]
  106. # In case the timestamp > capture max timestamp
  107. return complement_interval_pps[-1][1]
  108. def get_attacker_config(ipAddress: str):
  109. """
  110. Returns the attacker configuration depending on the IP address, this includes the port for the next
  111. attacking packet and the previously used (fixed) TTL value.
  112. :param ipAddress: The IP address of the attacker
  113. :return: A tuple consisting of (port, ttlValue)
  114. """
  115. # Determine port
  116. port = attacker_port_mapping.get(ipAddress)
  117. if port is not None: # use next port
  118. next_port = attacker_port_mapping.get(ipAddress) + 1
  119. if next_port > (2 ** 16 - 1):
  120. next_port = 1
  121. else: # generate starting port
  122. next_port = RandShort()
  123. attacker_port_mapping[ipAddress] = next_port
  124. # Determine TTL value
  125. ttl = attacker_ttl_mapping.get(ipAddress)
  126. if ttl is None: # determine TTL value
  127. is_invalid = True
  128. pos = ip_source_list.index(ipAddress)
  129. pos_max = len(gd)
  130. while is_invalid:
  131. ttl = int(round(gd[pos]))
  132. if 0 < ttl < 256: # validity check
  133. is_invalid = False
  134. else:
  135. pos = index_increment(pos, pos_max)
  136. attacker_ttl_mapping[ipAddress] = ttl
  137. # return port and TTL
  138. return next_port, ttl
  139. BUFFER_SIZE = 1000
  140. # Determine source IP and MAC address
  141. num_attackers = self.get_param_value(Param.NUMBER_ATTACKERS)
  142. if num_attackers is not None: # user supplied Param.NUMBER_ATTACKERS
  143. # The most used IP class in background traffic
  144. most_used_ip_class = self.statistics.process_db_query("most_used(ipClass)")
  145. # Create random attackers based on user input Param.NUMBER_ATTACKERS
  146. ip_source_list = self.generate_random_ipv4_address(most_used_ip_class, num_attackers)
  147. mac_source_list = self.generate_random_mac_address(num_attackers)
  148. else: # user did not supply Param.NUMBER_ATTACKS
  149. # use default values for IP_SOURCE/MAC_SOURCE or overwritten values
  150. # if user supplied any values for those params
  151. ip_source_list = self.get_param_value(Param.IP_SOURCE)
  152. mac_source_list = self.get_param_value(Param.MAC_SOURCE)
  153. # Initialize parameters
  154. packets = deque(maxlen=BUFFER_SIZE)
  155. port_source_list = self.get_param_value(Param.PORT_SOURCE)
  156. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  157. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  158. most_used_ip_address = self.statistics.get_most_used_ip_address()
  159. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  160. if pps == 0:
  161. result = self.statistics.process_db_query("SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='"+ip_destination+"';")
  162. if result:
  163. pps = num_attackers * result
  164. else:
  165. result = self.statistics.process_db_query("SELECT MAX(maxPktRate) FROM ip_statistics WHERE ipAddress='"+most_used_ip_address+"';")
  166. pps = num_attackers * result
  167. # Calculate complement packet rates of the background traffic for each interval
  168. attacker_pps = pps / num_attackers
  169. complement_interval_attacker_pps = self.statistics.calculate_complement_packet_rates(attacker_pps)
  170. # Check ip.src == ip.dst
  171. self.ip_src_dst_equal_check(ip_source_list, ip_destination)
  172. # Aidmar
  173. port_destination = self.get_param_value(Param.PORT_DESTINATION)
  174. if not port_destination: # user did not define port_dest
  175. port_destination = self.statistics.process_db_query(
  176. "SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "' ORDER BY portCount DESC LIMIT 1;")
  177. if not port_destination: # no port was retrieved
  178. port_destination = self.statistics.process_db_query(
  179. "SELECT portNumber FROM ip_ports WHERE portDirection='in' GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT 1;")
  180. if not port_destination:
  181. port_destination = max(1, str(RandShort()))
  182. attacker_port_mapping = {}
  183. attacker_ttl_mapping = {}
  184. # Gamma distribution parameters derived from MAWI 13.8G dataset
  185. alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
  186. gd = gamma.rvs(alpha, loc=loc, scale=beta, size=len(ip_source_list))
  187. path_attack_pcap = None
  188. # Aidmar
  189. timestamp_prv_reply, timestamp_confirm = 0, 0
  190. minDelay, maxDelay = self.get_reply_delay(ip_destination)
  191. victim_buffer = self.get_param_value(Param.VICTIM_BUFFER)
  192. # Aidmar
  193. pkts_num = self.get_param_value(Param.PACKETS_LIMIT)
  194. if pkts_num == 0:
  195. attack_duration = self.get_param_value(Param.ATTACK_DURATION)
  196. pkts_num = int(pps * attack_duration)
  197. source_win_sizes = self.statistics.process_db_query(
  198. "SELECT DISTINCT winSize FROM tcp_win ORDER BY RANDOM() LIMIT "+str(pkts_num)+";")
  199. destination_win_dist = self.statistics.get_win_distribution(ip_destination)
  200. if len(destination_win_dist) > 0:
  201. destination_win_prob_dict = Lea.fromValFreqsDict(destination_win_dist)
  202. destination_win_value = destination_win_prob_dict.random()
  203. else:
  204. destination_win_value = self.statistics.process_db_query("most_used(winSize)")
  205. # MSS that was used by IP destination in background traffic
  206. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  207. if mss_dst is None:
  208. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  209. replies_count = 0
  210. # Aidmar
  211. for attacker in range(num_attackers):
  212. # Timestamp
  213. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  214. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, attacker_pps)
  215. attacker_pkts_num = int(pkts_num / num_attackers) + randint(0,100)
  216. for pkt_num in range(attacker_pkts_num):
  217. # Build request package
  218. # Select one IP address and its corresponding MAC address
  219. (ip_source, mac_source) = get_nth_random_element(ip_source_list, mac_source_list)
  220. # Determine source port
  221. (port_source, ttl_value) = get_attacker_config(ip_source)
  222. request_ether = Ether(dst=mac_destination, src=mac_source)
  223. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  224. # Aidmar - random win size for each packet
  225. # request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0)
  226. source_win_size = choice(source_win_sizes)
  227. request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0, window=source_win_size)
  228. request = (request_ether / request_ip / request_tcp)
  229. request.time = timestamp_next_pkt
  230. # Append request
  231. packets.append(request)
  232. # Build reply package
  233. # Aidmar
  234. if replies_count <= victim_buffer:
  235. reply_ether = Ether(src=mac_destination, dst=mac_source)
  236. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  237. reply_tcp = TCP(sport=port_destination, dport=port_source, seq=0, ack=1, flags='SA', window=destination_win_value,options=[('MSS', mss_dst)])
  238. reply = (reply_ether / reply_ip / reply_tcp)
  239. timestamp_reply = update_timestamp(timestamp_next_pkt, attacker_pps, minDelay)
  240. while (timestamp_reply <= timestamp_prv_reply):
  241. timestamp_reply = update_timestamp(timestamp_prv_reply, attacker_pps, minDelay)
  242. timestamp_prv_reply = timestamp_reply
  243. reply.time = timestamp_reply
  244. packets.append(reply)
  245. replies_count+=1
  246. attacker_pps = max(getIntervalPPS(complement_interval_attacker_pps, timestamp_next_pkt), (pps/num_attackers)/2)
  247. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, attacker_pps)
  248. # Store timestamp of first packet (for attack label)
  249. if pkt_num == 1:
  250. self.attack_start_utime = packets[0].time
  251. elif pkt_num % BUFFER_SIZE == 0: # every 1000 packets write them to the pcap file (append)
  252. last_packet = packets[-1]
  253. packets = sorted(packets, key=lambda pkt: pkt.time)
  254. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  255. packets = []
  256. if len(packets) > 0:
  257. packets = sorted(packets, key=lambda pkt: pkt.time)
  258. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  259. # Store timestamp of last packet
  260. self.attack_end_utime = last_packet.time
  261. # return packets sorted by packet time_sec_start
  262. # pkt_num+1: because pkt_num starts at 0
  263. return pkt_num + 1, path_attack_pcap