PortscanAttack.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import logging
  2. import csv
  3. import socket
  4. from random import shuffle, randint, choice, uniform
  5. from lea import Lea
  6. from Attack import BaseAttack
  7. from Attack.AttackParameters import Parameter as Param
  8. from Attack.AttackParameters import ParameterTypes
  9. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  10. # noinspection PyPep8
  11. from scapy.layers.inet import IP, Ether, TCP
  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 Portscan attack.
  17. :return: Ports numbers to be used as default dest ports or default open ports in Portscan attack.
  18. """
  19. ports_dst = []
  20. spamreader = csv.reader(open('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
  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 is_valid_ip_address(self,addr):
  39. """
  40. Check if the IP address family is suported.
  41. :param addr: IP address to be checked
  42. :return: Boolean
  43. """
  44. try:
  45. socket.inet_aton(addr)
  46. return True
  47. except socket.error:
  48. return False
  49. def __init__(self, statistics, pcap_file_path):
  50. """
  51. Creates a new instance of the PortscanAttack.
  52. :param statistics: A reference to the statistics class.
  53. """
  54. # Initialize attack
  55. super(PortscanAttack, self).__init__(statistics, "Portscan Attack", "Injects a nmap 'regular scan'",
  56. "Scanning/Probing")
  57. # Define allowed parameters and their type
  58. self.supported_params = {
  59. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  60. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  61. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  62. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  63. Param.PORT_OPEN: ParameterTypes.TYPE_PORT,
  64. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  65. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  66. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  67. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  68. Param.PORT_DEST_SHUFFLE: ParameterTypes.TYPE_BOOLEAN,
  69. Param.PORT_DEST_ORDER_DESC: ParameterTypes.TYPE_BOOLEAN,
  70. Param.IP_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN,
  71. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  72. Param.PORT_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN
  73. }
  74. # PARAMETERS: initialize with default values
  75. # (values are overwritten if user specifies them)
  76. most_used_ip_address = self.statistics.get_most_used_ip_address()
  77. if isinstance(most_used_ip_address, list):
  78. most_used_ip_address = most_used_ip_address[0]
  79. self.add_param_value(Param.IP_SOURCE, most_used_ip_address)
  80. self.add_param_value(Param.IP_SOURCE_RANDOMIZE, 'False')
  81. self.add_param_value(Param.MAC_SOURCE, self.statistics.get_mac_address(most_used_ip_address))
  82. random_ip_address = self.statistics.get_random_ip_address()
  83. # Aidmar
  84. while not self.is_valid_ip_address(random_ip_address):
  85. random_ip_address = self.statistics.get_random_ip_address()
  86. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  87. destination_mac = self.statistics.get_mac_address(random_ip_address)
  88. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  89. destination_mac = self.generate_random_mac_address()
  90. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  91. self.add_param_value(Param.PORT_DESTINATION, self.get_ports_from_nmap_service_dst(1000))
  92. #self.add_param_value(Param.PORT_DESTINATION, '1-1023,1720,1900,8080,56652')
  93. # Not used initial value
  94. self.add_param_value(Param.PORT_OPEN, '1,11,111,1111')
  95. self.add_param_value(Param.PORT_DEST_SHUFFLE, 'False')
  96. self.add_param_value(Param.PORT_DEST_ORDER_DESC, 'False')
  97. self.add_param_value(Param.PORT_SOURCE, randint(1024, 65535))
  98. self.add_param_value(Param.PORT_SOURCE_RANDOMIZE, 'False')
  99. self.add_param_value(Param.PACKETS_PER_SECOND,
  100. (self.statistics.get_pps_sent(most_used_ip_address) +
  101. self.statistics.get_pps_received(most_used_ip_address)) / 2)
  102. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  103. def generate_attack_pcap(self):
  104. def update_timestamp(timestamp, pps, maxdelay):
  105. """
  106. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  107. :return: Timestamp to be used for the next packet.
  108. """
  109. return timestamp + uniform(0.1 / pps, maxdelay)
  110. # Determine ports
  111. dest_ports = self.get_param_value(Param.PORT_DESTINATION)
  112. if self.get_param_value(Param.PORT_DEST_ORDER_DESC):
  113. dest_ports.reverse()
  114. elif self.get_param_value(Param.PORT_DEST_SHUFFLE):
  115. shuffle(dest_ports)
  116. if self.get_param_value(Param.PORT_SOURCE_RANDOMIZE):
  117. # Aidmar
  118. sport = randint(1, 65535)
  119. #sport = randint(0, 65535)
  120. else:
  121. sport = self.get_param_value(Param.PORT_SOURCE)
  122. # Timestamp
  123. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  124. # store start time of attack
  125. self.attack_start_utime = timestamp_next_pkt
  126. # Initialize parameters
  127. packets = []
  128. ip_source = self.get_param_value(Param.IP_SOURCE)
  129. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  130. mac_source = self.get_param_value(Param.MAC_SOURCE)
  131. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  132. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  133. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 30, 5 / pps: 15, 10 / pps: 3})
  134. maxdelay = randomdelay.random()
  135. # open ports
  136. # Aidmar
  137. ports_open = self.get_param_value(Param.PORT_OPEN)
  138. if ports_open == [1,11,111,1111]: # user did not define open ports
  139. # the ports that were already used by ip.dst (direction in) in the background traffic are open ports
  140. ports_used_by_ip_dst = None #self.statistics.process_db_query(
  141. #"SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "'")
  142. if ports_used_by_ip_dst:
  143. ports_open = ports_used_by_ip_dst
  144. print("\nPorts used by %s: %s" % (ip_destination, ports_open))
  145. else: # if no ports were retrieved from database
  146. # Take open ports from nmap-service file
  147. #ports_temp = self.get_ports_from_nmap_service_dst(100)
  148. #ports_open = ports_temp[0:randint(1,10)]
  149. # OR take open ports from the most used ports in traffic statistics
  150. ports_open = self.statistics.process_db_query(
  151. "SELECT portNumber FROM ip_ports GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT "+str(randint(1,10)))
  152. print("\nPorts retrieved from statistics: %s" % (ports_open))
  153. # in case of one open port, convert ports_open to array
  154. if not isinstance(ports_open, list):
  155. ports_open = [ports_open]
  156. # =========================================================================================================
  157. # MSS (Maximum Segment Size) for Ethernet. Allowed values [536,1500]
  158. # Aidmar
  159. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  160. if mss_dst is None:
  161. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  162. mss_src = self.statistics.get_most_used_mss(ip_source)
  163. if mss_src is None:
  164. mss_src = self.statistics.process_db_query("most_used(mssValue)")
  165. # mss = self.statistics.get_mss(ip_destination)
  166. # =========================================================================================================
  167. # Set TTL based on TTL distribution of IP address
  168. ttl_dist = self.statistics.get_ttl_distribution(ip_source)
  169. if len(ttl_dist) > 0:
  170. ttl_prob_dict = Lea.fromValFreqsDict(ttl_dist)
  171. ttl_value = ttl_prob_dict.random()
  172. else:
  173. ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  174. for dport in dest_ports:
  175. # Parameters changing each iteration
  176. if self.get_param_value(Param.IP_SOURCE_RANDOMIZE) and isinstance(ip_source, list):
  177. ip_source = choice(ip_source)
  178. # 1) Build request package
  179. request_ether = Ether(src=mac_source, dst=mac_destination)
  180. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  181. # Aidmar - random src port for each packet
  182. sport = randint(1, 65535)
  183. # Aidmar - use most used window size
  184. win_size = self.statistics.process_db_query("most_used(winSize)")
  185. request_tcp = TCP(sport=sport, dport=dport, window=win_size, flags='S', options=[('MSS', mss_src)])
  186. # =========================================================================================================
  187. request = (request_ether / request_ip / request_tcp)
  188. # first packet uses timestamp provided by attack parameter Param.INJECT_AT_TIMESTAMP
  189. if len(packets) > 0:
  190. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  191. request.time = timestamp_next_pkt
  192. packets.append(request)
  193. # 2) Build reply package
  194. if dport in ports_open: # destination port is OPEN
  195. reply_ether = Ether(src=mac_destination, dst=mac_source)
  196. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  197. #if mss_dst is None:
  198. # reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=29200)
  199. #else:
  200. reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=29200,
  201. options=[('MSS', mss_dst)])
  202. reply = (reply_ether / reply_ip / reply_tcp)
  203. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  204. reply.time = timestamp_next_pkt
  205. packets.append(reply)
  206. # requester confirms
  207. confirm_ether = request_ether
  208. confirm_ip = request_ip
  209. confirm_tcp = TCP(sport=sport, dport=dport, seq=1, window=0, flags='R')
  210. reply = (confirm_ether / confirm_ip / confirm_tcp)
  211. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  212. reply.time = timestamp_next_pkt
  213. packets.append(reply)
  214. # else: destination port is NOT OPEN -> no reply is sent by target
  215. # store end time of attack
  216. self.attack_end_utime = packets[-1].time
  217. # write attack packets to pcap
  218. pcap_path = self.write_attack_pcap(sorted(packets, key=lambda pkt: pkt.time))
  219. # return packets sorted by packet time_sec_start
  220. return len(packets), pcap_path