DDoSAttack.py 15 KB

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