DDoSAttack.py 13 KB

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