DDoSAttack.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import logging
  2. from random import randint, uniform, choice #Aidmar choice
  3. #Aidmar
  4. import numpy as np
  5. from lea import Lea
  6. from scipy.stats import gamma
  7. from Attack import BaseAttack
  8. from Attack.AttackParameters import Parameter as Param
  9. from Attack.AttackParameters import ParameterTypes
  10. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  11. # noinspection PyPep8
  12. from scapy.layers.inet import IP, Ether, TCP, RandShort
  13. from collections import deque
  14. class DDoSAttack(BaseAttack.BaseAttack):
  15. # Aidmar - Metasploit DoS default PPS
  16. minDefaultPPS = 400
  17. maxDefaultPPS = 1400
  18. # Arbitrary values
  19. minDefaultBuffer = 1000
  20. maxDefaultBuffer = 2000
  21. def __init__(self, statistics, pcap_file_path):
  22. """
  23. Creates a new instance of the DDoS attack.
  24. :param statistics: A reference to the statistics class.
  25. """
  26. # Initialize attack
  27. super(DDoSAttack, self).__init__(statistics, "DDoS Attack", "Injects a DDoS attack'",
  28. "Resource Exhaustion")
  29. # Define allowed parameters and their type
  30. self.supported_params = {
  31. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  32. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  33. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  34. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  35. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  36. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  37. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  38. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  39. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  40. # Aidmar - use attack duration instead
  41. #Param.PACKETS_LIMIT: ParameterTypes.TYPE_INTEGER_POSITIVE,
  42. Param.NUMBER_ATTACKERS: ParameterTypes.TYPE_INTEGER_POSITIVE,
  43. # Aidmar
  44. Param.ATTACK_DURATION: ParameterTypes.TYPE_INTEGER_POSITIVE,
  45. Param.VICTIM_BUFFER: ParameterTypes.TYPE_INTEGER_POSITIVE
  46. }
  47. # PARAMETERS: initialize with default values
  48. # (values are overwritten if user specifies them)
  49. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  50. # attacker configuration
  51. num_attackers = randint(1, 16)
  52. # Aidmar
  53. # The most used IP class in background traffic
  54. most_used_ip_class = self.statistics.process_db_query("most_used(ipClass)")
  55. self.add_param_value(Param.IP_SOURCE, self.generate_random_ipv4_address(most_used_ip_class, num_attackers))
  56. self.add_param_value(Param.MAC_SOURCE, self.generate_random_mac_address(num_attackers))
  57. self.add_param_value(Param.PORT_SOURCE, str(RandShort()))
  58. # Aidmar
  59. #self.add_param_value(Param.PACKETS_PER_SECOND, randint(1, 64))
  60. self.add_param_value(Param.PACKETS_PER_SECOND, randint(self.minDefaultPPS, self.maxDefaultPPS))
  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. # Aidmar
  70. self.add_param_value(Param.VICTIM_BUFFER, randint(self.minDefaultBuffer,self.maxDefaultBuffer))
  71. # Aidmar - comment out
  72. """
  73. port_destination = self.statistics.process_db_query(
  74. "SELECT portNumber FROM ip_ports WHERE portDirection='in' ORDER BY RANDOM() LIMIT 1;")
  75. if port_destination is None:
  76. port_destination = str(RandShort())
  77. self.add_param_value(Param.PORT_DESTINATION, port_destination)
  78. """
  79. # Aidmar
  80. #self.add_param_value(Param.PACKETS_LIMIT, randint(1000, 5000))
  81. def generate_attack_pcap(self):
  82. def update_timestamp(timestamp, pps, maxdelay):
  83. """
  84. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  85. :return: Timestamp to be used for the next packet.
  86. """
  87. return timestamp + uniform(0.1 / pps, maxdelay)
  88. def get_nth_random_element(*element_list):
  89. """
  90. Returns the n-th element of every list from an arbitrary number of given lists.
  91. For example, list1 contains IP addresses, list 2 contains MAC addresses. Use of this function ensures that
  92. the n-th IP address uses always the n-th MAC address.
  93. :param element_list: An arbitrary number of lists.
  94. :return: A tuple of the n-th element of every list.
  95. """
  96. range_max = min([len(x) for x in element_list])
  97. if range_max > 0: range_max -= 1
  98. n = randint(0, range_max)
  99. return tuple(x[n] for x in element_list)
  100. def index_increment(number: int, max: int):
  101. if number + 1 < max:
  102. return number + 1
  103. else:
  104. return 0
  105. def get_attacker_config(ipAddress: str):
  106. """
  107. Returns the attacker configuration depending on the IP address, this includes the port for the next
  108. attacking packet and the previously used (fixed) TTL value.
  109. :param ipAddress: The IP address of the attacker
  110. :return: A tuple consisting of (port, ttlValue)
  111. """
  112. # Determine port
  113. port = attacker_port_mapping.get(ipAddress)
  114. if port is not None: # use next port
  115. next_port = attacker_port_mapping.get(ipAddress) + 1
  116. if next_port > (2 ** 16 - 1):
  117. next_port = 1
  118. else: # generate starting port
  119. next_port = RandShort()
  120. attacker_port_mapping[ipAddress] = next_port
  121. # Determine TTL value
  122. ttl = attacker_ttl_mapping.get(ipAddress)
  123. if ttl is None: # determine TTL value
  124. is_invalid = True
  125. pos = ip_source_list.index(ipAddress)
  126. pos_max = len(gd)
  127. while is_invalid:
  128. ttl = int(round(gd[pos]))
  129. if 0 < ttl < 256: # validity check
  130. is_invalid = False
  131. else:
  132. pos = index_increment(pos, pos_max)
  133. attacker_ttl_mapping[ipAddress] = ttl
  134. # return port and TTL
  135. return next_port, ttl
  136. BUFFER_SIZE = 1000
  137. # Determine source IP and MAC address
  138. num_attackers = self.get_param_value(Param.NUMBER_ATTACKERS)
  139. if num_attackers is not None: # user supplied Param.NUMBER_ATTACKERS
  140. # Create random attackers based on user input Param.NUMBER_ATTACKERS
  141. # Aidmar
  142. # The most used IP class in background traffic
  143. most_used_ip_class = self.statistics.process_db_query("most_used(ipClass)")
  144. ip_source_list = self.generate_random_ipv4_address(most_used_ip_class, num_attackers)
  145. mac_source_list = self.generate_random_mac_address(num_attackers)
  146. else: # user did not supply Param.NUMBER_ATTACKS
  147. # use default values for IP_SOURCE/MAC_SOURCE or overwritten values
  148. # if user supplied any values for those params
  149. ip_source_list = self.get_param_value(Param.IP_SOURCE)
  150. mac_source_list = self.get_param_value(Param.MAC_SOURCE)
  151. # Timestamp
  152. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  153. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  154. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 30, 5 / pps: 15, 10 / pps: 3})
  155. # Initialize parameters
  156. packets = deque(maxlen=BUFFER_SIZE)
  157. port_source_list = self.get_param_value(Param.PORT_SOURCE)
  158. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  159. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  160. port_destination = self.get_param_value(Param.PORT_DESTINATION)
  161. # Aidmar - Verify ip.src != ip.dst
  162. if ip_destination in ip_source_list:
  163. print("\nERROR: Invalid IP addresses; source IP is the same as destination IP: " + ip_destination + ".")
  164. import sys
  165. sys.exit(0)
  166. # Aidmar
  167. if not port_destination: # user did not define port_dest
  168. port_destination = self.statistics.process_db_query(
  169. "SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "' ORDER BY portCount DESC LIMIT 1;")
  170. if not port_destination: # no port was retrieved
  171. port_destination = self.statistics.process_db_query(
  172. "SELECT portNumber FROM ip_ports WHERE portDirection='in' GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT 1;")
  173. if not port_destination:
  174. port_destination = max(1, str(RandShort()))
  175. attacker_port_mapping = {}
  176. attacker_ttl_mapping = {}
  177. # Gamma distribution parameters derived from MAWI 13.8G dataset
  178. alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
  179. gd = gamma.rvs(alpha, loc=loc, scale=beta, size=len(ip_source_list))
  180. path_attack_pcap = None
  181. # Aidmar
  182. replies = []
  183. minDelay, maxDelay = self.get_reply_delay(ip_destination)
  184. victim_buffer = self.get_param_value(Param.VICTIM_BUFFER)
  185. # Aidmar
  186. #for pkt_num in range(self.get_param_value(Param.PACKETS_LIMIT)):
  187. attack_duration = self.get_param_value(Param.ATTACK_DURATION)
  188. pkts_num = int(pps * attack_duration)
  189. win_sizes = self.statistics.process_db_query(
  190. "SELECT winSize FROM tcp_syn_win ORDER BY RANDOM() LIMIT "+str(pkts_num)+";")
  191. # MSS that was used by IP destination in background traffic
  192. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  193. if mss_dst is None:
  194. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  195. for pkt_num in range(pkts_num):
  196. # Build request package
  197. # Select one IP address and its corresponding MAC address
  198. (ip_source, mac_source) = get_nth_random_element(ip_source_list, mac_source_list)
  199. # Determine source port
  200. (port_source, ttl_value) = get_attacker_config(ip_source)
  201. maxdelay = randomdelay.random()
  202. request_ether = Ether(dst=mac_destination, src=mac_source)
  203. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  204. # Aidmar - random win size for each packet
  205. # request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0)
  206. win_size = choice(win_sizes)
  207. request_tcp = TCP(sport=port_source, dport=port_destination, flags='S', ack=0, window=win_size)
  208. request = (request_ether / request_ip / request_tcp)
  209. request.time = timestamp_next_pkt
  210. # Build reply package
  211. # Aidmar
  212. if len(replies) <= victim_buffer:
  213. reply_ether = Ether(src=mac_destination, dst=mac_source)
  214. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  215. reply_tcp = TCP(sport=port_destination, dport=port_source, seq=0, ack=1, flags='SA', window=29200,options=[('MSS', mss_dst)])
  216. reply = (reply_ether / reply_ip / reply_tcp)
  217. timestamp_reply = timestamp_next_pkt + uniform(minDelay, maxDelay)
  218. if len(replies) > 0:
  219. last_reply_timestamp = replies[-1].time
  220. while timestamp_reply <= last_reply_timestamp:
  221. timestamp_reply = timestamp_reply + uniform(minDelay, maxDelay)
  222. reply.time = timestamp_reply
  223. replies.append(reply)
  224. # Aidmar
  225. # Append reply
  226. if replies:
  227. while timestamp_next_pkt >= replies[0].time:
  228. packets.append(replies[0])
  229. replies.remove(replies[0])
  230. if len(replies) == 0:
  231. break
  232. # Append request
  233. packets.append(request)
  234. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  235. # Store timestamp of first packet (for attack label)
  236. if pkt_num == 1:
  237. self.attack_start_utime = packets[0].time
  238. elif pkt_num % BUFFER_SIZE == 0: # every 1000 packets write them to the pcap file (append)
  239. last_packet = packets[-1]
  240. packets = sorted(packets, key=lambda pkt: pkt.time)
  241. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  242. packets = []
  243. # Requests are sent all, send all replies
  244. if pkt_num == pkts_num-1:
  245. for reply in replies:
  246. packets.append(reply)
  247. if len(packets) > 0:
  248. packets = sorted(packets, key=lambda pkt: pkt.time)
  249. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  250. # Store timestamp of last packet
  251. self.attack_end_utime = last_packet.time
  252. # return packets sorted by packet time_sec_start
  253. # pkt_num+1: because pkt_num starts at 0
  254. return pkt_num + 1, path_attack_pcap