PortscanAttack.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import csv
  2. import logging
  3. from random import shuffle, randint, choice
  4. from lea import Lea
  5. from scapy.layers.inet import IP, Ether, TCP
  6. from Attack import BaseAttack
  7. from Attack.AttackParameters import Parameter as Param
  8. from Attack.AttackParameters import ParameterTypes
  9. import ID2TLib.Utility as Util
  10. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  11. # noinspection PyPep8
  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.update({
  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. self.add_param_value(Param.IP_SOURCE, most_used_ip_address)
  48. self.add_param_value(Param.IP_SOURCE_RANDOMIZE, 'False')
  49. self.add_param_value(Param.MAC_SOURCE, self.statistics.get_mac_address(most_used_ip_address))
  50. random_ip_address = self.statistics.get_random_ip_address()
  51. # ip-dst should be valid and not equal to ip.src
  52. while not self.is_valid_ip_address(random_ip_address) or random_ip_address==most_used_ip_address:
  53. random_ip_address = self.statistics.get_random_ip_address()
  54. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  55. destination_mac = self.statistics.get_mac_address(random_ip_address)
  56. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  57. destination_mac = self.generate_random_mac_address()
  58. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  59. self.add_param_value(Param.PORT_DESTINATION, self.get_ports_from_nmap_service_dst(1000))
  60. self.add_param_value(Param.PORT_OPEN, '1')
  61. self.add_param_value(Param.PORT_DEST_SHUFFLE, 'False')
  62. self.add_param_value(Param.PORT_DEST_ORDER_DESC, 'False')
  63. self.add_param_value(Param.PORT_SOURCE, randint(1024, 65535))
  64. self.add_param_value(Param.PORT_SOURCE_RANDOMIZE, 'False')
  65. self.add_param_value(Param.PACKETS_PER_SECOND,
  66. (self.statistics.get_pps_sent(most_used_ip_address) +
  67. self.statistics.get_pps_received(most_used_ip_address)) / 2)
  68. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  69. def get_ports_from_nmap_service_dst(self, ports_num):
  70. """
  71. Read the most ports_num frequently open ports from nmap-service-tcp file to be used in the port scan.
  72. :return: Ports numbers to be used as default destination ports or default open ports in the port scan.
  73. """
  74. ports_dst = []
  75. file = open(Util.RESOURCE_DIR + 'nmap-services-tcp.csv', 'rt')
  76. spamreader = csv.reader(file, delimiter=',')
  77. for count in range(ports_num):
  78. # escape first row (header)
  79. next(spamreader)
  80. # save ports numbers
  81. ports_dst.append(next(spamreader)[0])
  82. file.close()
  83. # shuffle ports numbers partially
  84. if (ports_num == 1000): # used for port.dst
  85. temp_array = [[0 for i in range(10)] for i in range(100)]
  86. port_dst_shuffled = []
  87. for count in range(0, 10):
  88. temp_array[count] = ports_dst[count * 100:(count + 1) * 100]
  89. shuffle(temp_array[count])
  90. port_dst_shuffled += temp_array[count]
  91. else: # used for port.open
  92. shuffle(ports_dst)
  93. port_dst_shuffled = ports_dst
  94. return port_dst_shuffled
  95. def generate_attack_packets(self):
  96. mac_source = self.get_param_value(Param.MAC_SOURCE)
  97. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  98. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  99. # Calculate complement packet rates of the background traffic for each interval
  100. complement_interval_pps = self.statistics.calculate_complement_packet_rates(pps)
  101. # Determine ports
  102. dest_ports = self.get_param_value(Param.PORT_DESTINATION)
  103. if self.get_param_value(Param.PORT_DEST_ORDER_DESC):
  104. dest_ports.reverse()
  105. elif self.get_param_value(Param.PORT_DEST_SHUFFLE):
  106. shuffle(dest_ports)
  107. if self.get_param_value(Param.PORT_SOURCE_RANDOMIZE):
  108. sport = randint(1, 65535)
  109. else:
  110. sport = self.get_param_value(Param.PORT_SOURCE)
  111. # Timestamp
  112. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  113. # store start time of attack
  114. self.attack_start_utime = timestamp_next_pkt
  115. timestamp_prv_reply, timestamp_confirm = 0,0
  116. # Initialize parameters
  117. self.packets = []
  118. ip_source = self.get_param_value(Param.IP_SOURCE)
  119. if isinstance(ip_source, list):
  120. ip_source = ip_source[0]
  121. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  122. if isinstance(ip_destination, list):
  123. ip_destination = ip_destination[0]
  124. # Check ip.src == ip.dst
  125. self.ip_src_dst_equal_check(ip_source, ip_destination)
  126. # Select open ports
  127. ports_open = self.get_param_value(Param.PORT_OPEN)
  128. if ports_open == 1: # user did not specify open ports
  129. # the ports that were already used by ip.dst (direction in) in the background traffic are open ports
  130. ports_used_by_ip_dst = self.statistics.process_db_query(
  131. "SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "'")
  132. if ports_used_by_ip_dst:
  133. ports_open = ports_used_by_ip_dst
  134. else: # if no ports were retrieved from database
  135. # Take open ports from nmap-service file
  136. #ports_temp = self.get_ports_from_nmap_service_dst(100)
  137. #ports_open = ports_temp[0:randint(1,10)]
  138. # OR take open ports from the most used ports in traffic statistics
  139. ports_open = self.statistics.process_db_query(
  140. "SELECT portNumber FROM ip_ports GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT "+str(randint(1,10)))
  141. # in case of one open port, convert ports_open to array
  142. if not isinstance(ports_open, list):
  143. ports_open = [ports_open]
  144. # Set MSS (Maximum Segment Size) based on MSS distribution of IP address
  145. source_mss_dist = self.statistics.get_mss_distribution(ip_source)
  146. if len(source_mss_dist) > 0:
  147. source_mss_prob_dict = Lea.fromValFreqsDict(source_mss_dist)
  148. source_mss_value = source_mss_prob_dict.random()
  149. else:
  150. source_mss_value = Util.handle_most_used_outputs(self.statistics.process_db_query("most_used(mssValue)"))
  151. destination_mss_dist = self.statistics.get_mss_distribution(ip_destination)
  152. if len(destination_mss_dist) > 0:
  153. destination_mss_prob_dict = Lea.fromValFreqsDict(destination_mss_dist)
  154. destination_mss_value = destination_mss_prob_dict.random()
  155. else:
  156. destination_mss_value = Util.handle_most_used_outputs(self.statistics.process_db_query("most_used(mssValue)"))
  157. # Set TTL based on TTL distribution of IP address
  158. source_ttl_dist = self.statistics.get_ttl_distribution(ip_source)
  159. if len(source_ttl_dist) > 0:
  160. source_ttl_prob_dict = Lea.fromValFreqsDict(source_ttl_dist)
  161. source_ttl_value = source_ttl_prob_dict.random()
  162. else:
  163. source_ttl_value = Util.handle_most_used_outputs(self.statistics.process_db_query("most_used(ttlValue)"))
  164. destination_ttl_dist = self.statistics.get_ttl_distribution(ip_destination)
  165. if len(destination_ttl_dist) > 0:
  166. destination_ttl_prob_dict = Lea.fromValFreqsDict(destination_ttl_dist)
  167. destination_ttl_value = destination_ttl_prob_dict.random()
  168. else:
  169. destination_ttl_value = Util.handle_most_used_outputs(self.statistics.process_db_query("most_used(ttlValue)"))
  170. # Set Window Size based on Window Size distribution of IP address
  171. source_win_dist = self.statistics.get_win_distribution(ip_source)
  172. if len(source_win_dist) > 0:
  173. source_win_prob_dict = Lea.fromValFreqsDict(source_win_dist)
  174. source_win_value = source_win_prob_dict.random()
  175. else:
  176. source_win_value = Util.handle_most_used_outputs(self.statistics.process_db_query("most_used(winSize)"))
  177. destination_win_dist = self.statistics.get_win_distribution(ip_destination)
  178. if len(destination_win_dist) > 0:
  179. destination_win_prob_dict = Lea.fromValFreqsDict(destination_win_dist)
  180. destination_win_value = destination_win_prob_dict.random()
  181. else:
  182. destination_win_value = Util.handle_most_used_outputs(self.statistics.process_db_query("most_used(winSize)"))
  183. minDelay,maxDelay = self.get_reply_delay(ip_destination)
  184. for dport in dest_ports:
  185. # Parameters changing each iteration
  186. if self.get_param_value(Param.IP_SOURCE_RANDOMIZE) and isinstance(ip_source, list):
  187. ip_source = choice(ip_source)
  188. # 1) Build request package
  189. request_ether = Ether(src=mac_source, dst=mac_destination)
  190. request_ip = IP(src=ip_source, dst=ip_destination, ttl=source_ttl_value)
  191. # Random src port for each packet
  192. sport = randint(1, 65535)
  193. request_tcp = TCP(sport=sport, dport=dport, window= source_win_value, flags='S', options=[('MSS', source_mss_value)])
  194. request = (request_ether / request_ip / request_tcp)
  195. request.time = timestamp_next_pkt
  196. # Append request
  197. self.packets.append(request)
  198. # 2) Build reply (for open ports) package
  199. if dport in ports_open: # destination port is OPEN
  200. reply_ether = Ether(src=mac_destination, dst=mac_source)
  201. reply_ip = IP(src=ip_destination, dst=ip_source, ttl=destination_ttl_value, flags='DF')
  202. reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=destination_win_value,
  203. options=[('MSS', destination_mss_value)])
  204. reply = (reply_ether / reply_ip / reply_tcp)
  205. timestamp_reply = Util.update_timestamp(timestamp_next_pkt,pps,minDelay)
  206. while (timestamp_reply <= timestamp_prv_reply):
  207. timestamp_reply = Util.update_timestamp(timestamp_prv_reply,pps,minDelay)
  208. timestamp_prv_reply = timestamp_reply
  209. reply.time = timestamp_reply
  210. self.packets.append(reply)
  211. # requester confirms
  212. confirm_ether = request_ether
  213. confirm_ip = request_ip
  214. confirm_tcp = TCP(sport=sport, dport=dport, seq=1, window=0, flags='R')
  215. confirm = (confirm_ether / confirm_ip / confirm_tcp)
  216. timestamp_confirm = Util.update_timestamp(timestamp_reply,pps,minDelay)
  217. confirm.time = timestamp_confirm
  218. self.packets.append(confirm)
  219. # else: destination port is NOT OPEN -> no reply is sent by target
  220. pps = max(Util.get_interval_pps(complement_interval_pps, timestamp_next_pkt), 10)
  221. timestamp_next_pkt = Util.update_timestamp(timestamp_next_pkt, pps)
  222. def generate_attack_pcap(self):
  223. # store end time of attack
  224. self.attack_end_utime = self.packets[-1].time
  225. # write attack packets to pcap
  226. pcap_path = self.write_attack_pcap(sorted(self.packets, key=lambda pkt: pkt.time))
  227. # return packets sorted by packet time_sec_start
  228. return len(self.packets), pcap_path