PortscanAttack.py 14 KB

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