PortscanAttack.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import logging
  2. import csv
  3. from random import shuffle, randint, choice, uniform
  4. from lea import Lea
  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
  11. import numpy as np
  12. class PortscanAttack(BaseAttack.BaseAttack):
  13. # Aidmar
  14. def get_ports_from_nmap_service_dst(self, ports_num):
  15. """
  16. Read the most ports_num frequently open ports from nmap-service-tcp file to be used in the port scan.
  17. :return: Ports numbers to be used as default destination ports or default open ports in the port scan.
  18. """
  19. ports_dst = []
  20. spamreader = csv.reader(open('resources/nmap-services-tcp.csv', 'rt'), delimiter=',')
  21. for count in range(ports_num):
  22. # escape first row (header)
  23. next(spamreader)
  24. # save ports numbers
  25. ports_dst.append(next(spamreader)[0])
  26. # shuffle ports numbers partially
  27. if(ports_num==1000): # used for port.dst
  28. temp_array = [[0 for i in range(10)] for i in range(100)]
  29. port_dst_shuffled = []
  30. for count in range(0, 9):
  31. temp_array[count] = ports_dst[count * 100:count * 100 + 99]
  32. shuffle(temp_array[count])
  33. port_dst_shuffled += temp_array[count]
  34. else: # used for port.open
  35. shuffle(ports_dst)
  36. port_dst_shuffled = ports_dst
  37. return port_dst_shuffled
  38. def __init__(self, statistics, pcap_file_path):
  39. """
  40. Creates a new instance of the PortscanAttack.
  41. :param statistics: A reference to the statistics class.
  42. """
  43. # Initialize attack
  44. super(PortscanAttack, self).__init__(statistics, "Portscan Attack", "Injects a nmap 'regular scan'",
  45. "Scanning/Probing")
  46. # Define allowed parameters and their type
  47. self.supported_params = {
  48. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  49. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  50. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  51. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  52. Param.PORT_OPEN: ParameterTypes.TYPE_PORT,
  53. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  54. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  55. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  56. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  57. Param.PORT_DEST_SHUFFLE: ParameterTypes.TYPE_BOOLEAN,
  58. Param.PORT_DEST_ORDER_DESC: ParameterTypes.TYPE_BOOLEAN,
  59. Param.IP_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN,
  60. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  61. Param.PORT_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN
  62. }
  63. # PARAMETERS: initialize with default values
  64. # (values are overwritten if user specifies them)
  65. most_used_ip_address = self.statistics.get_most_used_ip_address()
  66. if isinstance(most_used_ip_address, list):
  67. most_used_ip_address = most_used_ip_address[0]
  68. self.add_param_value(Param.IP_SOURCE, most_used_ip_address)
  69. self.add_param_value(Param.IP_SOURCE_RANDOMIZE, 'False')
  70. self.add_param_value(Param.MAC_SOURCE, self.statistics.get_mac_address(most_used_ip_address))
  71. random_ip_address = self.statistics.get_random_ip_address()
  72. # Aidmar - ip-dst should be valid and not equal to ip.src
  73. while not self.is_valid_ip_address(random_ip_address) or random_ip_address==most_used_ip_address:
  74. random_ip_address = self.statistics.get_random_ip_address()
  75. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  76. destination_mac = self.statistics.get_mac_address(random_ip_address)
  77. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  78. destination_mac = self.generate_random_mac_address()
  79. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  80. self.add_param_value(Param.PORT_DESTINATION, self.get_ports_from_nmap_service_dst(1000))
  81. # Temporal value to be changed later accordint to the destination host open ports
  82. self.add_param_value(Param.PORT_OPEN, '1')
  83. self.add_param_value(Param.PORT_DEST_SHUFFLE, 'False')
  84. self.add_param_value(Param.PORT_DEST_ORDER_DESC, 'False')
  85. self.add_param_value(Param.PORT_SOURCE, randint(1024, 65535))
  86. self.add_param_value(Param.PORT_SOURCE_RANDOMIZE, 'False')
  87. self.add_param_value(Param.PACKETS_PER_SECOND,
  88. (self.statistics.get_pps_sent(most_used_ip_address) +
  89. self.statistics.get_pps_received(most_used_ip_address)) / 2)
  90. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  91. def generate_attack_pcap(self):
  92. def update_timestamp(timestamp, pps, delay=0):
  93. """
  94. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  95. :return: Timestamp to be used for the next packet.
  96. """
  97. if delay == 0:
  98. # Calculate request timestamp
  99. # To imitate the bursty behavior of traffic
  100. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 20, 5 / pps: 7, 10 / pps: 3})
  101. return timestamp + uniform(1/pps , randomdelay.random())
  102. else:
  103. # Calculate reply timestamp
  104. randomdelay = Lea.fromValFreqsDict({2*delay: 70, 3*delay: 20, 5*delay: 7, 10*delay: 3})
  105. return timestamp + uniform(1 / pps + delay, 1 / pps + randomdelay.random())
  106. # Aidmar
  107. def getIntervalPPS(complement_interval_pps, timestamp):
  108. """
  109. Gets the packet rate (pps) for a specific time interval.
  110. :param complement_interval_pps: an array of tuples (the last timestamp in the interval, the packet rate in the crresponding interval).
  111. :param timestamp: the timestamp at which the packet rate is required.
  112. :return: the corresponding packet rate (pps) .
  113. """
  114. for row in complement_interval_pps:
  115. if timestamp<=row[0]:
  116. return row[1]
  117. return complement_interval_pps[-1][1] # in case the timstamp > capture max timestamp
  118. mac_source = self.get_param_value(Param.MAC_SOURCE)
  119. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  120. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  121. # Aidmar - calculate complement packet rates of the background traffic for each interval
  122. complement_interval_pps = self.statistics.calculate_complement_packet_rates(pps)
  123. # Determine ports
  124. dest_ports = self.get_param_value(Param.PORT_DESTINATION)
  125. if self.get_param_value(Param.PORT_DEST_ORDER_DESC):
  126. dest_ports.reverse()
  127. elif self.get_param_value(Param.PORT_DEST_SHUFFLE):
  128. shuffle(dest_ports)
  129. if self.get_param_value(Param.PORT_SOURCE_RANDOMIZE):
  130. sport = randint(1, 65535)
  131. else:
  132. sport = self.get_param_value(Param.PORT_SOURCE)
  133. # Timestamp
  134. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  135. # store start time of attack
  136. self.attack_start_utime = timestamp_next_pkt
  137. timestamp_prv_reply, timestamp_confirm = 0,0
  138. # Initialize parameters
  139. packets = []
  140. ip_source = self.get_param_value(Param.IP_SOURCE)
  141. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  142. # Aidmar - check ip.src == ip.dst
  143. self.ip_src_dst_equal_check(ip_source, ip_destination)
  144. # Aidmar
  145. # Select open ports
  146. ports_open = self.get_param_value(Param.PORT_OPEN)
  147. if ports_open == 1: # user did not specify open ports
  148. # the ports that were already used by ip.dst (direction in) in the background traffic are open ports
  149. ports_used_by_ip_dst = self.statistics.process_db_query(
  150. "SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "'")
  151. if ports_used_by_ip_dst:
  152. ports_open = ports_used_by_ip_dst
  153. else: # if no ports were retrieved from database
  154. ports_open = self.statistics.process_db_query(
  155. "SELECT portNumber FROM ip_ports GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT "+str(randint(1,10)))
  156. # in case of one open port, convert ports_open to array
  157. if not isinstance(ports_open, list):
  158. ports_open = [ports_open]
  159. # Aidmar
  160. # Set MSS (Maximum Segment Size) based on MSS distribution of IP address
  161. source_mss_dist = self.statistics.get_mss_distribution(ip_source)
  162. if len(source_mss_dist) > 0:
  163. source_mss_prob_dict = Lea.fromValFreqsDict(source_mss_dist)
  164. source_mss_value = source_mss_prob_dict.random()
  165. else:
  166. source_mss_value = self.statistics.process_db_query("most_used(mssValue)")
  167. destination_mss_dist = self.statistics.get_mss_distribution(ip_destination)
  168. if len(destination_mss_dist) > 0:
  169. destination_mss_prob_dict = Lea.fromValFreqsDict(destination_mss_dist)
  170. destination_mss_value = destination_mss_prob_dict.random()
  171. else:
  172. destination_mss_value = self.statistics.process_db_query("most_used(mssValue)")
  173. # Set TTL based on TTL distribution of IP address
  174. source_ttl_dist = self.statistics.get_ttl_distribution(ip_source)
  175. if len(source_ttl_dist) > 0:
  176. source_ttl_prob_dict = Lea.fromValFreqsDict(source_ttl_dist)
  177. source_ttl_value = source_ttl_prob_dict.random()
  178. else:
  179. source_ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  180. destination_ttl_dist = self.statistics.get_ttl_distribution(ip_destination)
  181. if len(destination_ttl_dist) > 0:
  182. destination_ttl_prob_dict = Lea.fromValFreqsDict(destination_ttl_dist)
  183. destination_ttl_value = destination_ttl_prob_dict.random()
  184. else:
  185. destination_ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  186. # Aidmar
  187. # Set Window Size based on Window Size distribution of IP address
  188. source_win_dist = self.statistics.get_win_distribution(ip_source)
  189. if len(source_win_dist) > 0:
  190. source_win_prob_dict = Lea.fromValFreqsDict(source_win_dist)
  191. source_win_value = source_win_prob_dict.random()
  192. else:
  193. source_win_value = self.statistics.process_db_query("most_used(winSize)")
  194. destination_win_dist = self.statistics.get_win_distribution(ip_destination)
  195. if len(destination_win_dist) > 0:
  196. destination_win_prob_dict = Lea.fromValFreqsDict(destination_win_dist)
  197. destination_win_value = destination_win_prob_dict.random()
  198. else:
  199. destination_win_value = self.statistics.process_db_query("most_used(winSize)")
  200. # Aidmar
  201. minDelay,maxDelay = self.get_reply_delay(ip_destination)
  202. for dport in dest_ports:
  203. # Parameters changing each iteration
  204. if self.get_param_value(Param.IP_SOURCE_RANDOMIZE) and isinstance(ip_source, list):
  205. ip_source = choice(ip_source)
  206. # 1) Build request package
  207. request_ether = Ether(src=mac_source, dst=mac_destination)
  208. request_ip = IP(src=ip_source, dst=ip_destination, ttl=source_ttl_value)
  209. # Aidmar - random src port for each packet
  210. sport = randint(1, 65535)
  211. request_tcp = TCP(sport=sport, dport=dport, window= source_win_value, flags='S', options=[('MSS', source_mss_value)])
  212. request = (request_ether / request_ip / request_tcp)
  213. request.time = timestamp_next_pkt
  214. # Append request
  215. packets.append(request)
  216. # 2) Build reply (for open ports) package
  217. if dport in ports_open: # destination port is OPEN
  218. reply_ether = Ether(src=mac_destination, dst=mac_source)
  219. reply_ip = IP(src=ip_destination, dst=ip_source, ttl=destination_ttl_value, flags='DF')
  220. reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=destination_win_value,
  221. options=[('MSS', destination_mss_value)])
  222. reply = (reply_ether / reply_ip / reply_tcp)
  223. timestamp_reply = update_timestamp(timestamp_next_pkt,pps,minDelay)
  224. while (timestamp_reply <= timestamp_prv_reply):
  225. timestamp_reply = update_timestamp(timestamp_prv_reply,pps,minDelay)
  226. timestamp_prv_reply = timestamp_reply
  227. reply.time = timestamp_reply
  228. packets.append(reply)
  229. # requester confirms
  230. confirm_ether = request_ether
  231. confirm_ip = request_ip
  232. confirm_tcp = TCP(sport=sport, dport=dport, seq=1, window=0, flags='R')
  233. confirm = (confirm_ether / confirm_ip / confirm_tcp)
  234. # Aidmar - edit name timestamp_confirm
  235. timestamp_confirm = update_timestamp(timestamp_reply,pps,minDelay)
  236. confirm.time = timestamp_confirm
  237. packets.append(confirm)
  238. # else: destination port is NOT OPEN -> no reply is sent by target
  239. # Aidmar
  240. pps = max(getIntervalPPS(complement_interval_pps, timestamp_next_pkt),10)
  241. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps)
  242. # store end time of attack
  243. self.attack_end_utime = packets[-1].time
  244. # write attack packets to pcap
  245. pcap_path = self.write_attack_pcap(sorted(packets, key=lambda pkt: pkt.time))
  246. # return packets sorted by packet time_sec_start
  247. return len(packets), pcap_path